I've a couple of questions.

  1. mload function returns the data that resides on the address we pass to mload. Is this correct ?

  2. add function is used to give us the address from 0 to whatever we pass. add(arr, 64) would return the address from arr + 64 bytes. correct. ?

  3. I want to achieve same things with storage variables (x_slot and x_offset).. I have the following code.

uint[] storageArr;
    function assembly2() public view returns (uint a, uint b, uint c) {
        assembly {
            a := sload(0)
            b := sload(32)
            c := sload(64)

This returns {3, 0, 0,}. The first one(slot) is 3, since it stores the length of the array. why is the second and third one 0 ?


Due to their unpredictable size, dynamically-sized array types use a Keccak-256 hash computation to find the starting position of the array data.

So in your example:

  • The position of storageArr[0] is at keccak256(uint256(0)) + 0
  • The position of storageArr[1] is at keccak256(uint256(0)) + 1
  • The position of storageArr[2] is at keccak256(uint256(0)) + 2

Here is how you can put it into code:

function assembly2() public view returns (uint a, uint b, uint c) {
    uint index = uint(keccak256(abi.encode(uint(0))));
    assembly {
        a := sload(add(index, 0))
        b := sload(add(index, 1))
        c := sload(add(index, 2))
  • how would I write that in assembly language ? if you could change the code to reflect it, that would be great Sep 30 '20 at 9:17
  • @NikaKurashvili: I think that sload(keccak256(storageArr, n)) for n in [0, 1, 2] might work. Sep 30 '20 at 9:19
  • sload(keccak256(storageArr,0)) returns error: Only local variables are supported. To access storage variables, use the _slot and _offset suffixes. Sep 30 '20 at 9:25
  • @NikaKurashvili: OK, give me a few minutes to see if I can find it. Sep 30 '20 at 9:26
  • @NikaKurashvili: See updated answer. BTW, note that your view function changes a state variable. You should basically move that part out into a different function. Sep 30 '20 at 9:35

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.