TExcelTAD
Home › Solidity › immutable & constant

immutable & constant

Many values in a contract never change: a maximum supply, a fee denominator, the token a vault accepts, the address of the deployer. Storing them in normal state variables wastes gas on every read. Solidity offers two cheaper alternatives.

Keyword Value fixed at Stored in Read cost
constant compile time (a literal or pure expression) inlined into the bytecode like a literal (~3 gas)
immutable deployment (assigned in the constructor) written into the deployed bytecode like a literal (~3 gas)
normal state variable any time storage 2,100 cold / 100 warm

constant

A constant must be assigned where it's declared, with a value the compiler can compute. By convention constants use UPPER_CASE:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    uint256 public constant MAX_SUPPLY = 10_000;
    uint256 public constant BPS = 10_000;                    // 100% in basis points
    uint256 public constant FEE_BPS = 250;                   // 2.5%
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    string public constant NAME = "Ticket";

    function fee(uint256 amount) public pure returns (uint256) {
        return amount * FEE_BPS / BPS;                       // constants are usable in pure code
    }

    function main() external pure {
        console.log(NAME, "max supply:", MAX_SUPPLY);
        console.log("fee on 2000:", fee(2000));
        console.logBytes32(MINTER_ROLE);
    }
}
Ticket max supply: 10000
fee on 2000: 50
0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6

keccak256("MINTER_ROLE") is computed at compile time, so the role id costs nothing to use.

immutable

An immutable is assigned once, in the constructor (or at its declaration), and can't change afterwards. It's perfect for configuration that depends on deployment: the owner, a linked contract's address, a start time.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Vesting {
    address public immutable beneficiary;
    uint256 public immutable start;
    uint256 public immutable duration;

    constructor(address beneficiary_, uint256 duration_) {
        beneficiary = beneficiary_;
        start = block.timestamp;
        duration = duration_;
    }

    function vestedPercent(uint256 at) external view returns (uint256) {
        if (at <= start) return 0;
        if (at >= start + duration) return 100;
        return (at - start) * 100 / duration;
    }

    // function change() external { start = 0; }   // compile error: immutable
}

contract Main {
    function main() external {
        Vesting v = new Vesting(address(0xBEEF), 100 days);
        console.log("beneficiary:", v.beneficiary());
        console.log("after 25 days :", v.vestedPercent(block.timestamp + 25 days), "%");
        console.log("after 200 days:", v.vestedPercent(block.timestamp + 200 days), "%");
    }
}
beneficiary: 0x000000000000000000000000000000000000bEEF
after 25 days : 25 %
after 200 days: 100 %

Measuring the difference

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    uint256 public constant RATE_CONST = 7;
    uint256 public immutable rateImmutable = 7;
    uint256 public rateStorage;          // a storage slot not touched yet in this transaction

    function main() external view {
        uint256 g;
        uint256 x;

        g = gasleft();
        x = RATE_CONST;
        console.log("constant :", g - gasleft());

        g = gasleft();
        x = rateImmutable;
        console.log("immutable:", g - gasleft());

        g = gasleft();
        x = rateStorage;
        console.log("storage  :", g - gasleft(), x);
    }
}
constant : 77
immutable: 74
storage  : 2173 0

The storage read pays the 2,100 gas "cold slot" price for the first access in a transaction (whatever value the slot holds; here it was never set, so it's 0); the other two are just a value pushed onto the stack.

Rules and limits

  • constant works for value types and string/bytes; immutable only for value types (integers, addresses, bytes32, enums …).
  • An immutable can't be read inside the constructor before it's assigned.
  • Both can be public (with a getter) like any state variable.
  • Neither takes up a storage slot, so they're not affected by proxy storage layouts. That also means a contract behind a proxy reads the implementation's immutables, a subtle point covered in Proxies.

When to use which

  • Known when you write the code → constant.
  • Known only at deployment, never changes → immutable.
  • Might ever need to change → normal state variable, with an access-controlled setter that emits an event.

Test yourself

Where may an immutable variable be assigned?

  1. Anywhere in the contract
  2. Only in the constructor or at its declaration
  3. Only by the owner
  4. Never; it's always zero

Which declaration compiles?

  1. uint256 constant START = block.timestamp;
  2. uint256 immutable START = block.timestamp;
  3. string immutable NAME = "x";
  4. uint256 constant X;

Why are constants and immutables cheaper to read than state variables?

  1. They are cached by nodes
  2. Their values are part of the bytecode, so no storage read is needed
  3. They are stored in memory
  4. They are free in view functions