Skip to main content

Fetching Real-time Jumbochain Data with Node.js and Ethers

This tutorial will guide you through setting up a Node.js project and using the provided code to fetch and display information about new blocks as they are mined on your connected Jumbochain node.

Prerequisites

1. Node.js and npm (or yarn): Make sure you have Node.js and its package manager

(npm is usually included) installed on your system.

You can download from nodejs.org

2. Access to an Jumbochain Node: You'll need to have an RPC node running that you can connect to

This could be:

  • A local node (as indicated in your code). Make sure it's running and accessible at http://localhost:8575.

  • A connection to a testnet or mainnet RPC provider (search on chailink).

Set Up Your Node.js Project

Create a Project Directory: Open your terminal or command prompt and create a new directory for your project:

mkdir blockchain-watcher
cd blockchain-watcher

Initialize a new Node.js project using npm:

npm init -y

This will create a package.json file in your project directory with default settings.

Install the Ethers Library

The Ethers library is a powerful JavaScript library for interacting with the Ethereum and EVM-compatible blockchains. Let's install the latest version:

npm install ethers

This command will download and install the ethers library and add it as a dependency in your package.json file.

Create Your JavaScript File

Create a new JavaScript file named watcher.js (or any name you prefer) in your project directory.

Paste the following JavaScript code you provided into this watcher.js file.

watcher.js
    import { ethers } from "ethers";

// Replace with your Jumbochain RPC URL
const rpcUrl = "http://localhost:8575";
const provider = new ethers.JsonRpcProvider(rpcUrl)

async function getBlockInfo(blockNumber) {
try {
const block = await provider.getBlock(blockNumber, true);
if (!block) {
return null;
}

const transactionCount = block.transactions.length;
let totalValue = BigInt(0)

for (const tx of block.transactions) {
let t = await provider.getTransaction(tx)
totalValue += t?.value ?? BigInt(0); // Access transaction value safely
}

return {
blockNumber: block.number,
transactionCount: transactionCount,
totalValue: ethers.formatEther(totalValue), // Format to Ether for readability
};
} catch (error) {
console.error(`Error fetching block ${blockNumber}:`, error);
return null;
}
}

async function main() {
let currentBlockNumber = await provider.getBlockNumber();

while (true) {
const blockInfo = await getBlockInfo(currentBlockNumber);

if (blockInfo) {
console.log(
`Block Number: ${blockInfo.blockNumber}, Transactions: ${blockInfo.transactionCount
}, Total Value Transferred: ${blockInfo.totalValue} JNFTC`
);
currentBlockNumber++;
} else {
// If the block is not yet available, wait a bit before trying again
await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 2 seconds
}
}
}

main().catch((error) => {
console.error("An error occurred:", error);
});

Run Your Script

Open your terminal or command prompt and navigate to your blockchain-watcher project directory.

Execute the script

node watcher.js

This will start the script. It will first fetch the current block number and then continuously try to fetch information about subsequent blocks as they are mined.

You should see output in your console similar to this (the block numbers and transaction counts will vary):

Block Number: 17234567, Transactions: 125, Total Value Transferred: 567.890123456789 JNFTC
Block Number: 17234568, Transactions: 88, Total Value Transferred: 234.567890123456 JNFTC
Block Number: 17234569, Transactions: 150, Total Value Transferred: 890.123456789012 JNFTC
... and so on

Stopping the Script

To stop the script, simply press Ctrl + C in your terminal or command prompt.

Further Exploration

This is a basic example. You can extend this script in many ways, such as:

  • Filtering Transactions: Analyze transactions based on the sender, receiver, or the data they contain.

  • Real-time Events: Use Ethers to listen for specific events emitted by smart contracts.

  • Storing Data: Instead of just logging to the console, you could store the block information in a database or file.

  • Error Handling: Implement more robust error handling and potentially retry mechanisms.

  • Connecting to Different Networks: Modify the rpcUrl to connect to other networks (e.g., protojumbo) or other EVM-compatible blockchains.

Happy blockchain exploring!