⚠️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

Estimates the amount of gas required to execute a transaction on Avalanche C-Chain.

When to Use This Method

eth_estimateGas is essential for:

  • Transaction Cost Calculation - Calculate total transaction costs before sending
  • Gas Optimization - Optimize gas limits to prevent overpaying
  • Smart Contract Testing - Verify contract functions will execute successfully
  • User Experience - Show users estimated fees before transaction confirmation

Parameters

Transaction Object with the following fields:

  • from - (optional) Address sending the transaction
  • to - Address receiving the transaction
  • value - (optional) Value to transfer in wei
  • data - (optional) Contract method call data
  • gas - (optional) Gas limit (for estimation boundary)
  • gasPrice - (optional) Gas price in wei
  • maxFeePerGas - (optional) Maximum fee per gas (EIP-1559)
  • maxPriorityFeePerGas - (optional) Maximum priority fee (EIP-1559)
{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0xaff3454fce5edbc8cca8697c15331677e6ebcccc",
"to": "0xfff7ac99c8e4feb60c9750054bdc14a3b2f0fb8",
"value": "0xde0b6b3a7640000",
"data": "0xa9059cbb000000000000000000000000fff7ac99c8e4feb60c9750054bdc14a3b2f0fb8000000000000000000000000000000000000000000000000000000000000000a"
}],
"id": 1
}

Returns

QUANTITY - Estimated gas amount in hex format.

Implementation Examples

curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0xaff3454fce5edbc8cca8697c15331677e6ebcccc",
"to": "0xfff7ac99c8e4feb60c9750054bdc14a3b2f0fb8",
"value": "0xde0b6b3a7640000"
}],
"id": 1
}'

Response Example

Successful Response

{
"jsonrpc": "2.0",
"id": 1,
"result": "0x5208"
}

This represents 21,000 gas units in decimal.

Error Response

{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32000,
"message": "insufficient funds for gas * price + value"
}
}

Common Use Cases

1. Pre-Transaction Cost Calculator

Calculate total transaction costs before execution:

async function calculateTransactionCost(from, to, value, data = '0x') {
const tx = { from, to, value, data };

try {
const gasEstimate = await provider.estimateGas(tx);
const feeData = await provider.getFeeData();

// Calculate different fee scenarios
const scenarios = {
low: {
gasLimit: gasEstimate,
maxFeePerGas: feeData.gasPrice, // Fallback to legacy
cost: gasEstimate * feeData.gasPrice
},
standard: {
gasLimit: gasEstimate,
maxFeePerGas: feeData.maxFeePerGas,
cost: gasEstimate * feeData.maxFeePerGas
},
fast: {
gasLimit: gasEstimate,
maxFeePerGas: feeData.maxFeePerGas * 150n / 100n, // 50% higher
cost: gasEstimate * (feeData.maxFeePerGas * 150n / 100n)
}
};

return {
success: true,
gasEstimate: gasEstimate.toString(),
scenarios: Object.entries(scenarios).reduce((acc, [key, scenario]) => {
acc[key] = {
gasLimit: scenario.gasLimit.toString(),
maxFeePerGas: formatUnits(scenario.maxFeePerGas, 'gwei') + ' gwei',
cost: formatEther(scenario.cost) + ' AVAX',
costUSD: null // Add USD conversion if needed
};
return acc;
}, {})
};
} catch (error) {
return {
success: false,
error: error.message
};
}
}

2. Smart Contract Gas Profiler

Profile gas usage for different contract methods:

async function profileContractMethods(contractAddress, abi, testCases) {
const contract = new Contract(contractAddress, abi, provider);
const results = [];

for (const testCase of testCases) {
const { method, params, from } = testCase;

try {
// Encode function data
const txData = contract.interface.encodeFunctionData(method, params);

const tx = {
from: from,
to: contractAddress,
data: txData
};

const gasEstimate = await provider.estimateGas(tx);
const gasPrice = await provider.getGasPrice();

results.push({
method: method,
params: params,
gasEstimate: gasEstimate.toString(),
estimatedCost: formatEther(gasEstimate * gasPrice) + ' AVAX',
success: true
});

} catch (error) {
results.push({
method: method,
params: params,
error: error.message,
success: false
});
}
}

// Calculate statistics
const successful = results.filter(r => r.success);
const gasEstimates = successful.map(r => Number(r.gasEstimate));

const stats = {
totalMethods: results.length,
successfulMethods: successful.length,
averageGas: gasEstimates.reduce((sum, gas) => sum + gas, 0) / gasEstimates.length,
maxGas: Math.max(...gasEstimates),
minGas: Math.min(...gasEstimates)
};

return { results, stats };
}

3. Gas Optimization Advisor

Provide gas optimization recommendations:

