Contract Development – How to Read High-Level Storage Variable from Inline Assembly

assemblycontract-developmentstorage

This code does not compile:

pragma solidity >=0.8.0;

contract MyContract {
    uint256 public foo = 314;

    function myFunction() external view returns (uint256 result) {
        assembly {
            result := foo
        }
    }
}

This error is thrown:

TypeError: only local variables are supported. To access storage variables, use the ".slot" and ".offset" suffixes.

I modified my code like this:

result := foo.slot

But the result I got was "1" instead of "314". How can I get access to this storage variable in inline assembly?

Best Answer

See the Access to External Variables, Functions and Libraries section in the docs.

The solution is to use the sload function and pass the slot as the only argument:

assembly {
    result := sload(foo.slot)
}

Caveats:

  • Be careful if the value you're reading does not have a span of exactly 256 bits (e.g. address). You cannot assume that the bits not part of the encoding will be zero.
  • For dynamic data types like arrays, you have to use .offset and .length besides .slot.
Related Topic