codingraj's blog

codingraj's blog

Build a ETH Gas Price Tracker and convert to USD with HTML, CSS, Vanilla JavaScript, and Web3.js library

Build a ETH Gas Price Tracker and convert to USD with HTML, CSS, Vanilla JavaScript, and Web3.js library

Get the ETH Gas Price using the Web3.js library every 1 second and convert it to USD using a 3rd party Currency Converter API.

codingraj's photo
codingraj
·Feb 27, 2022·

5 min read

Subscribe to my newsletter and never miss my upcoming articles

My Table of content

Intended Audience

  • Experience or familiarity of using JavaScript to write into HTML elements
    • document.createElement()
    • document.createTextNode()
    • appendChild()
    • insertBefore()
  • Experience or familiarity of using 3rd party API
  • Newbies are welcome. Follow along and google (I use DuckDuckGo) anything you need more clarity on. Intermediate/Advanced programmers do this all the time.

What are we Building?

  • A website (demo link)
    • Gets the current gas price using the Web3.js API every 1 second
    • Display the current price gas price in WEI, ETH
    • Convert and display the current gas price in USD using a 3rd party currency converter API
    • show a trend in % if the gas price is rising or falling from the previous price
  • We will be using HTML, CSS, and Vanilla JavaScript to build the website.
  • The code is publicly available at GitHub.

Prerequisite

  • Any code editor (I use VSCode)

Folder Structure

project folder
│   index.html
│   script.js
│   style.css

Create Layout with HTML and CSS

Open up your code editor (I use VSCode). Create a folder. I called mine web3-playground.

Any name will do.

Create an HTML file called index.html

VSCode has a shortcut to create an HTML boilerplate. Type:

!

or copy below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

</body>
</html>

Give your HTML page a title. Any title will do.

<title>Web3.js Gas Price Tracker</title>

Create a header and main section. We will create a 4 column layout showing Gas Price in Wei, Gas Price in ETH, Gas Price in USD, and the % trend from the price 1 second ago.

  <body>
    <header>
      <h1>Web3.js Gas Price Tracker</h1>
    </header>
    <main>
      <div class="gas-price">
        <p class="column-header">gas wei:</p>
        <ul id="parent">
          <!-- This is where the current Gas Price in Wei goes -->
        </ul>
      </div>
      <div class="eth-price">
        <p class="column-header">gas eth:</p>
        <ul id="parent-eth">
          <!-- This is where the current Gas Price in ETH goes -->
        </ul>
      </div>
      <div class="usd-price">
        <p class="column-header">gas usd:</p>
        <ul id="parent-usd">
          <!-- This is where the current Gas Price in USD goes -->
        </ul>
      </div>
      <div class="trend">
        <p class="column-header">trend:</p>
        <ul id="parent-trend">
          <!-- This is where we show the % change in prices from 1 second ago -->
        </ul>
      </div>
    </main>
  </body>

Add some CSS to format the layout with Grid and add some color.

Create a CSS file called: style.css

Create a link to the CSS file on index.html in the head section.

<link rel="stylesheet" href="style.css">

Open style.css and set the box-sizing to border-box. Use the body tag to create the Grid for the header and main section. We will also use Grid in the Main element to create a 4 column layout for the Gas Prices.

/* Box sizing rules */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* Set Grid Layout and line height */
body {
  display: grid;
  grid-template-rows: auto 1fr;
  text-rendering: optimizeSpeed;
  line-height: 1.5;
}

main {
  grid-row: 2 / 3;
  padding: 2vw;
  margin: 2vw;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
}

.gas-price {
  grid-column: 1 / 2;
}

.eth-price {
  grid-column: 2 / 3;
}

.usd-price {
  grid-column: 3 / 4;
}

.trend {
  grid-column: 4 / 5;
}

.column-header {
  text-align: center;
  font-size: larger;
  background-color: beige;
}

Write Client-Side JavaScript

