Resolve Pending Transactions – How to Resolve and End Pending Transaction Checks in ethers.js

ethers.jsjavascriptpending-transactionstxpool

I have the following code scanning the pending transaction pool until my wallet is found:

var scanTxPool = async () => {
    var myWallet = '0x0000000000000000000000000000000000000000';
    var foundWallet = false;
    provider.on("pending", async (txHash) => {
        if (!foundWallet) {
            provider.getTransaction(txHash).then(async (tx) => {
                if (tx && tx.to) {
                    if (tx.from === myWallet) {
                        console.log('Found my wallet!');
                        foundWallet = true;
                    }
                }
            });
        }
    });
    // do other stuff 
}

The code is working great but I have two issues:

  1. While the pending transactions are run in the background, execution continues to "do other stuff." How can I make sure that the pending transaction check is awaited before do other stuff is executed?
  2. Once my wallet is found from the transaction hash I set foundWallet to true so the !foundWallet check stops it from calling getTransaction(txHash). However, the pending txHash check is still executed indefinitely. How can I cleanly end the pending transaction check once my condition has been met?

Edit: Please see a solution from zemse at the ethers-io repo that still didn't work for me: https://github.com/ethers-io/ethers.js/discussions/2176#discussioncomment-1487598

Best Answer

Your concept is bit wrong. provider.on("pending", ...) is called listener and it is should be called globaly. So it will listen for pending transactions and when find one it would notify you by executing the function passed as second parameter.

const completion = (tx) => {
   /* do some stuff */
}

const checkTxHash = async (txHash) => {
    const tx = await provider.getTransaction(txHash)
    if (!tx || !tx.to) return

    if (tx.from === myWallet) {
        console.log('Found my wallet!')
        provider.removeAllListeners()
        completion(tx)
     }
              
}

provider.on("pending", checkTxHash);
Related Topic