How to Build an Ethereum Gas Tracker with Infura

·

Understanding gas and gas prices is essential for any developer building on Ethereum. Efficient gas management can lead to significant cost savings—sometimes amounting to thousands of dollars—especially during smart contract deployments or high-frequency transactions. In this guide, we’ll explore what gas and gas pricing mechanisms are, how they’ve evolved, and most importantly, how to build your own Ethereum gas tracker using Infura’s powerful API suite.

Whether you're optimizing transaction timing or analyzing network congestion, a real-time gas tracker gives you actionable insights. Let’s dive in.


What Are Gas and Gas Prices?

On Ethereum, every operation—whether sending ETH or executing a smart contract—requires computational resources. To compensate validators for this work, users pay a fee measured in gas.

The total cost of a transaction is calculated as:

Total Cost = Gas Units Used × Gas Price

However, since the London Hard Fork and the implementation of EIP-1559, this model has evolved into a more predictable structure involving two components: the base fee and the priority fee.

👉 Discover how real-time data can improve your blockchain development workflow.


How Are Gas Prices Calculated After EIP-1559?

Prior to EIP-1559, gas pricing followed a volatile "blind auction" model where users bid against each other. This often led to unpredictable spikes during network congestion.

Now, the formula is:

Total Fee = Gas Units × (Base Fee + Priority Fee)

Here’s what each component means:

  1. Base Fee: Dynamically adjusted by the protocol based on block congestion. It increases by up to 12.5% when blocks are over half-full and decreases when underutilized. This fee is burned, reducing ETH supply.
  2. Priority Fee (Tip): A small additional incentive paid directly to validators to prioritize your transaction. Higher tips mean faster inclusion.
  3. Block Gas Limit: Doubled from 15 million to 30 million units post-EIP-1559, allowing better handling of traffic surges while targeting 50% average utilization.

This new system makes gas estimation more transparent and less prone to wild fluctuations.


Building Your Own Ethereum Gas Tracker

Let’s create a functional gas tracker in two parts:

  1. A Node.js script that fetches recent gas data from Ethereum via Infura.
  2. A React dashboard that displays the data in real time.

This project will help you monitor base fees, gas utilization, and trends across the latest blocks—empowering smarter transaction decisions.


Part 1: Create the Node.js Gas Tracker Script

Step 1: Install Node.js and npm

Ensure you have Node.js and its package manager (npm) installed. Run:

node -v

If a version number appears, you're ready to go.

Step 2: Set Up an Infura Account

Infura provides reliable access to Ethereum node data without running your own node. Sign up for a free account and create a new Web3 API key named “Gas Tracker.”

You’ll receive an HTTPS endpoint like:

https://mainnet.infura.io/v3/YOUR_API_KEY

We’ll use this to query Ethereum’s eth_feeHistory method.

Step 3: Initialize the Project

In your terminal:

mkdir gas-tracker && cd gas-tracker
npm init -y
npm install axios
touch main.js

Step 4: Write the Script

Open main.js and paste the following code:

const axios = require('axios');

const baseUrl = "https://mainnet.infura.io/v3/YOUR_API_KEY";
const data = JSON.stringify({
  "jsonrpc": "2.0",
  "method": "eth_feeHistory",
  "params": ["0x5", "latest", []],
  "id": 1
});

const config = {
  method: 'post',
  url: baseUrl,
  headers: { 'Content-Type': 'application/json' },
  data
};

axios(config)
  .then(response => {
    const history = response.data.result;
    history.baseFeePerGas = history.baseFeePerGas.map(x => (parseInt(x) / 1e9).toFixed(2));
    history.oldestBlock = parseInt(history.oldestBlock);
    console.log(history);
  })
  .catch(console.error);

Run it:

node main.js

You’ll see output showing base fees (in Gwei), block usage ratios, and block numbers for the last five blocks.


Part 2: Build a Live React Dashboard

Step 1: Clone the Starter App

