WTF ガス最適化#
Solidity ガス最適化技術、Foundry を使用。Solidity スマートコントラクトをよりガス効率的に書くためのテクニックをまとめます。
大綱#
6. require/assert よりもカスタムエラーを使用
1. 定数と不変を使用#
テスト
forge test --contracts 01_Constant/Constant.t.sol --gas-report
ガスレポート
関数名 | ガスコスト |
---|---|
varConstant | 183 |
varImmutable | 161 ✅ |
variable | 2305 |
2. メモリよりも calldata を使用#
テスト
forge test --contracts 02_CalldataAndMemory/CalldataAndMemory.T.sol --gas-report
ガスレポート
関数名 | ガスコスト |
---|---|
writeByCalldata | 67905 ✅ |
writeByMemory | 68456 |
3. ビットマップを使用#
テスト
forge test --contracts 03_Bitmap/Bitmap.T.sol --gas-report
ガスレポート
関数名 | ガスコスト |
---|---|
setDataWithBitmap | 22366 ✅ |
setDataWithBoolArray | 35729 |
4. チェックなしを使用#
テスト
forge test --contracts 04_unchecked/Unchecked.T.sol --gas-report
ガスレポート
関数名 | ガスコスト |
---|---|
forNormal | 1910309 |
forUnchecked | 570287 ✅ |
5. uint8 よりも uint256 を使用#
テスト
forge test --contracts 05_uint/Uint.T.sol --gas-report
ガスレポート
関数名 | ガスコスト |
---|---|
read Uint8 | 2379 |
read Uint128 | 2465 |
read Uint256 | 2317 ✅ |
set Uint8 | 5355 |
set Uint128 | 5358 |
set Uint256 | 5322 ✅ |
6. require/assert よりもカスタムエラーを使用#
テスト
forge test --contracts 06_Error/Error.T.sol --gas-report
ガスレポート
エラー名 | ガスコスト |
---|---|
Assert | 180 |
Require | 268 |
Revert | 164 ✅ |
7. ストレージよりもローカル変数を使用#
テスト
forge test --contracts 07_LocalData/LocalData.T.sol --gas-report
ガスレポート
データ型 | ガスコスト |
---|---|
localData | 1902339 ✅ |
storageData | 4022155 |
8. new/create2 よりも clone2 を使用#
テスト
forge test --contracts 08_Clone2/Clone2.T.sol --gas-report
ガスレポート
作成タイプ | ガスコスト |
---|---|
clone2 | 41493 ✅ |
create2 | 93031 |
new | 79515 |
9. ストレージスロットのパッキング#
テスト
forge test --contracts 09_Packing/Packing.T.sol --gas-report
ガスレポート
作成タイプ | ガスコスト |
---|---|
normal | 133521 |
packing | 111351 ✅ |