Docs

eth_feeHistory - MegaETH RPC Method

Get historical gas fee data on MegaETH including base fees and priority fee percentiles. Essential for gas price prediction, fee estimation UIs, and network congestion monitoring.

Returns historical gas fee data on MegaETH, including base fees per gas and priority fee percentiles for a range of recent blocks. This data is essential for building accurate fee estimation algorithms for EIP-1559 transactions.

Why MegaETH? Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.

When to Use This Method

eth_feeHistory is essential for high-frequency DeFi developers, gaming studios, and teams building real-time applications:

  • Gas Price Prediction — Analyze recent base fee trends to predict future gas costs and set appropriate maxFeePerGas values
  • Fee Estimation UIs — Build gas fee dashboards that show low/medium/high price tiers based on historical percentiles
  • Network Congestion Monitoring — Track gasUsedRatio across blocks to detect congestion patterns on high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
  • Transaction Cost Analysis — Calculate average transaction costs over time for budgeting and cost optimization

Code Examples

Common Use Cases

1. Gas Fee Estimator with Confidence Tiers

Build a fee estimator that provides low/medium/high options on MegaETH:

JavaScript
import { JsonRpcProvider, formatUnits } from 'ethers';

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

async function estimateGasFees(blockRange = 20) {
  const feeHistory = await provider.send('eth_feeHistory', [
    '0x' + blockRange.toString(16),
    'latest',
    [10, 50, 90]
  ]);

  // Get the predicted next base fee (last element in baseFeePerGas)
  const nextBaseFee = BigInt(feeHistory.baseFeePerGas[feeHistory.baseFeePerGas.length - 1]);

  // Calculate average priority fees at each percentile
  const avgRewards = [0, 1, 2].map(idx => {
    const fees = feeHistory.reward.map(r => BigInt(r[idx]));
    return fees.reduce((sum, f) => sum + f, 0n) / BigInt(fees.length);
  });

  return {
    low: {
      maxPriorityFeePerGas: avgRewards[0],
      maxFeePerGas: nextBaseFee + avgRewards[0],
      label: 'Low — may take several blocks'
    },
    medium: {
      maxPriorityFeePerGas: avgRewards[1],
      maxFeePerGas: nextBaseFee * 2n + avgRewards[1],
      label: 'Medium — next few blocks'
    },
    high: {
      maxPriorityFeePerGas: avgRewards[2],
      maxFeePerGas: nextBaseFee * 3n + avgRewards[2],
      label: 'High — next block target'
    }
  };
}

const fees = await estimateGasFees();
for (const [tier, data] of Object.entries(fees)) {
  console.log(`${data.label}`);
  console.log(`  Priority: ${formatUnits(data.maxPriorityFeePerGas, 'gwei')} Gwei`);
  console.log(`  Max Fee:  ${formatUnits(data.maxFeePerGas, 'gwei')} Gwei`);
}

2. Network Congestion Monitor

Track MegaETH network congestion using gas utilization ratios:

JavaScript
async function getCongestionLevel(provider, blockRange = 50) {
  const feeHistory = await provider.send('eth_feeHistory', [
    '0x' + blockRange.toString(16),
    'latest',
    []
  ]);

  const ratios = feeHistory.gasUsedRatio;
  const avgRatio = ratios.reduce((sum, r) => sum + r, 0) / ratios.length;
  const recentRatio = ratios.slice(-5).reduce((sum, r) => sum + r, 0) / 5;

  // Detect base fee trend
  const baseFees = feeHistory.baseFeePerGas.map(f => Number(BigInt(f)));
  const firstHalf = baseFees.slice(0, Math.floor(baseFees.length / 2));
  const secondHalf = baseFees.slice(Math.floor(baseFees.length / 2));
  const avgFirst = firstHalf.reduce((a, b) => a + b, 0) / firstHalf.length;
  const avgSecond = secondHalf.reduce((a, b) => a + b, 0) / secondHalf.length;
  const trend = avgSecond > avgFirst * 1.1 ? 'rising' : avgSecond < avgFirst * 0.9 ? 'falling' : 'stable';

  let level;
  if (recentRatio > 0.8) level = 'high';
  else if (recentRatio > 0.5) level = 'moderate';
  else level = 'low';

  return {
    congestion: level,
    averageUtilization: (avgRatio * 100).toFixed(1) + '%',
    recentUtilization: (recentRatio * 100).toFixed(1) + '%',
    baseFeeTrend: trend
  };
}

