Solidity String Encoding – How to Encode Strings into Bytes and Decode Them Back

solidity

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). But encodePacked 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 of abi.encodePacked). So your code would change to

function encode(string memory _address1, string memory _address2) public  returns (bytes memory) {
   encoded = abi.encode(_address1, _address2);
   return encoded;
}

Edit: Here the link to the docs for abi.encode

Related Topic