A comprehensive guide to teach you about gas optimization patterns.
This guide is aimed at developers who are already familiar with Solidity and want to learn how to write more gas efficient smart contracts.
- Introduction
- General overview of gas in Ethereum
- EVM Basics
- Necessary background knowledge about the EVM (i.e. data locations)
- Gas optimization techniques
- Extensive collection of gas optimization techniques
You can use Foundry to look into certain code snippets in detail. Most gas optimization examples have a corresponding source and test file to debug/inspect further.
Useful forge commands for inspecting and debugging contracts in this repository:
forge test --mc <contract_name> -vvvv
// run tests and show stack tracesforge inspect <Contract> ir-optimized
// show optimized Yulforge inspect <Contract> methods
// show function selectorsforge debug --debug <Contract> --sig "foo()"
// debug functions
Practice by completing the challenges in ./src/practice/
. The suggested order to complete them is:
ArraySum
is an example contract where you can apply various gas optimization patterns. The required gas goal is achieveable by just using the patterns described in the Gas optimization techniques section.
Airdrop
, BadERC20
and BadERC721
are inefficient contracts that have been deployed onchain. Try to improve them as much as you can. You can use the following test cases to track your progress:
forge test --mc ArraySumTest
forge test --mc AirdropTest
forge test --mc BadERC20Test -vv
forge test --mc BadERC721Test -vv