eth_subscribe pushes their hashes to you as they enter the transaction pool (mempool), so your application can track transactions
or watch network activity without polling.
This guide subscribes to pending transactions over a WebSocket connection to a peaq node. The example creates the subscription, handles incoming hashes and errors, and cleans up the subscription and the connection on shutdown.
Prerequisites
- Node.js installed.
- A WebSocket endpoint for a peaq node (
wss://quicknode1.peaq.xyz). - The
web3,dotenv, andweb3-providers-wspackages.
Instructions
1. Setting Up the Environment
- Install Dependencies: Install the packages:
- Set ESM Module:
Add the following to your
package.jsonto allow for ESM modules.
- Configure Environment Variables:
Create a
.envfile with the following content:
2. How eth_subscribe works
eth_subscribe is a JSON-RPC method available over WebSocket connections. Calling web3.eth.subscribe('pendingTransactions') tells the node to push a notification for every new transaction it sees in the mempool.
Each notification carries one transaction hash and arrives on the subscription’s "data" event. Network errors and dropped connections arrive on its "error" event.
3. Run the example
The script opens a WebSocket provider againstPEAQ_WS_URL, subscribes to pending transactions, and registers a SIGINT handler (Ctrl+C) that unsubscribes and disconnects the provider before exiting.


