ETH transactions subscriptions

Web3 API doesn’t allow you to subscribe directly to a wallet’s incoming transactions, so to solve our particular problem, we have to use a different strategy. First, we subscribe to all pending transactions, then we filter them by the sender’s wallet address and certain other criteria.

Web3.js allows us to talk directly to an Ethereum node via multiple protocols, including HTTP and WebSockets. For example, I use Rinkeby Testnet and nodes provided by Infura. However, you a free to use any other provider, including local nodes.

In the function shown below, a new web3 instance with the WebSockets provider is created and used to establish a subscription to newly created transactions in blockchain. This instance is called pending.

A subscription object can be created using two methods, subscribe() and unsubscribe(). Both of them accept a callback function to handle errors and any results of subscribing. There are two events that we can handle with subscriptions to pending transactions: data and error. Certainly, data is the essential event that we need for finding the transfer.

A data event handler only has one input parameter, which represents a transaction hash and checks every transaction for compliance with our search criteria when we need more details than just a hash. That’s where a different web3.js method, getTransaction(), can be used for reading transaction details. As this is an asynchronous call, I simply wrap it into a try-catch statement and await for the response. You can find the response object format in the official documentation for web3 here.

Once a response is received and the transaction matches our filter conditions, we need to initiate the transaction confirmation process and cancel the subscription by calling its unsubscribe() method. If we don’t have a transaction that satisfies our filter, we simply return from function to stay subscribed.

The function is shown below, but also you could get full workable blockchain tracker example source code here.

Please note that the above examples uses HttpProvider to get transaction details, because the risk of having a connection error with WebSockets is much higher. I had at least two errors during a thirty-minute observation with WebSocketProvider and none with HttpProvider.