const congestion = await getCongestionLevel(provider);
console.log('Network congestion:', congestion);

3. Base Fee Prediction

Predict the next block's base fee from recent history:

JavaScript
async function predictBaseFee(provider) {
  const feeHistory = await provider.send('eth_feeHistory', ['0x1', 'latest', []]);

  const currentBaseFee = BigInt(feeHistory.baseFeePerGas[0]);
  const gasUsedRatio = feeHistory.gasUsedRatio[0];

  // EIP-1559 base fee adjustment formula
  // If gas used > 50% target, base fee increases (up to 12.5%)
  // If gas used < 50% target, base fee decreases (up to 12.5%)
  const targetRatio = 0.5;
  const maxChange = 0.125; // 12.5%

  let changeRatio;
  if (gasUsedRatio > targetRatio) {
    changeRatio = Math.min((gasUsedRatio - targetRatio) / targetRatio, 1) * maxChange;
  } else {
    changeRatio = -Math.min((targetRatio - gasUsedRatio) / targetRatio, 1) * maxChange;
  }

  const predictedBaseFee = currentBaseFee + BigInt(Math.floor(Number(currentBaseFee) * changeRatio));

  console.log(`Current base fee: ${Number(currentBaseFee) / 1e9} Gwei`);
  console.log(`Gas used ratio: ${(gasUsedRatio * 100).toFixed(1)}%`);
  console.log(`Predicted next base fee: ${Number(predictedBaseFee) / 1e9} Gwei`);

  return predictedBaseFee;
}

Block Range Limit

Block Range Limit

On MegaETH, eth_feeHistory queries are subject to a maximum block range of 10,000 blocks. This means the blockCount parameter cannot exceed 10,000 blocks per request.

For querying larger block ranges, split your requests into batches:

JavaScript
// Example: Query in 10,000-block batches
const MAX_RANGE = 10000;
const totalBlocks = 50000;
const newestBlock = await provider.getBlockNumber();

const allFeeHistory = [];

for (let i = 0; i < totalBlocks; i += MAX_RANGE) {
  const blockCount = Math.min(MAX_RANGE, totalBlocks - i);
  const feeHistory = await provider.send('eth_feeHistory', [
    blockCount,
    newestBlock - i,
    []
  ]);
  allFeeHistory.push(feeHistory);
}

Error Handling

Common errors and solutions:

Error CodeDescriptionSolution
-32602Invalid paramsEnsure blockCount is 1-1024, rewardPercentiles is sorted ascending, and values are 0-100
-32601Method not foundThe node may not support EIP-1559 — fall back to eth_gasPrice
-32603Internal errorRetry with exponential backoff
-32005Rate limit exceededReduce blockCount or implement caching
-32000Block range unavailableRequested blocks may be pruned — use a smaller range or more recent newestBlock
JavaScript
async function safeFeeHistory(provider, blockCount = 10, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await provider.send('eth_feeHistory', [
        '0x' + blockCount.toString(16),
        'latest',
        [25, 50, 75]
      ]);
    } catch (error) {
      if (error.code === -32602 && blockCount > 1) {
        // Reduce block count and retry
        blockCount = Math.max(1, Math.floor(blockCount / 2));
        continue;
      }
      if (error.code === -32005) {
        await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
        continue;
      }
      if (i === maxRetries - 1) throw error;
      await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
    }
  }
}