Gas Estimation
Predicting the compute a transaction will need so it does not run out mid-execution.
Basically
Gas estimation predicts how much computing work an Ethereum transaction needs. You use the estimate to set a gas limit and reduce the risk of failure.
Key Takeaways
- Gas estimation predicts how much computational work a transaction requires: Ethereum nodes simulate the transaction against current state using the eth_estimateGas RPC call and return the gas consumed, helping you set an appropriate gas limit.
- Estimates can be inaccurate because blockchain state changes between estimation and execution: other transactions, MEV activity, and non-deterministic contract behaviour can all shift the actual gas consumed, making the original estimate too low or too high.
- Gas estimation differs from fee estimation: gas estimation determines how much gas a transaction needs, while fee estimation under EIP-1559 determines the price per unit of gas, comprising the base fee plus priority tip, and both are needed to calculate total transaction cost.
What Is Gas Estimation?
Gas estimation predicts how much computational gas an Ethereum transaction will consume before you submit it to the network. Every operation on the Ethereum Virtual Machine (EVM) costs a fixed amount of gas: a simple transfer costs 21,000 gas, while complex smart contract interactions can require hundreds of thousands or even millions. The right gas limit matters because a limit that is too low causes the transaction to revert and the gas is still consumed, while a limit that is too high reserves capacity you do not need.
The standard way to estimate gas is through the eth_estimateGas JSON-RPC method, which every Ethereum node exposes. Wallets like MetaMask, libraries like ethers.js and viem, and infrastructure providers like Infura all rely on this call behind the scenes to suggest gas limits for you. Gas estimation remains inherently imperfect despite its ubiquity: the estimate is a snapshot of what would happen if the transaction executed right now, but by the time it is included in a block, the state may have changed.
How It Works
A client calls eth_estimateGas to request an estimate. The node then performs the following steps:
The result is not simply the gas used during simulation. Clients like Geth run a binary search to find the smallest gas budget that allows the transaction to execute without reverting. The search starts by dry-running the transaction at the maximum allowed limit, typically the pending block's gas limit, then narrows the range between the gas actually consumed and that upper bound.
The Binary Search Algorithm
Geth's estimation algorithm assumes monotonicity: if a transaction succeeds with a gas limit of N, it should succeed with any limit greater than N. The binary search exploits this by halving the range on each iteration:
The approach typically converges in 10 to 20 iterations. For simple ETH transfers, some clients like Reth skip the search entirely and return the known constant of 21,000 gas.
Gas Cap and Upper Bounds
Nodes enforce a cap on eth_estimateGas to prevent abuse. Geth's default RPC gas cap is set to 50 million gas and is configurable via the --rpc.gascap flag. If no gas limit is specified in the transaction object, the node uses the pending block's gas limit as the upper bound, and the Ethereum mainnet block gas limit is currently around 36 million gas, which means a single transaction cannot consume more than that.
Why Estimates Can Be Wrong
Gas estimation simulates against a snapshot of state, but real execution happens in a future block with potentially different state. Research measuring EVM workloads found that gas estimates vary across nearby historical states for approximately 14% of transactions on Ethereum mainnet and as high as 46% on Layer 2 chains like Base. Several factors drive this inaccuracy:
State Changes Between Estimation and Execution
Every transaction in a block modifies the blockchain state. Between the moment you call eth_estimateGas and when your transaction is actually included in a block, other transactions may alter the contract storage your transaction depends on. A DeFi swap that looked like it would cost 150,000 gas might cost 180,000 gas if a prior transaction in the same block changes the liquidity pool's state.
MEV and Transaction Ordering
MEV searchers can insert transactions before yours, altering the state your transaction sees. In a sandwich attack, a bot front-runs your swap to move the price, making your transaction consume different gas than estimated. MEV and DeFi transactions account for the largest share of estimation variance because their gas consumption is highly state-dependent.
Non-Monotonic Gas Behavior
The binary search assumes that if a transaction succeeds at gas limit N, it will succeed at N+1, but that is not always true. Some contracts have branching logic where different gas limits trigger different code paths. Separate regions of gas limits can make a transaction successful, with gaps in between where it fails, and this rare edge case can produce incorrect estimates.
Storage Refunds and Dynamic Costs
Ethereum refunds a portion of gas when storage is cleared, for example when setting a storage slot from a non-zero value to zero. These refunds depend on the exact pre-execution state. If the storage slot was already zero when estimated but non-zero at execution time, or vice versa, the actual gas consumed will differ from the estimate.
Gas Estimation vs. Fee Estimation
Gas estimation and fee estimation are two separate problems that are often confused. Gas estimation answers how many units of gas your transaction will consume, while fee estimation answers what price per gas unit you should pay to get included in a block.
EIP-1559 sets the base fee algorithmically through the protocol and adjusts it based on block fullness. You add a priority fee, or tip, to incentivise block builders. The total transaction cost is gas used multiplied by the effective gas price, comprising the base fee plus priority fee; gas estimation determines the first factor and fee estimation determines the second, and for a deeper look at how paymasters can abstract these costs away from end users, see the research on gasless paymaster transaction design.
Gas Limit Setting Strategies
The right gas limit balances two risks. A limit that is too low causes the transaction to fail, while a limit that is too high can waste fees in certain edge cases.
Too Low: Transaction Reverts
A gas limit below what the transaction actually needs makes the EVM run out of gas mid-execution and revert the transaction. You still pay for all the gas consumed up to the point of failure. The intended state changes are rolled back, but the gas fee is not refunded, which makes underestimation expensive.
Too High: Wasted Capacity
A successful transaction refunds unused gas to you, so setting a high limit does not directly waste money. Indirect costs remain: the gas limit counts against the block's total gas budget during transaction inclusion, and some gas price mechanisms on L2 networks may factor the gas limit into pricing. Additionally, if the transaction reverts for a reason unrelated to gas, such as a contract revert condition, the entire gas limit is consumed.
Wallet Gas Suggestions
Every Ethereum wallet calls eth_estimateGas before prompting you to confirm a transaction. The estimate populates the gas limit field and, combined with fee estimation, shows you the expected total cost. Without this step, you would need to manually research gas costs for every contract interaction.
DApp Transaction Builders
Decentralised applications use gas estimation to build transactions programmatically. A DEX aggregator, for example, estimates gas for each possible swap route and factors the gas cost into its routing decision. It selects the path that minimises total cost, comprising swap slippage plus gas.
Gas Optimization Tooling
Smart contract developers use gas estimation during development to benchmark their contracts. By calling eth_estimateGas against a local node or fork, developers can measure how changes to contract logic affect gas consumption. They can identify optimisation opportunities before deploying to mainnet.
Batch Transaction Planning
Protocols that batch multiple operations into a single transaction, common in L2 sequencers and batch settlement systems, use gas estimation for planning. They determine whether a batch fits within the block gas limit. They also use the estimate to price the batch appropriately for users.
Practical Example
An ERC-20 token transfer prepared with ethers.js shows gas estimation in practice. The process looks like this:
The two separate estimation steps are estimateGas for the gas quantity and getFeeData for the gas price. Both are needed to construct a complete transaction.
Why It Matters
Accurate gas estimation directly affects user experience and cost. An underestimate causes a failed transaction where you lose the gas fee with nothing to show for it. An overestimate is less harmful but can confuse you with inflated cost previews and make you hesitate to transact, and for protocols built on Ethereum and EVM-compatible chains, gas estimation is a fundamental piece of infrastructure that runs behind every wallet interaction.
The complexity of gas estimation is one reason why many modern wallet designs pursue gasless transactions and gas sponsorship models. By abstracting gas away from end users entirely, platforms like Spark eliminate the estimation problem at the user-facing layer. On Bitcoin Layer 2 networks like Spark, the UTXO-based model avoids the concept of gas altogether, offering predictable transaction costs without the estimation uncertainty inherent to the EVM.
Failed Transactions Still Cost Money
Failed transactions are not free, making bad gas estimation a consequential risk. When a transaction runs out of gas, your intended state changes are reverted, but the gas consumed up to the failure point is permanently spent. For expensive contract calls, you can lose significant fees on a transaction that accomplished nothing.
Estimation Calls Have Latency
Each eth_estimateGas call requires the node to simulate the full transaction execution. For complex contract interactions, this can take hundreds of milliseconds. Applications that need to estimate gas for multiple possible transaction paths, like DEX aggregators comparing routes, may face noticeable latency from sequential estimation calls.
State Staleness
The estimate may be several blocks old by the time a transaction is included in a block. During periods of high network congestion or intense MEV activity, state can change significantly between estimation and inclusion. Applications that handle large values or interact with highly contested contracts should use larger safety margins or implement retry logic with re-estimation.
Cross-Client Differences
Different Ethereum clients, including Geth, Reth, Nethermind and Besu, may return slightly different estimates for the same transaction. While they all implement the same EVM specification, their estimation algorithms, heuristics and rounding behaviour can vary. Applications that need consistent estimates should be aware of which client their RPC provider runs.
The glossary entry is for informational purposes only and does not constitute financial or investment advice. Always do your own research before using any protocol or technology.