How to Build an Ethereum Gas Price Tracker using EIP-1559 Standard

Photo by olieman.eth on Unsplash

How to Build an Ethereum Gas Price Tracker using EIP-1559 Standard

Ethereum's evolution is primarily determined by submissions put forward by the community that maintains the network.

The Ethereum network's London Hard Fork, which happened in August 2021, was one of the most significant changes. As part of the fork, EIP-1559 was introduced, which is a better gas pricing scheme than the blind auction approach.

Ethereum has run into some gas price issues while attempting to scale. Many layer two solutions and sidechains arose to address this issue. Still, Ethereum remains the main chain, which needs to be fixed at some point, and EIP-1559 was introduced to lessen the volatility of gas pricing on-chain.

This tutorial will build an ethereum gas tracker using EIP-1559 Standard, implementing a Gas Price Webhook allowing users to receive a notification when the gas price goes below a certain number.

We will also add other statistics (block volume, baseFeePerGas, reward) for the latest 20 blocks.

What is an Ethereum Improvement Proposal (EIP)?

The Ethereum Improvement Proposals procedure entails a developer or group of developers changing the network, evaluated and discussed by the core developers who control Ethereum's Github code repository.

However, EIPs can then be integrated into the core protocol after going through an approval process.

What is EIP-1559?

EIP-1559 is a transaction pricing scheme that includes a burnt fixed-per-block network fee and dynamically expands/contracts block sizes to handle temporary congestion.

EIP-1559 eliminates the first-price auction as the primary method of calculating gas fees. People offer a specific amount of money to pay for their transaction to be processed in first-price auctions, and the highest bidder wins.

The EIP approach begins with a base pricing level which is adjusted based on how busy the network is by the protocol. The base price increases slightly when the network's per-block gas usage exceeds the objective, reducing when capacity falls short of the target. The most significant difference in base charge from block to block is predictable since these base fee increases are restricted.

Prerequisite

We require Node.js and its package manager NPM installed to proceed.

Verify we have nodejs installed using the following terminal command:

node -v && npm -v

The above command should output their respective version number if installed.

Step 1: Create an Alchemy account

Alchemy is a blockchain developer platform that allows us to connect to the Ethereum network and communicate with it, including the most recent gas fee history of blocks, without setting up our nodes.

We can create an Alchemy account for free here.

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

Step 2: Create an Alchemy App (and API key)

After creating a new account successfully, we will be redirected to our dashboard, where we can create an App by clicking on the Create App button as shown below.

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

Let us input the app information as shown below.

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

Next, we will click on the View Key button, which will open a popup with our app's HTTP and Websocket URLs. In this tutorial, we will be using the WebSocket URL.

Step 3: Project Setup and Installation

In this step, we'll create an empty project and install the Alchemy web3.js library dependency using the following commands.

mkdir EIP-1559-App && cd EIP-1559-App
npm init -y
npm install @alch/alchemy-web3
touch index.js

Step 4: Create a web3 client instance using Alchemy SDK

It's pretty easy to set up a client instance using Alchemy web3. Let us update the index.js file using the following code snippet.

const { createAlchemyWeb3 } = require("@alch/alchemy-web3");

// Using WebSockets
const web3 = createAlchemyWeb3(
      "wss://eth-mainnet.alchemyapi.io/v2/<key>" // Websocket URL
 );

In the code snippet above, we will replace the url with our WebSocket URL retrieved from our dashboard earlier.

Step 5: Get Fee History of the most recent 20 Blocks on Ethereum Mainnet

This section will get the gas fees history of the last 20 blocks using the Alchemy eth_feeHistory that returns the base fee, used gas ratio, block volume, and reward.

Let us update the index.js file with the code snippet below.

const { createAlchemyWeb3 } = require("@alch/alchemy-web3");

// Using WebSockets
const web3 = createAlchemyWeb3(
    "wss://eth-mainnet.alchemyapi.io/v2/<key>" // Websocket URL
);

web3.eth.getFeeHistory(20, "latest", [25, 50, 75]).then(console.log)

To retrieve the gas fee history, we will run the following command.

node index.js

We should have something similar to what is shown below.

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

Step 6: Format the result

Although the result from the preceding step is valid, it is unreadable.

The fees are hexadecimal, and the data format makes it impossible to determine which data belongs to which block.

We'll create a function that converts raw data into a list, with each containing data for a specific block. Using the function we wrote, all hexadecimal gas values denominated in wei will be converted to decimals denominated in Gwei.

To achieve this, we will use the following code snippet.

const formatOutput = (data, numBlocks) => {
      let blocksOutput = [];

 for (let i = 0; i < numBlocks; i++) {
     blocksOutput.push({
       blockNumber: data.oldestBlock + i,
        baseFeePerGas: Math.round(Number(data.baseFeePerGas[i]) / 10 ** 9),
          gasUsedRatio: data.gasUsedRatio[i],
          reward: data.reward[i].map((r) => Math.round(Number(r) / 10 ** 9)),
     });
}

      return blocksOutput;
};

After retrieving gas history, we will use the following code snippet to call our formatOutput function.

web3.eth.getFeeHistory(20, "latest", [25, 50, 75]).then((data) => {
      console.log(formatOutput(data, 20));
});

To retrieve the gas fee history, we will run the following command.

node index.js

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

Step 7: Gas Price Webhook Setup and Installation

We have entirely built our application in the previous steps. Still, in this section, we will set up and configure a gas price webhook allowing users to receive a notification when the gas price goes below a certain number.

To update the index.js file, let us create a simple http server using the following code snippet.

const http = require("http");

const { createAlchemyWeb3 } = require("@alch/alchemy-web3");

    //...

//create a server object:
http
      .createServer(function (req, res) {
        res.write("Hello World! This is an Ethereum Gas Price Tracker using EIP-1559 Standard !!!"); //write a response to the client
        res.end(); //end the response
   })
   .listen(80); //the server object listens on port 80

We will run the following command to retrieve the gas fee history and start the http server.

node index.js

Next, we will spin up Ngrok, which we will be using to test our webhook.

To set up ngrok we,

brew install ngrok
ngrok authtoken YOUR_AUTH_TOKEN
ngrok http 80

We will have something similar to what is shown in the image below.

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

Ensure our server is up and running with the ngrok tunnel we just created. Let us navigate to https://f73f-102-89-3-195.ngrok.io on our browser.

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

Note: Chrome browser flags such URL as a malicious or dangerous site.

Step 8: Set up and Test Webhook on Alchemy dashboard

We will navigate to the Notify tab on our Alchemy Dashboard.

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

Next, we will select create a Gas Price Webhook with gas price thresholds we would like to be notified of, and Alchemy will send us notifications when the gas price passes our points.

How to Build Ethereum Gas Price Tracker using EIP-1559 Standard

As shown in the image above, by clicking the TEST WEBHOOK button, we should get a response in our terminal via the ngrok tunnel created.

Gas Price Webhook Notification

Next, we will create our webhook.

Gas Price Webhook Notification

Since we are using ngrok, we should see the webhooks roll in here: http://localhost:4040/inspect/http, as shown below.

Gas Price Webhook Notification

Congratulations! We have successfully built a fully functional Ethereum gas tracker application with a gas fee webhook notification.

Complete code is available on GitHub

Conclusion

This article explained how to build an Ethereum gas price tracker using EIP-1559 Standard with a gas fee webhook notification.

Reference

You may find these resources helpful.

I'd love to connect with you at Twitter | LinkedIn | GitHub | Portfolio

See you in my next blog article. Take care!!!