Back to homepage

Easy way to monitor pending transactions from the mempool

Published

Blockchain transaction lifecycle

When a user submits a transaction from his wallet, the transaction goes directly to a blockchain node, which makes sure that it's formatted correctly.

Once the transaction is validated by the node that received it directly from the user, the transaction is added to the mempool and propagated to other nodes.

What is the mempool?

The blockchain memory pool is where all unconfirmed transactions are kept before they're picked up by a miner and added to a block.

Monitoring pending transactions in the blockchain transaction pool is commonly used by applications like flash loans, arbitrage bots, and other apps.

How to monitor pending transactions from the mempool

To monitor pernding transactions from the mempool, we need access to a blockchain node. Chainstack is my go-to node provider as they offer a pretty generous free plan, support many blockchain protocols, and it's super easy to use. Follow these links to:

We'll connect via websocket to receive events of pending transactions directly from our node. The pendingTransactions event returns the transaction id of every transaction added to the mempool, however, it does not include the transaction details, like the address from and to, the amount, gas fees etc.

To obtain the specific transaction details, we need to do an additional query to the node, this time using the web3.eth.getTransaction() method and passing the transaction id.

Here is the full code:

var Web3 = require('web3');

const main = async () => {
  //
  const options = {
    reconnect: {
      auto: true,
      delay: 2000,
      maxAttempts: 3,
      onTimeout: false,
    },
  };
  const web3 = new Web3(
    new Web3.providers.WebsocketProvider(
      'wss://your-node-endpoint/12345-abcde',
      options
    )
  );

  // subscribe to pendingTransactions events
  web3.eth
    .subscribe('pendingTransactions', async (error, result) => {
      if (error) console.log('error', error);
    })
    .on('data', async (trxId) => {
      // receives the transaction id
      console.log('🧮 TRX ID >> ', trxId);
      // query all transaction details using its id
      const trxDetails = await web3.eth.getTransaction(trxId);
      console.log(`📑 TRX ${trxId} DETAILS >> `, trxDetails);
    });
};

main();

TAGS

If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Buy Me A Coffee