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:
- Ethereum Node Communication: Connect via HTTP, IPC, or WebSocket.
- Smart Contract Interaction: Deploy and manage contracts programmatically.
- Transaction Handling: Send Ether and query transaction details.
Why Use Web3.js?
- Simplified Development: Abstracts complex RPC calls into easy-to-use methods.
- Real-Time Data: Subscribe to events like new blocks or pending transactions.
- Scalability: Integrates seamlessly with decentralized applications (dApps).
Ethereum Node Basics
What Is an Ethereum Node?
A node is a computer running Ethereum client software (e.g., Geth, Nethermind). Nodes:
- Validate transactions and blocks.
- Maintain a copy of the blockchain.
- Serve data to applications via RPC endpoints.
Setting Up a Node
Choose one of these options:
- Self-Hosted Node: Run Geth or OpenEthereum locally (Geth installation guide).
Node-as-a-Service (NaaS):
👉 Compare node providers and pricing
Fetching Transaction Data with Web3.js
Step-by-Step Guide
Initialize a Node.js Project
mkdir eth-transactions && cd eth-transactions yarn init -y touch index.jsInstall Web3.js
yarn add web3Connect to an RPC Endpoint
const Web3 = require('web3'); const web3 = new Web3('YOUR_RPC_ENDPOINT');Listen for New Blocks
web3.eth.subscribe('newBlockHeaders', (error, blockHeader) => { if (!error) console.log(blockHeader.number); });Retrieve Block Transactions
web3.eth.getBlock('latest').then(block => { console.log(block.transactions); // Array of transaction hashes });
Example Output
A block object includes:
transactions: List of transaction hashes.timestamp: When the block was mined.gasUsed: Total gas consumed.
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?
- Web3.js: Official Ethereum Foundation library; broader feature set.
- Ethers.js: Lighter, more modular; better for frontend dApps.
Final Notes
- Use Astra DB for scalable blockchain data storage (learn more).
- Questions? Email
[email protected].
👉 Explore Ethereum development tools
By mastering Web3.js, you unlock the potential to build responsive, data-driven dApps. Start experimenting today!