1

Suppose that you define an immutable variable like this:

contract Contract {
    uint256 public immutable foo;
    uint256 public bar;

    constructor() {
        foo = 50;
    }

Will bar be the first storage variable of this contract? Or foo?

My hunch is that the answer is that bar is indeed the first, because foo will get inlined in the runtime bytecode.

1
  • @SolidityLearner I don't think that that's right. But I am sot sure. Commented Mar 3, 2023 at 10:07

1 Answer 1

3

You are correct. The bar in this example will be stored in slot 0. The reason for this is because the compiler doesn't reserve a storage slot for constant/immutable variables, rather than copying the value of that variable everywhere in the code where that particular value is used.

That's why constant/immutable variables are gas efficient, as they are not stored directly in the storage.

You can also test it yourself by deploying the contract on any testnet and then use web3 library to access the storage slots.

await web3.eth.getStorageAt("ContractAddress", 0)

Will return you the value that is stored in the first slot.

await web3.eth.abi.decodeParameter("uint256", "ResultFromGetStorageAt")

Then you can use decodeParameter to check the actual value stored in it.

If you try to run getStorageAt("ContractAddress", 1) you will notice it's empty. That's because as we said earlier, constrants aren't saved in the storage slots but in the contract code itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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