Create a file called script.js in the root folder.

Add a script tag to link the script.js to the index.html.

Add a script tag to link the web3.js library to the index.html.

<​script​ ​src​="​https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js​"></​script​>
<script src="/script.js"></script>

To read the Ethereum blockchain, you need a gateway to read it. Cloudflare provides a gateway that is free to use. Just use this URL https://cloudflare-eth.com.

const web3 = new Web3("https://cloudflare-eth.com");

// this variable will be the HTML ID value for the gas prices.
let dynamicElementID = 0;

// get gas price and convert to eth and usd every 1 second using the Set Interval Function
const interval = setInterval(function () {
  // when this function runs every 1 second, we will increment the ID value by 1. This will make more sense later in the code
  dynamicElementID = dynamicElementID + 1;

  // get gas price in WEI from Web3.js
  web3.eth.getGasPrice().then((data) => {
    // create bullet point element and assign an ID
    // the ID is used to compare the current price and the last price 1 second ago
    let timeOutResults = document.createElement("li");
    timeOutResults.id = dynamicElementID;

    // bind and display WEI gas price to the html element
    let textNode = document.createTextNode(data);
    timeOutResults.appendChild(textNode);
    let parent = document.getElementById("parent");
    parent.insertBefore(timeOutResults, parent.childNodes[0]);

    // get gas price in ETH from Web3.js and show 12 decimal places
    let etherValue = Web3.utils.fromWei(data, "ether");
    etherValue = Number(etherValue).toFixed(12);

    // bind and display ETH gas price to the html element
    let ethResults = document.createElement("li");
    let ethTextNode = document.createTextNode(etherValue);
    ethResults.appendChild(ethTextNode);
    let parentETH = document.getElementById("parent-eth");
    parentETH.insertBefore(ethResults, parentETH.childNodes[0]);

    // calculate the trend
    // grab last price using the ID created 1 second ago (current ID - 1)
    let lastPriceID = dynamicElementID - 1;
    let lastPrice = document.getElementById(lastPriceID);

    // get current price in WEI
    let currentPrice = data;

    //calculate the difference between the current price and last price in percentage
    let difference = Math.floor(
      ((currentPrice - lastPrice.innerText) / lastPrice.innerText) * 100
    );

     // bind and display trend % to the html element
    let trendResults = document.createElement("li");
    trendResults.id = "trend-" + dynamicElementID;
    let trendTextNode = document.createTextNode(difference + "%");
    trendResults.appendChild(trendTextNode);
    let parentTrend = document.getElementById("parent-trend");
    parentTrend.insertBefore(trendResults, parentTrend.childNodes[0]);

    //convert ETH to USD using a free Currency Converter API

    fetch("https://api.cryptonator.com/api/full/eth-usd")
      .then((response) => response.json())
      .then((data) => {
        let usdResults = document.createElement("li");
        let usdPrice = etherValue * data.ticker.price;
        let usdTextNode = document.createTextNode("$" + usdPrice.toFixed(4));
        usdResults.appendChild(usdTextNode);

        // use color to show if the trend is staying the same (yellow), increasing (green), or decreasing (pink)
        if (difference === 0) {
          trendResults.style.backgroundColor = "yellow";
          usdResults.style.backgroundColor = "yellow";
        }

        if (difference > 0) {
          trendResults.style.backgroundColor = "lightgreen";
          usdResults.style.backgroundColor = "lightgreen";
        }

        if (difference < 0) {
          trendResults.style.backgroundColor = "lightpink";
          usdResults.style.backgroundColor = "lightpink";
        }

        let parentUSD = document.getElementById("parent-usd");
        parentUSD.insertBefore(usdResults, parentUSD.childNodes[0]);
      });
  });
}, 1000);

You now have an ETH Gas Tracker that updates every 1 second using the Web3.js library built with HTML, CSS, and Vanilla JavaScript.

 
Share this