Skip to content

Commit

Permalink
Merge pull request #818 from smallfu6/feature/optimize-abi-encode
Browse files Browse the repository at this point in the history
Closes #782:  optimize ABI encoding
  • Loading branch information
AmazingAng authored Oct 19, 2024
2 parents c19151d + bca1d01 commit b423ea2
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion 27_ABIEncode/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,19 @@ function encode() public view returns(bytes memory result) {
}
```

编码的结果为`0x000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000007a58c0be72be218b41c608b7fe7c5bb630736c7100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000043078414100000000000000000000000000000000000000000000000000000000`,由于`abi.encode`将每个数据都填充为32字节,中间有很多`0`
编码的结果为`0x000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000007a58c0be72be218b41c608b7fe7c5bb630736c7100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000043078414100000000000000000000000000000000000000000000000000000000`,详细解释下编码的细节:

```
000000000000000000000000000000000000000000000000000000000000000a // x
0000000000000000000000007a58c0be72be218b41c608b7fe7c5bb630736c71 // addr
00000000000000000000000000000000000000000000000000000000000000a0 // name 参数的偏移量
0000000000000000000000000000000000000000000000000000000000000005 // array[0]
0000000000000000000000000000000000000000000000000000000000000006 // array[1]
0000000000000000000000000000000000000000000000000000000000000004 // name 参数的长度为4字节
3078414100000000000000000000000000000000000000000000000000000000 // name
```

其中 `name` 参数被转换为UTF-8的字节值 `0x30784141`,在 abi 编码规范中,string 属于动态类型 ,动态类型的参数需要借助偏移量进行编码,可以参考[动态类型的使用](https://learnblockchain.cn/docs/solidity/abi-spec.html#id9)。由于 abi.encode 会将每个参与编码的参数元素(包括偏移量,长度)都填充为32字节(evm字长为32字节),所以可以看到编码后的数据中有很多填充的 0 。

### `abi.encodePacked`

Expand Down

0 comments on commit b423ea2

Please sign in to comment.