3

The Solidity docs say this about dynamic calldata arrays:

For dynamic calldata arrays, you can access their calldata offset (in bytes) and length (number of elements) using x.offset and x.length

But they don't offer any example.

What does an "offset" mean in this context?

2 Answers 2

3

offset is the position in the calldata where the actual data of the array starts, i.e. where the first array element is located. Let's take an example:

contract Foo {
    function getOffset(uint256[] calldata arr) external pure returns (uint256 offset) {
        assembly {
            offset := arr.offset
        }
    }
}

Passing [1,2,3] as an input to this function would return 68:

Call to Foo.getOffset

Now, let's define another parameter in the function, before arr:

function getOffset (uint256 param, uint256[] calldata arr) external pure returns (uint256 offset) {
    assembly {
        offset := arr.offset
    }
}

Passing 0,[1,2,3] as an input would now return 100 instead of 68, because there is another EVM word that sits before arr, and EVM words are 32 byte long:

Second call to Foo.getOffset

2

Let's say we have this function:

contract Foo {
    function getOffset(uint256[] calldata arr) external pure returns (uint256 offset) {
        assembly {
            offset := arr.offset
        }
    }
}

Passing [1, 2, 3] as an input to this function would return 68.
but how it calculated 68?

Based on the docs we can find encoded argument, which for this input and function argument it will be:

0x1fe457d7                                                         - function signature
  0000000000000000000000000000000000000000000000000000000000000020 - offset of [1,2,3]
  0000000000000000000000000000000000000000000000000000000000000003 - count for [1,2,3]
  0000000000000000000000000000000000000000000000000000000000000001 - encoding of 1
  0000000000000000000000000000000000000000000000000000000000000002 - encoding of 2
  0000000000000000000000000000000000000000000000000000000000000003 - encoding of 3

If you count number of bytes from the function signature line (4 bytes) to the beginning of the line encoding of 1 where the actual data of the array starts, you will find out there are 68 bytes.

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.