async function gasOptimizationAdvisor(transactions) {
const advice = [];

for (const tx of transactions) {
try {
const baseEstimate = await provider.estimateGas(tx);

// Test different optimization strategies
const optimizations = {};

// 1. Test with explicit gas limit
if (!tx.gas) {
optimizations.explicitGasLimit = {
suggestion: "Add explicit gas limit",
gasLimit: Math.ceil(Number(baseEstimate) * 1.1).toString(),
rationale: "Explicit gas limits prevent estimation failures"
};
}

// 2. Test with reduced value for contract calls
if (tx.data && tx.value && tx.value > 0n) {
try {
const reducedValueTx = { ...tx, value: 0n };
const reducedEstimate = await provider.estimateGas(reducedValueTx);

if (reducedEstimate < baseEstimate) {
optimizations.reduceValue = {
suggestion: "Consider reducing transaction value",
gasReduction: (Number(baseEstimate) - Number(reducedEstimate)).toString(),
rationale: "Lower values may reduce gas consumption"
};
}
} catch (e) {
// Ignore - reduction not possible
}
}

// 3. Check if method is view/pure (should use eth_call instead)
if (tx.data) {
try {
await provider.call(tx);
optimizations.useCall = {
suggestion: "Use eth_call instead of transaction",
gasReduction: baseEstimate.toString(),
rationale: "This appears to be a read-only operation"
};
} catch (e) {
// Not a read-only operation
}
}

advice.push({
transaction: tx,
baseGasEstimate: baseEstimate.toString(),
optimizations: optimizations,
hasOptimizations: Object.keys(optimizations).length > 0
});

} catch (error) {
advice.push({
transaction: tx,
error: error.message,
success: false
});
}
}

return advice;
}

4. Network Congestion Gas Predictor

Predict optimal gas prices based on network conditions:

async function predictOptimalGas(urgency = 'standard') {
const currentBlock = await provider.getBlock('latest');
const feeData = await provider.getFeeData();

// Analyze recent blocks for congestion
const recentBlocks = await Promise.all(
Array.from({ length: 10 }, (_, i) =>
provider.getBlock(currentBlock.number - i)
)
);

const avgUtilization = recentBlocks.reduce(
(sum, block) => sum + (Number(block.gasUsed) / Number(block.gasLimit)), 0
) / recentBlocks.length;

// Base recommendations
const recommendations = {
slow: {
multiplier: 0.9,
description: "Low priority, may take longer",
expectedTime: "30-60 seconds"
},
standard: {
multiplier: 1.0,
description: "Normal priority",
expectedTime: "10-20 seconds"
},
fast: {
multiplier: 1.3,
description: "High priority",
expectedTime: "5-10 seconds"
},
instant: {
multiplier: 1.6,
description: "Highest priority",
expectedTime: "2-5 seconds"
}
};

// Adjust based on network congestion
const congestionMultiplier = avgUtilization > 0.8 ? 1.2 :
avgUtilization < 0.3 ? 0.8 : 1.0;

const selectedRec = recommendations[urgency];
const adjustedMultiplier = selectedRec.multiplier * congestionMultiplier;

const recommendedMaxFee = feeData.maxFeePerGas * BigInt(Math.floor(adjustedMultiplier * 100)) / 100n;
const recommendedPriorityFee = feeData.maxPriorityFeePerGas * BigInt(Math.floor(adjustedMultiplier * 100)) / 100n;

return {
urgency: urgency,
networkUtilization: (avgUtilization * 100).toFixed(1) + '%',
congestionLevel: avgUtilization > 0.8 ? 'High' : avgUtilization < 0.3 ? 'Low' : 'Medium',
recommendations: {
maxFeePerGas: recommendedMaxFee,
maxPriorityFeePerGas: recommendedPriorityFee,
maxFeePerGasGwei: formatUnits(recommendedMaxFee, 'gwei') + ' gwei',
maxPriorityFeePerGasGwei: formatUnits(recommendedPriorityFee, 'gwei') + ' gwei'
},
description: selectedRec.description,
expectedConfirmationTime: selectedRec.expectedTime
};
}

Performance Optimization

Batch Gas Estimations

Estimate gas for multiple transactions efficiently:

async function batchGasEstimations(transactions) {
const batch = transactions.map((tx, i) => ({
jsonrpc: '2.0',
method: 'eth_estimateGas',
params: [tx],
id: i
}));

const response = await fetch('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});

const results = await response.json();

return results.map((result, index) => ({
transactionIndex: index,
success: !result.error,
gasEstimate: result.result ? parseInt(result.result, 16) : null,
error: result.error?.message
}));
}

Error Handling

Common errors and solutions:

Error CodeDescriptionSolution
-32000Insufficient fundsCheck account balance
-32000Execution revertedReview contract logic and parameters
-32602Invalid transaction objectValidate transaction fields
async function safeGasEstimate(tx, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const gasEstimate = await provider.estimateGas(tx);
return { success: true, gasEstimate };
} catch (error) {
if (error.message.includes('insufficient funds')) {
return {
success: false,
error: 'Insufficient balance for transaction',
suggestion: 'Check account balance and reduce transaction value'
};
}

if (error.message.includes('execution reverted')) {
return {
success: false,
error: 'Transaction would revert',
suggestion: 'Check contract requirements and parameters'
};
}

if (i === maxRetries - 1) {
return { success: false, error: error.message };
}

await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}

Need help? Contact our support team or check the Avalanche documentation.