Pending tx out of sync with blocks

I tried to catch all pending tx hashes and then find them inside new blocks. But it has some sync issue. Here is my simplified code example:

const provider = new ethers.providers.WebSocketProvider(
  process.env.PROVIDER_WS_URL
);

const txs = new Map();

provider.on("pending", (hash) => {
  txs.set(hash, Date.now());
});

provider.on("block", (blockNum) => {
  provider.getBlock(blockNum).then((block) => {
    const lastTx = block.transactions.pop();
    // Expected to find block tx inside previousle recorded pending txs
    console.log(block.number, lastTx, txs.get(lastTx));
  });
});

what exactly is not working as expected?
on what chain are you trying to do this?

It is BSC chain. I expect tx first appear in “pending” listener, and then later in “block” listener, as one of block’s transactions.

but at least some of the pending transactions appear later in the new blocks? maybe some pending transactions don’t get processed right away

Your are right, some pended transactions can be skipped and not get included into block. But I found opposite case, when not all transactions, included in block were pended before. Here is example:

const txs = new Map();

provider.on("pending", (hash) => {
  txs.set(hash, Date.now());
});

provider.on("block", (blockNum) => {
  provider.getBlock(blockNum).then((block) => {
    const pended = block.transactions.filter((hash) => txs.has(hash));
    console.log("New block %s", block.number);
    console.log("Total transactions: %s", block.transactions.length);
    console.log("Pended transactions: %s", pended.length);
  });
});

Here Total transaction are always greater than Pended transactions.

New block 13439924
Total transactions: 334
Pended transactions: 322
New block 13439925
Total transactions: 384
Pended transactions: 376

a block has transactions collected from everywhere, maybe our speedy nodes didn’t receive all the pending transactions from everywhere

1 Like