Chapter 1: Elementary

Lesson 3: Mutable variables

A smart contract is not much different from a regular program. It takes certain inputs, operates on them and returns an output. Any operation may also require reading other data from the memory or storage.

For doing operations on data, we usually need to have variables whose value will be changed by the code in the contract.

These variables, which can be updated but are still stored on the blockchain are known as mutable variables.

At this point, new students often ask how you can store something mutable on an immutable blockchain. The answer is that what remains immutable is the history of how that variable’s value changed over time. But only the latest value is actually considered by the contract to be the true value of the variable.

For example, if you had USD 100 at the beginning of the month and spent USD 40 by the end of it then the bank will have a clear transaction history which you cannot change even though you can certainly change your current balance by depositing or withdrawing more money. In this example your current balance is a mutable variable but the balance-sheet itself is immutable.

To declare a mutable variable, we need to pay attention to three factors:

  • Variable name: This is the identifier of the variable to be used by various operators later in the contract.
  • Variable type: Choose the appropriate type of the variable. Such as Uint128 for amounts, String for names, ByStr20 for addresses etc.
  • Variable value: We may choose to declare a variable with or without an initial value.
  • The format for the mutable variable declaration might slightly vary depending on the variable type and variable value. You can access the list of the most important permutations in the variable declarations in the Cheat Sheet in the Task section below. For now, let’s look at the format for a simple mutable variable that will contain a text/string value.

    We look at an example for which the VariableType is String.

    The important point to know is that in the smart contract security, changing the value of a mutable variable is a very important step and if done wrong, such a change could inadvertently result in major security vulnerabilities. We’ll see later how that issue can be handled in a methodical way in Scilla.

    We have a task for you!

    Let’s start with having a simple variable that stores the name of a user. Declare a variable with following details:

  • Variable name: username
  • Variable type: String
  • Variable value: Alice
  • Your Workspace

    Show Solution

    Solution

    1

    2

    3

    4

    5

    6

    scilla_version 0
    contract SocialMediaPayment (owner: ByStr20)
    (* Start typing from the line below. *)
    field username: String = "Alice"
    scilla_version 0
    
    contract SocialMediaPayment (owner: ByStr20)
    
    (* Start typing from the line below. *)
    1
    2
    3
    4
    5