4

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 Answer 1

6

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.
1
  • 1
    It is simple. But, result memory variable didn't return as real value. It is result memory variable initialize value 1 in constructor(), when I assign like this and console log with hardhat log result like this 5973652239065808857055946470512512878469198127164779725056. Why? Compiler version is 0.8.4. Thank you for interest. Commented Jan 27, 2022 at 14:41

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.