subscribe("pendingTransactions") allows developers to subscribe to real-time updates about new block headers on the gnosis blockchain; the application will receive notifications whenever a new block is added to the blockchain. The notification will include information about the new block, such as its block number, hash, and timestamp.
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— a keyword identifying the type of event to subscribe to,pendingTransactionsin this case.function— (optional) a callback function that will be called every time a new event of the specified type is received. This function takes two parameters:errorandresult. The error parameter contains any error that occurred while subscribing to the event, and the result parameter contains the data for the event that was received.
Response
string— the hash identifying the pending transaction.
subscribe("pendingTransactions") code example
Note that ethers.js subscriptions require a WebSocket connection.
WebSocketProvider event listeners to react to subscription events:
"pending"— activates for each new pending transaction hash received.provider.on("error", ...)— activates if an error is detected during the subscription.provider.removeAllListeners("pending")— unsubscribes from the pending transactions event.
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 xDAI.
The following is an implementation of this concept using ethers.js subscriptions:
pending event using the provider.on method on a WebSocketProvider. This method registers event listeners that are called whenever a new pending transaction hash is received.
The code defines two event listener functions that are attached to the provider: handleNewPending and handleError. The handleNewPending function is called when a new pending transaction is received; it runs the eth_getTransactionByHash method via provider.getTransaction and extracts the from, to, and value fields. If the value transferred is above 100 xDAI, the data is logged.
The code includes the unsubscribe function that can be implemented in the logic to unsubscribe and exit the program when a condition is met.
The handleError function is called when an error occurs, and it logs an error message.
Finally, the code calls the subscribeTopendingTransactions function, which creates the subscription and attaches the event listeners. When a new pending transaction is received, the handleNewPending function is called to extract the data and log it to the console.