How to Build a Real-Time Ethereum Data Monitor with QuickNode and CoinGecko

How to Build a Real-Time Ethereum Data Monitor with QuickNode and CoinGecko

Tracking Ethereum Price and Block Number

Introduction

In today's rapidly evolving blockchain ecosystem, staying informed about the latest Ethereum price movements and blockchain data is essential for traders, developers, and enthusiasts alike. In this article, we'll explore how to build a real-time data monitor using QuickNode for Ethereum blockchain data and CoinGecko for cryptocurrency price information.

Introduction to QuickNode and CoinGecko

QuickNode is a leading blockchain infrastructure provider that offers fast and reliable access to Ethereum nodes. With QuickNode, developers can interact with the Ethereum blockchain seamlessly, accessing real-time data and deploying smart contracts with ease. On the other hand, CoinGecko is a popular cryptocurrency data platform that provides comprehensive market data, including prices, trading volume, and market capitalization, for a wide range of cryptocurrencies.

By leveraging QuickNode's infrastructure and CoinGecko's API, we can create a robust real-time data monitor that fetches the latest Ethereum price and block number at regular intervals.

Prerequisites

Before we begin, ensure you have the following prerequisites:

  1. Basic knowledge of JavaScript and Node.js.

  2. A QuickNode account and API key. Sign up here

  3. Access to the CoinGecko API.

Setting Up the Project

Let's start by setting up our project and installing the necessary dependencies:

bashCopy codemkdir ethereum-data-monitor
cd ethereum-data-monitor
npm init -y
npm install axios

Now, create a new file named index.js in your project directory.

Fetching Ethereum Data

We'll begin by fetching Ethereum blockchain data using QuickNode's RPC endpoint. The following code snippet demonstrates how to fetch the latest Ethereum block number:

const axios = require('axios');

// QuickNode CoinGecko Addon endpoint
const quickNodeRpcEndpoint = `YOUR_QUICKNODE_COINGECKO_ADDON_ENDPOINT`;

// Function to fetch Ethereum data using QuickNode's RPC endpoint
async function getEthereumData() {
  try {
    // Example: Get the latest block number
    const blockNumberResponse = await axios.post(quickNodeRpcEndpoint, {
      jsonrpc: '2.0',
      method: 'eth_blockNumber',
      params: [],
      id: 1,
    });

    const latestBlockNumberHex = blockNumberResponse.data.result;
    const latestBlockNumber = parseInt(latestBlockNumberHex, 16); // Convert hex to decimal
    console.log('Latest Ethereum block number:', latestBlockNumber);
  } catch (error) {
    console.error('Error fetching Ethereum data:', error.message);
  }
}

In this code snippet:

  • We import the Axios library for making HTTP requests (const axios = require('axios')). Axios is a promise-based HTTP client for the browser and Node.js.

  • We define the QuickNode CoinGecko Addon endpoint (quickNodeRpcEndpoint). This endpoint is provided by QuickNode and represents the RPC endpoint for accessing the CoinGecko Addon functionality. You should replace 'YOUR_QUICKNODE_COINGECKO_ADDON_ENDPOINT' with the actual endpoint provided by QuickNode.

  • We create an asynchronous function named getEthereumData(). This function is responsible for fetching Ethereum blockchain data using QuickNode's RPC endpoint.

  • Inside the function, we use a try...catch block to handle any potential errors that may occur during the API request.

  • We use Axios (axios.post()) to make a POST request to the QuickNode RPC endpoint (quickNodeRpcEndpoint).

  • The JSON-RPC request contains:

    • jsonrpc: The JSON-RPC protocol version (set to '2.0').

    • method: The method we want to call on the Ethereum blockchain, which is eth_blockNumber to fetch the latest block number.

    • params: An empty array because the eth_blockNumber method does not require any parameters.

    • id: A unique identifier for the request (set to 1).

  • After sending the request, we await the response (await axios.post(...)).

  • If the request is successful, we extract the latest Ethereum block number from the response data (blockNumberResponse.data.result) and convert it from hexadecimal to decimal using parseInt(latestBlockNumberHex, 16). We then log the latest Ethereum block number to the console.

  • If an error occurs during the request, we catch the error and log an error message to the console, including the error message provided by Axios (error.message).

This function encapsulates the logic for fetching Ethereum blockchain data using QuickNode's RPC endpoint, making it reusable and easy to call from other parts of the code.

Exploring the QuickNode Smart Contract Explorer

Now, let's enhance our code to fetch the latest Ethereum price from CoinGecko QuickNode CoinGecko Addon:

