Lesson 4 of 4 Gas and Transaction Fees

Estimating and Optimising Gas

Gas costs are paid by every user of a contract, so measuring and reducing them is part of good design. This lesson explains how to estimate and measure gas with tools, then covers the optimisation techniques that matter most and the ones to avoid.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how eth_estimateGas works and when it fails.
  • Describe tools for measuring gas.
  • Choose effective gas optimisation techniques.
  • Identify optimisations that compromise safety.

Estimating gas

eth_estimateGas simulates a transaction against the current state and returns the gas it would use. web3.js exposes it as web3.eth.estimateGas(tx) and contract.methods.fn(args).estimateGas({ from }). Wallets call it before every transaction and add a margin. Two behaviours are worth knowing: if the simulated transaction would revert, estimation fails with the revert reason, warning the user before they pay; and if state changes between estimation and inclusion, actual usage can differ, especially for functions with loops or branches that depend on state.

True or false

How estimation works

Exam skills 5.2.2

Check what eth_estimateGas does and where its result can be wrong.

Log in to try this activity Interactive activities are free with an account.

Measuring gas during development

The following tools measure real gas usage.

Hardhat gas statistics
npx hardhat test --gas-stats prints minimum, average, median and maximum gas per function called in tests, deployment gas and bytecode size.
Remix
The terminal shows transaction cost and execution cost for every transaction in the Remix VM; the debugger shows gas per opcode.
Receipts
gasUsed and effectiveGasPrice give the actual cost of any mined transaction.
Foundry
forge test --gas-report and gas snapshots compare costs between versions.

Running gas reports in continuous integration catches regressions: a change that makes a common function 20% more expensive is visible before deployment.

Optimisation techniques

Most savings come from reducing storage access. The following table lists the techniques with the biggest effect.

TechniqueWhy it saves gas
Pack small variables into one slotOne SSTORE or SLOAD serves several variables
Use constant and immutableValues live in bytecode; no SLOAD at run time
Cache storage reads in local variablesOne cold SLOAD instead of repeated reads in loops
Use calldata for read-only external parametersAvoids copying into memory
Use custom errorsSmaller bytecode and cheaper reverts than strings
Emit events for off-chain dataLogs cost far less than storage
Avoid unbounded loopsKeeps gas bounded and prevents denial of service
unchecked for provably safe arithmeticSkips overflow checks, for example on a bounded loop counter
Enable the optimizer with suitable runsApplies many low-level optimisations automatically
// Unpacked: three slots
uint256 a;   // slot 0
uint256 b;   // slot 1
uint256 c;   // slot 2

// Packed: one slot (16 + 8 + 8 = 32 bytes)
uint128 a;
uint64  b;
uint64  c;

Packing only helps when the variables are declared next to each other and are read or written together; a lone uint8 can even cost slightly more than a uint256, because the EVM must mask the smaller value.

Spot the bug

A gas-hungry function

Exam skills 5.3.1

Find the lines that waste gas in this reward function. The behaviour is correct; only the cost is the problem.

Log in to try this activity Interactive activities are free with an account.

What not to optimise

Safety first

Never trade safety for gas. Removing input checks, using unchecked where overflow is possible, replacing audited library code with hand-written assembly, or skipping reentrancy protection can save a few hundred gas and lose everything the contract holds. Optimise after the code is correct, tested and reviewed, and measure every change.

Scenario questions

When to stop optimising

Exam skills 5.3.1

Weigh gas savings against safety and clarity.

Log in to try this activity Interactive activities are free with an account.
Worked example

Caching in a loop

A function loops 100 times and reads the state variable feeRate in each iteration. How much gas does caching it in a local variable save?

Without caching, the first read is cold (2,100 gas) and the next 99 are warm (99 × 100 = 9,900), about 12,000 gas in total. With uint256 rate = feeRate; before the loop, there is one cold read of 2,100 gas and then cheap stack reads of about 3 gas each, saving close to 10,000 gas per call. If feeRate never changes after deployment, making it immutable removes even the first read.

Worked example

A reverting estimate

A DApp's "Buy" button shows the error "cannot estimate gas; transaction may fail" and the wallet never opens. What should the developer investigate?

Gas estimation simulates the transaction, and the simulation reverted. The developer should read the revert reason in the error (for example, an insufficient allowance, a sale that has not started or a missing value) rather than forcing a fixed gas limit. Forcing a limit would only send a transaction that reverts on chain and charges the user for nothing.

Check yourself

Name the optimisation that stores several small variables in one storage slot.

Show answer

Variable packing: declaring variables smaller than 32 bytes next to each other, such as a uint128 and two uint64s, so they share one slot and are read or written together.

Exam Tips

Remember for the exam

  • estimateGas simulates; a failed estimate usually means the transaction would revert.
  • Measure with npx hardhat test --gas-stats, Remix and receipts.
  • Biggest savings: fewer storage reads and writes (packing, caching, constant, immutable).
  • Never remove checks or protections to save gas.