Skill 5.2.2

Estimate gas with tools before and after deployment

Key Concepts

The eth_estimateGas JSON-RPC method simulates a transaction against current state and returns the gas it would use. web3.js exposes it as web3.eth.estimateGas(tx) and contract.methods.fn().estimateGas({ from }); wallets call it automatically and add a margin. If the simulated transaction would revert, estimation fails, which warns the user before paying. Estimates can differ from actual usage when state changes between estimation and inclusion.

During development, Hardhat's npx hardhat test --gas-stats prints the minimum, average, median and maximum gas of each function called in tests, plus deployment cost and bytecode size. Remix shows the gas of each transaction in its terminal. After a transaction, the receipt's gasUsed and effectiveGasPrice give the actual cost. To express a cost in ether, multiply gas by the gas price in gwei and divide by 109.