Building an Ethereum Gas Fee Tracker

ยท

Introduction to Ethereum Gas Fees

Ethereum gas fees are a fundamental aspect of Web3 development, representing the transaction costs on the Ethereum network. These fees fluctuate based on network demand, much like fuel prices for vehicles. Understanding and tracking gas fees is essential for developers and users engaging with decentralized applications (dApps), smart contracts, and DeFi platforms.

Step-by-Step Guide to Building a Gas Fee Tracker

1. Project Setup

Create a new directory and Python file for your project:

mkdir Web3_Gas_Calculations
cd Web3_Gas_Calculations
touch gas_calc.py

2. Install Required Dependencies

Install the Web3.py library to interact with the Ethereum blockchain:

pip install web3

3. Connect to Infura

Sign up on Infura to obtain a Web3 API URL. Set your environment variable:

export INFURA_URL=<Your_Infura_URL>

4. Establish Connection

Use the following Python code to connect to Infura:

import os
from web3 import Web3

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

Run the script:

python gas_calc.py

5. Retrieve Block Data

Fetch the latest block data:

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

6. Extract Gas Metrics

Calculate key gas metrics:

currentGasPrice = web3.eth.gas_price
gasUsed = block_data.gasUsed
gasLimit = block_data.gasLimit

7. Create Utility Functions

Base Fee Per Gas

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

Burnt Fees

def get_burnt_fees():
    try:
        burnt_fees = get_base_fee_per_gas() * block_data.gasUsed
    except:
        burnt_fees = str(0)
    return burnt_fees

Gas Used Percentage

def get_gas_used_percentage():
    try:
        gasUsedPercentage = (block_data.gasUsed / gasLimit) * 100
        return gasUsedPercentage if gasUsedPercentage > 0 else 0
    except:
        print("GAS USED PERCENTAGE ERROR")
        return 0

Gas Target Percentage

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

8. Generate Report

Print the collected data:

print("---------------------------")
print("Current Gas Price: " + str(currentGasPrice))
print("-------Block Gas Data-------")
print("Gas Used: ", gasUsed)
print("Gas Limit: ", gasLimit)
print("Base Fee Per Gas: ", get_base_fee_per_gas())
print("Burnt Fee: ", get_burnt_fees())
print("Gas Used Percentage: ", get_gas_used_percentage())
print("Gas Target Percentage: ", get_gas_target_percentage())

Example Output:

Connected to Eth Node (Infura): True
---------------------------
Current Gas Price: 32264456935
-------Block Gas Data-------
Gas Used: 14136173
Gas Limit: 30000000
Base Fee Per Gas: 3.1914456935E-8
Burnt Fee: 0.451148284434209755
Gas Used Percentage: 47.12057666666667
Gas Target Percentage: -5.758846666666656

Advanced Solutions: Astra Block

๐Ÿ‘‰ Simplify Ethereum development with Astra Block, which offers indexed blockchain data without the need for complex node management. Access real-time gas prices and other metrics effortlessly.

FAQ

Why do Ethereum gas fees fluctuate?

Gas fees vary based on network congestion. Higher demand increases fees, while lower demand reduces them.

How can I reduce gas costs?

Schedule transactions during off-peak hours or use Layer 2 solutions like Optimism or Arbitrum.

What is the difference between gasUsed and gasLimit?

gasUsed is the amount of gas consumed in a block, while gasLimit is the maximum gas allowed per block.

Can I predict future gas fees?

While exact predictions are impossible, tools like Etherscan's gas tracker provide historical trends for estimation.

Is Infura the only option for connecting to Ethereum?

No, alternatives include Alchemy, QuickNode, or running your own node.

Conclusion

Tracking Ethereum gas fees is critical for optimizing transaction costs. This guide provides a foundational approach using Web3.py and Infura. For a streamlined experience, consider leveraging Astra Block to access comprehensive blockchain data without infrastructure overhead.