kasoqian

kasoqian

区块链步道师,传播区块链技术

WTF 燃气优化

WTF Gas 优化#

Solidity gas 优化技术,使用 Foundry。总结写 Solidity 智能合约更省 gas 的技巧。

大纲#

1. 使用 constant 和 immutable

2. 使用 calldata 而非 memory

3. 使用 Bitmap

4. 使用 unchecked

5. 使用 uint256 而非 uint8

6. 使用自定义错误而非 require/assert

7. 使用局部变量而非存储

8. 使用 clone2 而非 new/create2

9. 打包存储槽

1. 使用 constant 和 immutable#

代码 | 文章

测试

forge test --contracts 01_Constant/Constant.t.sol --gas-report

Gas 报告

函数名称Gas 成本
varConstant183
varImmutable161 ✅
variable2305

2. 使用 calldata 而非 memory#

代码 | 文章

测试

forge test --contracts 02_CalldataAndMemory/CalldataAndMemory.T.sol --gas-report

Gas 报告

函数名称Gas 成本
writeByCalldata67905 ✅
writeByMemory68456

3. 使用 Bitmap#

代码 | 文章

测试

forge test --contracts 03_Bitmap/Bitmap.T.sol --gas-report

Gas 报告

函数名称Gas 成本
setDataWithBitmap22366 ✅
setDataWithBoolArray35729

4. 使用 unchecked#

代码 | 文章

测试

forge test --contracts 04_unchecked/Unchecked.T.sol --gas-report

Gas 报告

函数名称Gas 成本
forNormal1910309
forUnckecked570287 ✅

5. 使用 uint256 而非 uint8#

代码 | 文章

测试

forge test --contracts 05_uint/Uint.T.sol --gas-report

Gas 报告

函数名称Gas 成本
read Uint82379
read Uint1282465
read Uint2562317 ✅
set Uint85355
set Uint1285358
set Uint2565322 ✅

6. 使用自定义错误而非 require/assert#

代码 | 文章

测试

forge test --contracts 06_Error/Error.T.sol --gas-report

Gas 报告

错误名称Gas 成本
Assert180
Require268
Revert164 ✅

7. 使用局部变量而非存储#

代码 | 文章

测试

forge test --contracts 07_LocalData/LocalData.T.sol --gas-report

Gas 报告

数据类型Gas 成本
localData1902339 ✅
storageData4022155

8. 使用 clone2 而非 new/create2#

代码 | 文章

测试

forge test --contracts 08_Clone2/Clone2.T.sol --gas-report

Gas 报告

创建类型Gas 成本
clone241493 ✅
create293031
new79515

9. 打包存储槽#

代码

测试

forge test --contracts 09_Packing/Packing.T.sol --gas-report

Gas 报告

创建类型Gas 成本
normal133521
packing111351 ✅

WTF Gas 优化 贡献者#

贡献者是WTF学院的基石 #

image
加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。