subscribe("pendingTransactions") allows developers to subscribe to real-time updates about pending transactions on the Ethereum blockchain; the application will receive notifications whenever a pending transaction appears on the blockchain.
If you are using this method to track your own transactions, make sure MEV protection is disabled. Otherwise you won’t detect them as they go through a private pool.
Get your own node endpoint today
Start for free and get your app to production levels immediately. No credit card required.You can sign up with your GitHub, X, Google, or Microsoft account.Parameters
string— the event name to subscribe to,"pending"in ethers.js, which maps to thependingTransactionssubscription.function— a listener function that is called every time a new pending transaction is received. In ethers.js this listener receives a single parameter, the transaction hash.
Response
string— the hash identifying the pending transaction.
subscribe("pendingTransactions") code example
Note that ethers.js subscriptions require a WebSocket connection, so use
ethers.WebSocketProvider.provider.on("pending", listener)— registers a listener that runs for each new pending transaction and receives the transaction hash.listener— your callback handles any errors internally, so wrap the work in atry...catchblock.provider.off("pending", listener)— removes the listener to stop receiving pending transactions.provider.destroy()— closes the WebSocket connection when you are done.
Use case
A practical use case forsubscribe("pendingTransactions") is a DApp that continuously listens for new pending transactions, then isolates the from, to, and value fields for analytics purposes. This is useful, for example, to only track transactions that move at least a certain amount of ETH.
The following is an implementation of this concept using ethers.js subscriptions:
provider.on("pending", listener) method on a WebSocketProvider. This registers a listener that runs for every new pending transaction hash.
The code defines the handleNewPending listener function that is attached to the provider. The handleNewPending function is called when a new pending transaction is received; it runs the eth_getTransactionByHash method and extracts the from, to, and value fields. If the value transferred is above 1 ETH, the data is logged.
The code includes the unsubscribe function that can be implemented in the logic to remove the listener, close the connection, and exit the program when a condition is met.
Finally, the code calls the subscribeToPendingTransactions function, which creates the subscription and attaches the listener. When a new pending transaction is received, the handleNewPending function is called to extract the data and log it to the console.