Search code examples
node.jsweb3js

How to track the status of a crypto transaction in Node.js backend?


I think I would need an async function to stop it from blocking the server. But I wonder how often I should check the status of a transaction and if I should somehow add a queue to avoid having too many transactions being tracked simultaneously. If my server needs to make too many checking calls periodically, it may also slow down the server.

Currently, I have found a function that can check the status of a transaction until it is timeout (120 seconds).

  function checkIfTransactionProceed(txHash: string) {
    return new Promise<void>(async (resolve, reject) => {
      var receipt = null;
      var counter = 0;
      while ((receipt = await web3.eth.getTransactionReceipt(txHash)) === null) {
        if (counter++ > 120) {
          break;
        }
        setTimeout(() => {
          return;
        }, 1000);
      }
      if (receipt && (receipt.status === true)) {
        resolve();
      }
      else {
        reject();
      }
    })
  }

Would that be a trouble if I just call this function every time I receive a transaction, make a callback function and leave it running by itself? Would it cause performance issue, and should I (or how to) limit the number of promises to exist?


Solution

  • Turns out I can simply use web3 in the backend as Node.js supports it as well. So as that function does work on the frontend, it also works on the backend.