7

Solidity 0.4.25.

Consider this code

contract A{
    function test() public view returns (bytes){
        bytes memory output = abi.encodePacked(bytes32(1));
        return output;
    }
}

The returned data is:

0000000000000000000000000000000000000000000000000000000000000020 0000000000000000000000000000000000000000000000000000000000000020 0000000000000000000000000000000000000000000000000000000000000001

If you look at how bytes are laid out in memory then the first bytes32 is the length of the bytes (in numbers of bytes, e.g. a bytes with 32 bytes length has 0x20 on the first bytes32 padded left). However apparently this returndata has TWO 0x20's in it. If you expand the length of the returned bytes the first bytes32 still stays 0x20.

I don't get why this is. What is the purpose of this 0x20? Is this a solidity bug or does it have any purpose?

The expected returndata would be:

0000000000000000000000000000000000000000000000000000000000000020 0000000000000000000000000000000000000000000000000000000000000001

1
  • Just a thought: might have to do that new solidity might implement multi-level arrays soon and that this returndata hence has to do with the layout of the array. (It still doesn't make sense that there is a 0x20 = 32 on here though)
    – JBrouwer
    Oct 14, 2018 at 17:49

1 Answer 1

7

The ABI encoding includes an offset to the start of data.

The first 0x20 is the offset to the start of data as described in this example: https://docs.soliditylang.org/en/develop/abi-spec.html#use-of-dynamic-types In the example look at:

0x0000000000000000000000000000000000000000000000000000000000000080 (offset to start of data part of second parameter, 4*32 bytes, exactly the size of the head part)

After the offset, you're correct that the next 32 bytes will be the length of the data, and then the data.

2
  • Thank you, I was pretty sure I missed something in the documentation! =)
    – JBrouwer
    Oct 15, 2018 at 7:53
  • Thanks for all your open source work =)
    – eth
    May 26 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.