Building an Ethereum Gas Fee Tracker

·

Ethereum gas fees are a critical component of any blockchain interaction — whether you're deploying smart contracts, executing transactions, or building decentralized applications (dApps). As network demand fluctuates, so do gas prices, making real-time monitoring essential for developers and users alike. In this guide, you’ll learn how to build your own Ethereum gas fee tracker using Python and Web3.py, enabling you to retrieve live blockchain data such as current gas price, base fee per gas, burnt fees, and network utilization metrics.

By the end of this tutorial, you'll have a functional script that connects to the Ethereum blockchain via Infura, fetches the latest block data, and calculates key gas-related metrics — all in just a few lines of code.

Setting Up Your Development Environment

Before diving into the code, ensure your system has Python and pip installed. Once confirmed, create a dedicated project directory to keep your files organized.

mkdir Web3_Gas_Calculations
cd Web3_Gas_Calculations
touch gas_calc.py

This creates a folder named Web3_Gas_Calculations and initializes a Python file called gas_calc.py, where we'll write our gas tracking logic.

👉 Discover how to streamline blockchain data access with powerful tools

Installing Required Dependencies

The primary library we’ll use is Web3.py, a Python interface for interacting with Ethereum nodes. Install it using pip:

pip install web3

Additionally, you'll need an API endpoint to connect to the Ethereum network. We’ll use Infura, a popular remote procedure call (RPC) service that provides scalable access to Ethereum without requiring you to run your own node.

Head over to infura.io, sign up, create a new project, and copy your HTTPS endpoint URL. This will be used to establish a secure connection to the Ethereum mainnet.

Connecting to Ethereum via Infura

To securely manage your Infura URL, store it as an environment variable. This avoids hardcoding sensitive endpoints directly into your script.

In your terminal, run:

export INFURA_URL="https://mainnet.infura.io/v3/YOUR_PROJECT_ID"

Now, open gas_calc.py and add the following code to initialize the Web3 connection:

import os
from web3 import Web3

try:
    INFURA_URL = os.getenv('INFURA_URL')
    web3 = Web3(Web3.HTTPProvider(INFURA_URL))
    print("Connected to Eth Node (Infura):", web3.is_connected())
except Exception as e:
    print(e)
    print("INFURA CONNECTION FAILED")

Run the script:

python gas_calc.py

If successful, you should see:

Connected to Eth Node (Infura): True

This confirms your application is communicating with the Ethereum blockchain.

Fetching Latest Block Data

Once connected, retrieve information about the most recent block. This block contains vital gas metrics we’ll analyze.

block_data = web3.eth.get_block('latest')

This returns a dictionary-like object containing fields such as gasUsed, gasLimit, and baseFeePerGas.

Extracting Core Gas Metrics

Now, extract the fundamental values needed for our gas tracker:

current_gas_price = web3.eth.gas_price
gas_used = block_data.gasUsed
gas_limit = block_data.gasLimit

These figures form the foundation of our analysis.

Calculating Advanced Gas Metrics

Let’s go beyond raw data by creating functions that compute more insightful metrics.

Base Fee Per Gas

Since the London hard fork (EIP-1559), each block includes a base fee, which is burned rather than given to miners. This fee adjusts dynamically based on network congestion.

def get_base_fee_per_gas():
    global base_fee_per_gas
    try:
        base_fee_per_gas = web3.from_wei(block_data.baseFeePerGas, 'ether')
    except AttributeError:
        print('BASE FEE NOT AVAILABLE')
        base_fee_per_gas = None
    return base_fee_per_gas

Note: Older blocks pre-EIP-1559 won't have this field, hence the error handling.

Burnt Fees

Burnt fees represent the total ETH destroyed in the latest block due to the base fee mechanism:

def get_burnt_fees():
    global burnt_fees
    try:
        burnt_fees = get_base_fee_per_gas() * gas_used
    except:
        burnt_fees = 0
    return burnt_fees

This metric reflects how much value is being removed from circulation — a key economic signal in Ethereum’s deflationary model.

Gas Usage Percentage

This shows how full the latest block is:

def get_gas_used_percentage():
    try:
        percentage = (gas_used / gas_limit) * 100
        return round(percentage, 2)
    except:
        print("GAS USED PERCENTAGE ERROR")
        return 0

A consistently high usage (>90%) indicates network congestion and potentially rising fees.

Gas Target Percentage

Ethereum targets 50% block capacity for optimal fee stability. Deviations influence base fee adjustments:

def get_gas_target_percentage():
    try:
        usage = get_gas_used_percentage()
        if usage < 50:
            return -100 + 2 * usage
        else:
            return 100 - 2 * (100 - usage)
    except:
        print("ERROR GAS TARGET PERCENTAGE")
        return None

A negative value means blocks are underutilized; positive means they’re overfull.

Generating a Gas Fee Report

With all functions in place, print a clean summary:

print("---------------------------")
print("Current Gas Price (wei):", current_gas_price)
print("-------Block Gas Data-------")
print("Gas Used:", gas_used)
print("Gas Limit:", gas_limit)
print("Base Fee Per Gas (ETH):", get_base_fee_per_gas())
print("Burnt Fees (ETH):", get_burnt_fees())
print("Gas Used Percentage (%):", get_gas_used_percentage())
print("Gas Target Deviation (%):", get_gas_target_percentage())

Sample output:

---------------------------
Current Gas Price (wei): 32264456935
-------Block Gas Data-------
Gas Used: 14136173
Gas Limit: 30000000
Base Fee Per Gas (ETH): 3.1914456935e-08
Burnt Fees (ETH): 0.451148284434209755
Gas Used Percentage (%): 47.12
Gas Target Deviation (%): -5.76

👉 Access real-time blockchain analytics with next-gen development tools

Core Keywords

Frequently Asked Questions

Why do Ethereum gas fees change so frequently?

Gas fees fluctuate based on network demand. When many users send transactions simultaneously, miners prioritize those with higher bids. Post-EIP-1559, the base fee automatically adjusts per block depending on whether usage exceeds or falls below 50% of the gas limit.

What is the difference between gas price and base fee?

The gas price is what users pay per unit of gas, composed of the base fee plus optional priority (tip) fees. The base fee is algorithmically determined and burned, while tips go to validators for faster inclusion.

Can I track historical gas prices with this method?

Yes, but this script only fetches the latest block. To analyze historical trends, you’d need to loop through past blocks or use an indexed blockchain database like Astra DB or The Graph.

Is running a full Ethereum node necessary for this?

No — services like Infura or Alchemy provide remote access to Ethereum nodes without requiring you to sync or maintain one yourself. This lowers entry barriers for developers.

How can I reduce gas costs in my dApp?

Consider batching transactions, optimizing smart contract logic, and guiding users to transact during low-usage periods. Real-time gas tracking (like this script) helps inform these decisions.

What are burnt fees and why do they matter?

Burnt fees are ETH destroyed as part of transaction processing under EIP-1559. They reduce circulating supply and can contribute to deflationary pressure when network activity is high — making them important for economic modeling.

👉 Unlock advanced blockchain insights with seamless data integration