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
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。