This Recipe shows you how to leverage subscriptions, WSS endpoints, and web3.js to monitor incoming transactions in real-time.
Overview
Environment setup
npm install web3
Get your Chainstack endpoint
The code
Web3
class is imported from the web3
package.Web3
instance is created, connected to an Ethereum node through a WebSocket URL (NODE_URL
).walletAddress
.subscribeToNewBlocks
is an asynchronous function that establishes a subscription to the newBlockHeaders
event using web3.eth.subscribe
.data
event) and another for handling errors (error
event).handleNewBlock
function is triggered whenever a new block header is received.walletAddress
.web3.eth.getBlock
.to
address) matches the walletAddress
.from
), recipient address (to
), and the value transferred in Ether.handleError
function logs any errors that occur during the subscription or block handling process.subscribeToNewBlocks()
, initiating the subscription and monitoring process.Run the code
NODE_URL
const. Then you can run it with node YOUR_SCRIPT_NAME