Skip to main content

POST /api/gas-estimate

Estimates the gas cost for a contract interaction on Mantle Sepolia. Queries the live RPC for eth_gasPrice and eth_estimateGas, then optionally enriches the response with AI-generated gas optimization suggestions.


Endpoint

POST /api/gas-estimate

Runtime: Node.js
Auth: Not required


Request

Body

{
"address": "0x9d9b602CFe69cfF9706EAc399808E84682ce94FB",
"calldata": "0x8456cb59",
"from": "0x0000000000000000000000000000000000000001"
}
ParameterTypeRequiredDescription
addressstringYesTarget contract address (42-char hex)
calldatastringYesTransaction calldata (hex, starts with 0x)
fromstringNoSender address for gas estimation context

Validation

  • address must match /^0x[0-9a-fA-F]{40}$/
  • calldata must match /^0x[0-9a-fA-F]*$/
  • Returns 400 if validation fails

Response

Success (200)

{
"estimatedGas": 45000,
"gasPriceGwei": 0.02,
"estimatedCostMNT": "0.0000009000",
"estimatedCostUSD": "0.00000072",
"optimizations": [
"Use uint256 instead of smaller integer types to avoid packing overhead in storage",
"Cache storage variables in memory at the top of hot functions",
"Emit events instead of storing non-critical data on-chain"
],
"summary": "Estimated 45,000 gas units at 0.0200 Gwei on Mantle Sepolia. Apply the suggestions below to reduce execution cost."
}

Response Fields

FieldTypeDescription
estimatedGasnumberEstimated gas units for the transaction
gasPriceGweinumberCurrent gas price in Gwei (from eth_gasPrice)
estimatedCostMNTstringEstimated cost in MNT (18 decimal places)
estimatedCostUSDstringApproximate USD cost (MNT at ~$0.80)
optimizationsstring[]3 AI-generated gas optimization suggestions
summarystringHuman-readable cost summary

Error: Gas Estimation Failed (422)

{
"error": "Gas estimation failed: execution reverted. The transaction may revert or require a specific caller.",
"gasPriceGwei": 0.02
}

Returns the current gas price even when estimation fails.

Error: Invalid Input (400)

{
"error": "Invalid contract address."
}

How It Works

Step 1: Get Current Gas Price

const gasPriceHex = await rpcCall('eth_gasPrice', []);
const gasPriceWei = parseInt(gasPriceHex, 16);
const gasPriceGwei = gasPriceWei / 1e9;

Step 2: Estimate Gas

const estimateHex = await rpcCall('eth_estimateGas', [{
to: address,
data: calldata,
from: from ?? '0x0000000000000000000000000000000000000001',
}]);
estimatedGas = parseInt(estimateHex, 16);

If eth_estimateGas reverts (transaction would fail), returns 422 with the error message and current gas price.

Step 3: Calculate Cost

const costWei = BigInt(estimatedGas) * BigInt(gasPriceWei);
const costMNT = Number(costWei) / 1e18;
const costUSD = costMNT * 0.80; // Approximate MNT/USD

Step 4: AI Optimization Suggestions

An optional AI call generates gas optimization tips:

async function callAI(estimatedGas: number, calldata: string, address: string) {
const prompt = `A developer is calling a smart contract on Mantle Sepolia (EVM L2):

Contract address: ${address}
Calldata: ${calldata.slice(0, 200)}
Estimated gas: ${estimatedGas.toLocaleString()} units

Provide 3 specific, actionable Solidity gas optimization suggestions that could reduce this gas cost. Focus on Mantle L2 specific optimizations and general EVM best practices.

Return only a JSON array of strings: ["<opt 1>", "<opt 2>", "<opt 3>"]`;

// Try Hunyuan first, then Groq
if (process.env.HUNYUAN_API_KEY) {
const res = await fetch('https://api.hunyuan.cloud.tencent.com/v1/chat/completions', {
model: 'hunyuan-lite',
messages: [
{ role: 'system', content: 'You are an EVM gas optimization expert. Return only valid JSON arrays. No markdown.' },
{ role: 'user', content: prompt }
],
temperature: 0.2,
max_tokens: 400,
});
// ...
}

if (process.env.GROQ_API_KEY) {
const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
model: 'llama-3.1-8b-instant',
messages: [
{ role: 'system', content: 'You are an EVM gas optimization expert...' },
{ role: 'user', content: prompt }
],
temperature: 0.2,
max_tokens: 400,
response_format: { type: 'json_object' },
});
// Groq json_object may return { optimizations: [...] } or just [...]
const arr = Array.isArray(parsed) ? parsed : (parsed.optimizations ?? []);
}
}

Fallback Optimizations

If no AI provider is available:

const FALLBACK = {
estimatedGas: 45000,
gasPriceGwei: 0.02,
estimatedCostMNT: '0.0000009',
estimatedCostUSD: '0.00000072',
optimizations: [
'Use uint256 instead of smaller integer types to avoid packing overhead in storage',
'Cache storage variables in memory at the top of hot functions',
'Emit events instead of storing non-critical data on-chain',
],
summary: 'This is a standard operation. Savings are possible by reducing storage writes and using packed structs where applicable.',
};

Mantle Sepolia Gas Characteristics

Mantle Sepolia is an Optimism-based L2 with very low gas costs:

ParameterTypical Value
Gas price~0.02 Gwei
L1 data feeIncluded in gas price
Block time~2 seconds

At 0.02 Gwei, a 120,000 gas transaction costs approximately 0.0000024 MNT (~$0.00000192 USD).


Example: cURL

curl -X POST http://localhost:3000/api/gas-estimate \
-H "Content-Type: application/json" \
-d '{
"address": "0x9d9b602CFe69cfF9706EAc399808E84682ce94FB",
"calldata": "0x8456cb59"
}'

Response

{
"estimatedGas": 28734,
"gasPriceGwei": 0.020018,
"estimatedCostMNT": "0.0000005749",
"estimatedCostUSD": "0.00000046",
"optimizations": [
"Use uint256 instead of smaller integer types...",
"Cache storage variables in memory...",
"Emit events instead of storing..."
],
"summary": "Estimated 28,734 gas units at 0.0200 Gwei on Mantle Sepolia. Apply the suggestions below to reduce execution cost."
}

Performance

StageTypical Latency
eth_gasPrice RPC call50-150ms
eth_estimateGas RPC call100-300ms
AI optimization suggestions200-800ms
Fallback<5ms
Total (with AI)350-1250ms
Total (fallback)150-450ms

Next Steps