⚠️Blast API (blastapi.io) ends Oct 31. Migrate to Dwellir and skip Alchemy's expensive compute units.
Switch Today →
Skip to main content

eth_estimateGas

Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain.

When to Use This Method

eth_estimateGas is crucial for:

  • Transaction Preparation - Calculate gas limits before sending
  • Cost Estimation - Preview transaction fees for users
  • Gas Optimization - Find optimal gas usage for complex operations
  • Error Prevention - Detect failures before broadcasting

Parameters

  1. Transaction Object

    • from - (optional) Address sending the transaction
    • to - Address of receiver or contract
    • gas - (optional) Gas limit for estimation
    • gasPrice - (optional) Gas price in wei
    • value - (optional) Value to send in wei
    • data - (optional) Hash of method signature and encoded parameters
  2. Block Parameter - QUANTITY|TAG (optional)

    • "latest" - Most recent block (default)
    • "pending" - Pending state
    • Block number in hex
{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [
{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}
],
"id": 1
}

Returns

QUANTITY - The estimated gas amount in hexadecimal.

Implementation Examples

import { JsonRpcProvider, Contract, parseEther, parseUnits } from 'ethers';

const provider = new JsonRpcProvider('https://api-manta-pacific-mainnet.n.dwellir.com/YOUR_API_KEY');

// Gas estimation utility
class GasEstimator {
constructor(provider) {
this.provider = provider;
this.cache = new Map();
}

async estimateETHTransfer(from, to, value) {
try {
const gasEstimate = await this.provider.estimateGas({
from: from,
to: to,
value: parseEther(value)
});

// Add 10% buffer for safety
const gasWithBuffer = gasEstimate * 110n / 100n;

// Get current gas prices
const feeData = await this.provider.getFeeData();

// Calculate costs
const estimatedCost = gasWithBuffer * feeData.gasPrice;
const estimatedCostEIP1559 = gasWithBuffer * feeData.maxFeePerGas;

return {
gasLimit: gasWithBuffer.toString(),
gasPrice: feeData.gasPrice.toString(),
maxFeePerGas: feeData.maxFeePerGas.toString(),
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas.toString(),
estimatedCostWei: estimatedCost.toString(),
estimatedCostETH: ethers.formatEther(estimatedCost),
estimatedCostEIP1559Wei: estimatedCostEIP1559.toString(),
estimatedCostEIP1559ETH: ethers.formatEther(estimatedCostEIP1559)
};
} catch (error) {
throw new Error(`Gas estimation failed: ${error.message}`);
}
}

async estimateContractCall(contractAddress, abi, method, params, from) {
const contract = new Contract(contractAddress, abi, this.provider);

try {
// Build transaction
const tx = await contract[method].populateTransaction(...params);
tx.from = from;

// Estimate gas
const gasEstimate = await this.provider.estimateGas(tx);
const l2Cost = gasWithBuffer * feeData.maxFeePerGas;
const totalCost = l2Cost;

return {
gasLimit: gasWithBuffer.toString(),
l2GasEstimate: gasEstimate.toString(), maxFeePerGas: feeData.maxFeePerGas.toString(),
l2CostWei: l2Cost.toString(),
l2CostETH: ethers.formatEther(l2Cost),
totalCostWei: totalCost.toString(),
totalCostETH: ethers.formatEther(totalCost),
method: method,
contract: contractAddress
};
} catch (error) {
// Parse revert reason if available
if (error.data) {
const reason = this.parseRevertReason(error.data);
throw new Error(`Estimation failed: ${reason}`);
}
throw error;
}
} parseRevertReason(data) {
if (typeof data === 'string' && data.startsWith('0x08c379a0')) {
// Standard revert string
const reason = ethers.AbiCoder.defaultAbiCoder().decode(
['string'],
'0x' + data.slice(10)
)[0];
return reason;
}
return 'Unknown error';
}

async batchEstimate(transactions) {
const estimates = [];

for (const tx of transactions) {
try {
const gasEstimate = await this.provider.estimateGas(tx);
const feeData = await this.provider.getFeeData();

estimates.push({
transaction: tx,
gasLimit: gasEstimate.toString(),
estimatedCost: (gasEstimate * feeData.maxFeePerGas).toString(),
success: true
});
} catch (error) {
estimates.push({
transaction: tx,
error: error.message,
success: false
});
}
}

return estimates;
}

async compareGasStrategies(transaction) {
const gasEstimate = await this.provider.estimateGas(transaction);
const feeData = await this.provider.getFeeData();
const block = await this.provider.getBlock('latest');

// Different gas strategies
const strategies = {
conservative: {
gasLimit: gasEstimate * 150n / 100n, // 50% buffer
maxFeePerGas: feeData.maxFeePerGas * 120n / 100n,
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas * 120n / 100n
},
standard: {
gasLimit: gasEstimate * 110n / 100n, // 10% buffer
maxFeePerGas: feeData.maxFeePerGas,
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas
},
aggressive: {
gasLimit: gasEstimate * 105n / 100n, // 5% buffer
maxFeePerGas: block.baseFeePerGas * 2n + feeData.maxPriorityFeePerGas / 2n,
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas / 2n
}
};

const results = {};
for (const [name, strategy] of Object.entries(strategies)) {
const maxCost = strategy.gasLimit * strategy.maxFeePerGas;
const likelyCost = strategy.gasLimit *
(block.baseFeePerGas + strategy.maxPriorityFeePerGas);

results[name] = {
...strategy,
maxCostWei: maxCost.toString(),
maxCostETH: ethers.formatEther(maxCost),
likelyCostWei: likelyCost.toString(),
likelyCostETH: ethers.formatEther(likelyCost)
};
}

return results;
}
}

// Usage example
const estimator = new GasEstimator(provider);

// Estimate simple transfer
const transferEstimate = await estimator.estimateETHTransfer(
'0xYourAddress',
'0xRecipientAddress',
'0.1'
);
console.log('Transfer cost:', transferEstimate.estimatedCostETH, 'ETH');

// Estimate contract interaction
const contractEstimate = await estimator.estimateContractCall(
'0xContractAddress',
['function transfer(address to, uint256 amount)'],
'transfer',
['0xRecipient', parseUnits('100', 18)],
'0xYourAddress'
);
console.log('Contract call cost:', contractEstimate.totalCostETH, 'ETH');