How to Get Real-Time Ethereum Transactions Using Web3.js

·

This article is part of our Web3 development series, focusing on practical ways to interact with the Ethereum blockchain. Today, we'll explore how to use Web3.js to fetch real-time transaction data efficiently.

Understanding Web3.js

Web3.js is a JavaScript library that enables developers to interact with the Ethereum blockchain. It provides tools to connect to nodes, send transactions, deploy smart contracts, and retrieve blockchain data. Key features include:

Why Use Web3.js?


Ethereum Node Basics

What Is an Ethereum Node?

A node is a computer running Ethereum client software (e.g., Geth, Nethermind). Nodes:

Setting Up a Node

Choose one of these options:

  1. Self-Hosted Node: Run Geth or OpenEthereum locally (Geth installation guide).
  2. Node-as-a-Service (NaaS):

👉 Compare node providers and pricing


Fetching Transaction Data with Web3.js

Step-by-Step Guide

  1. Initialize a Node.js Project

    mkdir eth-transactions && cd eth-transactions
    yarn init -y
    touch index.js
  2. Install Web3.js

    yarn add web3
  3. Connect to an RPC Endpoint

    const Web3 = require('web3');
    const web3 = new Web3('YOUR_RPC_ENDPOINT');
  4. Listen for New Blocks

    web3.eth.subscribe('newBlockHeaders', (error, blockHeader) => {
      if (!error) console.log(blockHeader.number);
    });
  5. Retrieve Block Transactions

    web3.eth.getBlock('latest').then(block => {
      console.log(block.transactions); // Array of transaction hashes
    });

Example Output

A block object includes:


Advanced Use Cases

Tracking Specific Transactions

Filter transactions by address or contract:

const txHash = '0x...';
web3.eth.getTransaction(txHash).then(tx => {
  console.log(`Sender: ${tx.from}, Value: ${web3.utils.fromWei(tx.value)} ETH`);
});

Estimating Gas Costs

web3.eth.estimateGas({
  to: '0x...',
  value: web3.utils.toWei('0.1', 'ether')
}).then(gas => console.log(`Estimated gas: ${gas}`));

FAQs

1. How do I handle failed transactions?

Check the status field (0 = failure, 1 = success) in the transaction receipt:

web3.eth.getTransactionReceipt(txHash).then(receipt => {
  console.log(receipt.status ? 'Success' : 'Failed');
});

2. Can I fetch historical transactions?

Yes, loop through block numbers:

for (let i = 0; i < 10; i++) {
  web3.eth.getBlock(i).then(block => console.log(block));
}

3. What’s the difference between Web3.js and Ethers.js?


Final Notes

👉 Explore Ethereum development tools

By mastering Web3.js, you unlock the potential to build responsive, data-driven dApps. Start experimenting today!