Content
@
https://ethereum.org
0 reply
0 recast
0 reaction
Trashpirate
@trashpirate.eth
Have you been using abi.encode() but you actually are not sure what really happens under the hood? Here is a hopefully straight forward explanation what abi.encode() really does.
1 reply
0 recast
0 reaction
Trashpirate
@trashpirate.eth
When you use abi.encode() the following operations take place: 1. Encoding: Each data type is converted into a binary format 2. Padding: The binary data is padded to encode fixed-size data types (such as uint256, address, bool, etc.) to 32-byte (256-bit) chunks and dynamic-sized data types by first encoding the length of the data followed by the actual data (like fixed-sized data) 3. Concatenation: The encoded values are concatenated to a single byte array.
1 reply
0 recast
0 reaction
Trashpirate
@trashpirate.eth
Take the following example:
1 reply
0 recast
0 reaction
Trashpirate
@trashpirate.eth
Breakdown of the Encoding Process: 1. uint256 num = 42: 42 in hexadecimal is 0x2A. ABI encoding requires a 32-byte representation: 0x000000000000000000000000000000000000000000000000000000000000002A. 2. address addr = 0x1234567890123456789012345678901234567890: The address is already a 20-byte value. It is left-padded to 32 bytes: 0x0000000000000000000000001234567890123456789012345678901234567890.
1 reply
0 recast
0 reaction
Trashpirate
@trashpirate.eth
3. string text = "Hello, ABI": First, the length of the string is encoded as a 32-byte value: 0x000000000000000000000000000000000000000000000000000000000000000A (10 bytes for "Hello, ABI"). The ASCII encoding of "Hello, ABI" is: 0x48656C6C6F2C20414249. This is right-padded to 32 bytes: 0x48656C6C6F2C2041424900000000000000000000000000000000000000000000. 4. Concatenation: 0x000000000000000000000000000000000000000000000000000000000000002A0000000000000000000000001234567890123456789012345678901234567890000000000000000000000000000000000000000000000000000000000000000A48656C6C6F2C2041424900000000000000000000000000000000000000000000
2 replies
0 recast
0 reaction
Trashpirate
@trashpirate.eth
Now what does abi.encodePacked do? Well, it just doesn't do the padding - so use it with caution if you need to decode the data. Because strings are easily reconstructed from bytes without padding, you can use abi.encodePacked() to concatenate strings.
0 reply
0 recast
0 reaction
Trashpirate
@trashpirate.eth
If you find this useful, FOLLOW me! Give this a LIKE, REPOST, or a COMMENT - much appreciated ✨
0 reply
0 recast
0 reaction