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.
