0

I have the following code:

import Web3 from 'web3';

function waitForFunds() {
    let web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
    return new Promise((resolve, reject) => {
        web3.eth.subscribe('pendingTransactions').on("data", resolve);
    });
};

(async function () {
    await waitForFunds();
    console.log('Waiting');
})();

I would expect that nodeJS waits until the promise returned by waitForFunds() gets resolved, but instead, NodeJS is just exiting immediately and not waiting for the subscription to resolve the promise upon receiving data. The console never logs "Waiting". Am I doing anything wrong?

2 Answers 2

5

In order to subscribe to events, you need a Websocket endpoint. This is your code updated to use WSS:

var Web3 = require('web3')

async function waitForFunds() {
  let web3 = new Web3(
    new Web3.providers.WebsocketProvider(
      'wss://your-websocket-endpoint/12345'
    )
  )
  return new Promise((resolve, reject) => {
    web3.eth.subscribe('pendingTransactions').on('data', resolve)
  })
}

waitForFunds()
console.log('Waiting')

Also, if you want to list pending transactions, you can use something like this:

var Web3 = require('web3')

const main = async () => {
  var web3 = new Web3(
    new Web3.providers.WebsocketProvider(
      'wss://your-websocket-endpoint/12345'
    )
  )

  var subscription = web3.eth
    .subscribe('pendingTransactions', async (error, result) => {
      if (error) console.log('error', error)
    })
    .on('data', async (transaction) => {
      console.log('TRX >>', transaction)
      const trxDetails = await web3.eth.getTransaction(transaction)
      console.log('trxDetails', trxDetails)
    })

}

main()

You can use Chainstack to get HTTP and WSS endpoints to multiple blockchain protocols.

0

I think that your function waitForFunds should be asynchronous like so in order to wait for the Promise to resolve: async function waitForFunds() {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.