We’ve prepared a starter React app with styling and custom hooks:

git clone https://github.com/rounakbanik/infura-gas-tracker.git
cd infura-gas-tracker
npm install

Step 2: Implement Real-Time Updates

Replace App.js with this enhanced version:

import './App.css';
import axios from 'axios';
import { useState } from 'react';
import { useInterval } from './hooks/useInterval';

const baseUrl = "https://mainnet.infura.io/v3/YOUR_API_KEY";
const data = JSON.stringify({
  "jsonrpc": "2.0",
  "method": "eth_feeHistory",
  "params": ["0x5", "latest", []],
  "id": 1
});

const config = { method: 'post', url: baseUrl, headers: { 'Content-Type': 'application/json' }, data };

function App() {
  const [feeHistory, setFeeHistory] = useState(null);

  useInterval(async () => {
    try {
      const response = await axios(config);
      let history = response.data.result;

      const baseFees = history.baseFeePerGas.map(x => (parseInt(x) / 1e9).toFixed(2));
      const gasUsedPercent = history.gasUsedRatio.map(x => (x * 100).toFixed(2));
      const oldestBlock = parseInt(history.oldestBlock);
      const blockRange = Array.from({ length: 5 }, (_, i) => oldestBlock + i);

      const formattedHistory = [blockRange, baseFees, gasUsedPercent];
      const transposed = formattedHistory[0].map((_, i) => formattedHistory.map(row => row[i]));

      setFeeHistory(transposed);
    } catch (err) {
      console.error("Failed to fetch gas data:", err);
    }
  }, 15000); // Update every 15 seconds

  return (
    <div className="App">
      <h1>Ethereum Gas Tracker</h1>
      {feeHistory && (
        <table>
          <thead>
            <tr>
              <th>Block Number</th>
              <th>Base Fee (Gwei)</th>
              <th>Gas Used (%)</th>
            </tr>
          </thead>
          <tbody>
            {feeHistory.map(row => (
              <tr key={row[0]}>
                <td>{row[0]}</td>
                <td>{row[1]}</td>
                <td>{row[2]}%</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}

export default App;

Start the app:

npm start

Visit http://localhost:3000 to see a live-updating dashboard of Ethereum gas metrics.

👉 Access scalable blockchain infrastructure to power your next dApp.


Frequently Asked Questions (FAQ)

Q: Why do I need to track Ethereum gas prices?
A: Monitoring gas prices helps you time transactions strategically, avoiding peak congestion and reducing costs significantly—especially crucial for frequent traders or dApp deployers.

Q: What does EIP-1559 change about gas fees?
A: EIP-1559 introduced a dynamic base fee that adjusts per block and is burned, plus a tip (priority fee) for faster processing. This makes fees more predictable and reduces volatility.

Q: Can I use this tracker for other EVM chains?
A: Yes! Infura supports multiple networks (e.g., Polygon, Arbitrum). Just switch the endpoint URL and test accordingly.

Q: How often should I poll for new data?
A: Polling every 10–15 seconds balances freshness with API rate limits. Ethereum block times average ~12 seconds, so this interval captures most new blocks.

Q: Is there a way to predict future gas prices?
A: While exact predictions are hard, analyzing historical trends (e.g., daily peaks) using extended eth_feeHistory ranges can reveal patterns useful for scheduling transactions.

Q: Do I need a paid Infura plan?
A: No. The free tier supports sufficient requests for personal tracking. Upgrade only if building high-traffic production apps.


Final Thoughts

You now have a fully functional Ethereum gas tracker powered by Infura’s robust API. You’ve learned how gas pricing works post-EIP-1559 and built both a backend script and frontend dashboard for monitoring real-time network conditions.

With this tool, you can:

👉 Supercharge your blockchain analytics with advanced tools and APIs.

By integrating timely data into your development workflow, you gain a competitive edge—making smarter, faster, and cheaper decisions on Ethereum.