// Function to fetch Ethereum price from CoinGecko using QuickNode CoinGecko Addon
async function getEthereumPrice() {
  try {
    const response = await axios.post(quickNodeRpcEndpoint, {
      jsonrpc: '2.0',
      method: 'cg_simplePrice',
      params: ['ethereum', 'usd'],
      id: 1,
    });

    const ethereumPrice = response.data.result.ethereum.usd;
    console.log('Latest Ethereum price (USD):', ethereumPrice);
  } catch (error) {
    console.error('Error fetching Ethereum price:', error.message);
  }
}

// Call the functions to fetch Ethereum data
getEthereumPrice();
getEthereumData();

In this enhanced code snippet:

  • This function is an asynchronous function (async function) named getEthereumPrice(). It is responsible for fetching the latest Ethereum price from CoinGecko using QuickNode's CoinGecko Addon.

  • Inside the function, we use a try...catch block to handle any potential errors that may occur during the API request.

  • We use Axios (axios.post()) to make a POST request to the QuickNode RPC endpoint (quickNodeRpcEndpoint), which is provided by QuickNode and includes your QuickNode API key. This endpoint allows us to access the CoinGecko Addon functionality.

  • The JSON-RPC request contains:

    • jsonrpc: The JSON-RPC protocol version (set to '2.0').

    • method: The method we want to call on the CoinGecko Addon, which is cg_simplePrice to fetch the simple price of Ethereum.

    • params: An array containing the parameters for the method. Here, we pass 'ethereum' (the cryptocurrency) and 'usd' (the currency) to fetch the Ethereum price in USD.

    • id: A unique identifier for the request (set to 1).

  • After sending the request, we await the response (await axios.post(...)).

  • If the request is successful, we extract the Ethereum price from the response data (response.data.result.ethereum.usd) and log it to the console with a message indicating that it's the latest Ethereum price in USD.

  • If an error occurs during the request, we catch the error and log an error message to the console, including the error message provided by Axios (error.message).

  • We call the getEthereumData() and getEthereumPrice() functions initially to fetch Ethereum data and price immediately when the script starts.

This function encapsulates the logic for fetching the Ethereum price from CoinGecko using QuickNode's CoinGecko Addon, making it reusable and easy to call from other parts of the code.

💡
Start Building on QuickNode. Get started for free

Setting up Interval for Real-Time Monitoring

Now that we can fetch Ethereum data, let's set up an interval to continuously monitor and display the latest Ethereum block number and price. We'll modify our code to fetch and display this data every 30 seconds:

// Set interval for real-time monitoring
setInterval(() => {
  getEthereumData();
  getEthereumPrice();
}, 30000); // 30 seconds

This code snippet sets up an interval for real-time monitoring of Ethereum data, ensuring that the latest Ethereum block number and price are fetched at regular intervals. Here's a breakdown of each part:

  1. setInterval(() => { ... }, 30000);: This line calls the setInterval() function, which repeatedly executes a specified function (...) at a given time interval. In this case, the interval is set to 30,000 milliseconds or 30 seconds.

  2. () => { ... }: This is an arrow function that defines the code block to be executed at each interval.

  3. Inside the arrow function:

    • getEthereumData();: This line calls the getEthereumData() function, which fetches the latest Ethereum block number using QuickNode's RPC endpoint.

    • getEthereumPrice();: This line calls the getEthereumPrice() function, which fetches the latest Ethereum price from CoinGecko's API.

To execute the code and fetch real-time Ethereum data, run the following command in your terminal or command prompt after navigating to the directory containing your index.js file:

node index.js

This command will run the code and display the latest Ethereum block number and price in the console every 30 seconds.

Access the Code

Want to explore the code and try it out yourself? Head over to my GitHub repository where you can download or fork the code to build your own real-time Ethereum data monitor.

Link to Github Repository

Feel free to experiment with the code, customize it to suit your needs, or integrate it into your projects. Don't forget to star the repository if you find it helpful and consider contributing by submitting pull requests or raising issues for any improvements or feature requests.

Happy coding!

Conclusion

In this article, we've demonstrated how to build a real-time data monitor for Ethereum using QuickNode for blockchain data and CoinGecko for cryptocurrency prices. By combining these powerful tools, developers can easily create comprehensive solutions to track Ethereum price changes and monitor blockchain data. Whether you're a trader, developer, or blockchain enthusiast, this real-time data monitor provides valuable insights into the Ethereum ecosystem and helps you stay informed about the latest developments.

Now that you have the code and understanding of how to fetch Ethereum data and display it in real time, you can further customize and expand this solution to suit your specific needs and integrate it into your applications or trading strategies.

Additional Resources

I'd love to connect with you on Twitter | LinkedIn | Instagram.

About QuickNode

QuickNode is dedicated to constructing the infrastructure necessary to uphold the forthcoming era of Web3. Since 2017, we've collaborated with numerous developers and organizations, facilitating the expansion of decentralized applications (dApps) and offering superior access to over 25 blockchains. Sign up for our newsletter to access further content similar to this and remain up-to-date with the latest developments in Web3!