Overview
Overview
In this Recipe, we leverage the web3.js library to monitor real-time incoming transactions to a specified address.We’ll use a WebSocket endpoint to listen for new blocks, then inspect the new block to find transactions we might be interested in.
Environment setup
Environment setup
Install node.js in case it is not installed yet.Create a new directory for your project, then install the web3.js library:
npm install web3
Get your Chainstack endpoint
Get your Chainstack endpoint
To run this code, you will need a Chainstack account and an Ethereum archive node.
The code
The code
Here is a breakdown of the code:
- Import and Setup:
- The
Web3
class is imported from theweb3
package. - A new
Web3
instance is created, connected to an Ethereum node through a WebSocket URL (NODE_URL
). - A specific Ethereum wallet address to monitor is defined as
walletAddress
.
- The
- Subscribing to New Block Headers:
- The function
subscribeToNewBlocks
is an asynchronous function that establishes a subscription to thenewBlockHeaders
event usingweb3.eth.subscribe
. - Upon successfully subscribing, it logs the connection status and the subscription ID.
- It attaches two event listeners to the subscription: one for handling new block data (
data
event) and another for handling errors (error
event).
- The function
- Handling New Blocks:
- The
handleNewBlock
function is triggered whenever a new block header is received. - It logs a message indicating it’s scanning for transactions to the specified
walletAddress
. - The function fetches the full block data, including all transactions, using
web3.eth.getBlock
. - It iterates over each transaction in the block, checking if the transaction’s recipient (
to
address) matches thewalletAddress
. - For transactions matching the criteria, it logs the transaction hash, sender address (
from
), recipient address (to
), and the value transferred in Ether.
- The
- Error Handling:
- The
handleError
function logs any errors that occur during the subscription or block handling process.
- The
- Execution:
- The script executes by calling
subscribeToNewBlocks()
, initiating the subscription and monitoring process.
- The script executes by calling
Run the code
Run the code
Now you can get your endpoint and paste it into the
NODE_URL
const. Then you can run it with node YOUR_SCRIPT_NAME