Decoding and Encoding

I am trying to understand how to handle the encoding and decoding of the abi library provided by solidity.

I have tried to encode a message and then decode it. But it always gives me error. I have removed one of the parameters that were in string because maybe it had to be encoded to bytes too. But using the address type also fails me.

Where am I going wrong?


contract EncodeDecode {


        function encode(address account, uint number) public pure returns(bytes memory) {

            return abi.encodePacked(account, number);
        }

         function decode(bytes memory data) public pure returns(address, uint) {

             (address account, uint number ) = abi.decode(data, (address, uint));
            
            return (account, number);
        }


}

Here’s a little fix

contract EncodeDecode{
    function encode(address _account, uint _number) public pure returns (bytes memory) {
        return (abi.encode(_account, _number));
    }

function decode(bytes memory data) public pure returns (address _account, uint _number) {
        (_account, _number) = abi.decode(data, (address, uint));            
    }
}
1 Like

What? !
I have never seen it done this way before.
a return without return
crazy…
was there the problem @qudusayo ?

Changing this to abi.encode

What is the essential difference between the two methods?

See the Solidity documentation for 0.5 breaking changes for the difference between abi.encode and abi.encodePacked

The ABI encoder now properly pads byte arrays and strings from calldata (msg.data and external function parameters) when used in external function calls and in abi.encode . For unpadded encoding, use abi.encodePacked .

abi.encodePacked is a non-standard packed mode

Reference Here

Thanks for the info I already knew but I don’t understand very well why in my case it works with encode and doesn’t work with encodePacked .