My goal is to encode two strings into bytes
with this function:
function encode(string memory _address1, string memory _address2) public returns (bytes memory) {
encoded = abi.encodePacked(_address1, _address2);
return encoded;
}
And then I want to decode the bytes back into individual strings:
function decode(bytes memory _encoded) public pure returns (string memory x, string memory y) {
return abi.decode(_encoded, (string, string));
}
However, when I feed the bytes from the encode
function, I get the following error:
call to ERC721ReceiverMock.decode errored: VM error: revert.
Best Answer
For the
decode
function it is required that the data is ABI encoded (the details for this can be found in the Solidity docs). ButencodePacked
does not do so, it actually performs a packed encoding, which omits meta information about the encoded data (e.g. the length of the strings). More on this can also be found in the Solidity docs.To encode your data in a way that follows the ABI spec you need use
abi.encode
(instead ofabi.encodePacked
). So your code would change toEdit: Here the link to the docs for
abi.encode