patternjavascriptModerate
Gas estimation: getting accurate gas limits before sending transactions
Viewed 0 times
ethers.js v6.x
estimateGasgas limitgas estimationEIP-1559transaction gasbuffer
Error Messages
Problem
Transactions fail with 'out of gas' if the gas limit is too low, but setting it too high wastes user funds.
Solution
Call provider.estimateGas() or contract.method.estimateGas() before sending. Add a 20% buffer to handle edge cases.
const estimated = await contract.transfer.estimateGas(recipient, amount);
const gasLimit = (estimated * 120n) / 100n; // 20% buffer
const tx = await contract.transfer(recipient, amount, { gasLimit });Why
Gas estimation simulates the transaction at the current block state. A buffer is needed because state can change between estimation and execution.
Gotchas
- estimateGas throws if the transaction would revert — use a try/catch to surface the revert reason
- For EIP-1559 transactions, also set maxFeePerGas and maxPriorityFeePerGas, not just gasPrice
- Gas estimation on testnets may differ from mainnet due to different EVM versions or contract states
Code Snippets
Estimate gas with a safety buffer
async function sendWithEstimatedGas(contract, signer, recipient, amount) {
const tokenWithSigner = contract.connect(signer);
// Estimate gas
const estimated = await tokenWithSigner.transfer.estimateGas(recipient, amount);
const gasLimit = (estimated * 120n) / 100n; // 20% buffer
// Get EIP-1559 fee data
const feeData = await signer.provider.getFeeData();
const tx = await tokenWithSigner.transfer(recipient, amount, {
gasLimit,
maxFeePerGas: feeData.maxFeePerGas,
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
});
return tx.wait();
}Context
Preparing transactions for user submission to avoid failures
Revisions (0)
No revisions yet.