Node.js web3 subscription to pending transaction doesn't work

I’m trying to subscribe to the pending transactions using nodejs, web3 and infura, but I’m getting nothing in my console as if there’s no transactions happening in the network. No errors or anything.
What am I doing wrong?

Here’s my code.

const { Web3 } = require('web3');
const web3 = new Web3(`wss://mainnet.infura.io/ws/v3/${projectId}`);
const subscription = web3.eth.subscribe('pendingTransactions', (error, result) => {
    if (!error) {
      console.log(result);
    } else {
      console.error(error);
    }
});
1 Like

Hey, you’ll also need to listen for the subscription data, something like:

const { Web3 } = require("web3");

const web3 = new Web3('wss://mainnet.infura.io/ws/v3/...');
  
async function main() {

const subscription = await web3.eth.subscribe('pendingTransactions');

subscription.on('data', async txHash => {
    console.log('New transaction: ', txHash);
});
subscription.on('error', error =>
    console.log('Error when subscribing: ', error),
);

}

main();
1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.