2

What is the immutable keyword in Solidity and how do I use it?

1

The immutable keyword was added to Solidity in 0.6.5.

State variables can be marked immutable which causes them to be read-only, but assignable in the constructor. The value will be stored directly in the code.

From the docs:

Variables declared as immutable are a bit less restricted than those declared as constant: Immutable variables can be assigned an arbitrary value in the constructor of the contract or at the point of their declaration. They cannot be read during construction time and can only be assigned once.

An example code snippet is as follows:

pragma solidity ^0.6.5;

contract TestImmutable {
    uint256 public immutable a;

    // This is a valid constructor
    constructor (uint256 _a) public {
        a = _a;
    }

    // This is invalid and will not compile
    function setA (uint256 _a) public {
        a = _a;
    }
}

It is important to note that the contract creation code generated by the compiler will modify the contract’s runtime code before it is returned by replacing all references to immutables by the values assigned to the them. This is important if you are comparing the runtime code generated by the compiler with the one actually stored in the blockchain.

| improve this answer | |
  • Great post. The curious reader can take a look at Uniswap v2's Router02 contract, which makes use of the immutable keyword. – Paul Razvan Berg Jul 8 at 10:59
  • Etherscan verification: would I need to verify separately two identical contracts deployed with a different construction argument used for immutable assignment? – goodvibration Aug 27 at 14:05
  • No, seems that it requires two different verifications. – goodvibration Aug 27 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.