1

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?

1

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.

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.