🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Constants and Immutable

Constants and immutable variables are values that cannot change once they are set. A constant is fixed in the code itself, and an immutable value is fixed when the contract is created.

A constant is fixed where it is declared

The FEE constant is set to 25 in its declaration line. Nothing in the contract can change it later.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract FeeBox {
    uint256 public constant FEE = 25;

    function getFee() public returns (uint256) {
        return FEE;
    }
}

An immutable value is set once in the constructor

Here is a first look at a constructor. It is a special function that runs once when the contract is created, and it stores the limit it is given.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract LimitBox {
    uint256 public immutable limit;

    constructor(uint256 startingLimit) {
        limit = startingLimit;
    }
}

One contract can use a constant and an immutable together

The shop limit MAX_ITEMS is the same for every shop. The shop id is chosen once for each shop when it is created.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract ShopRules {
    uint256 public constant MAX_ITEMS = 10;
    uint256 public immutable shopId;

    constructor(uint256 chosenId) {
        shopId = chosenId;
    }
}

Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract TicketSale {
    uint256 public constant TICKET_PRICE = 100;
    uint256 public immutable saleLimit;

    constructor(uint256 limit) {
        saleLimit = limit;
    }

    function totalForTwo() public returns (uint256) {
        return TICKET_PRICE * 2;
    }
}

Key points

  • Constant: a constant variable gets its value where it is declared, right in the code.
  • Fixed forever: no function can change a constant after the code is written.
  • Immutable: an immutable variable gets its value once, when the contract is created.
  • Constructor: a constructor is a special function that runs once when the contract is created.
  • Per contract: two contracts created from the same code can hold different immutable values.

In this example, the ticket price is a constant fixed at 100 in the code. The sale limit is immutable, so the constructor stores the 500 it is given at creation, and totalForTwo uses the constant price to work out the cost of two tickets.

Note

constant names are often written in capital letters, like MAX_ITEMS, so readers spot them fast.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

When does an immutable variable get its value?