Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

43
Views
Web3.js Script exits while listening to CreatedPairs

I am trying to create a simple script to test the event listening functionality of Web3.js CreatedPairs. However, my script runs through the code once and then exits instead of continuing to listen for created pairs and I cannot figure out why.

const Web3 = require('web3')
const web3 = new Web3(Web3.givenProvider || 'https://mynodeishere');

const IUniswapV2Factory = require("@uniswap/v2-core/build/IUniswapV2Factory.json")
const UNI_FACTORY_ADDRESS = '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f'
const uFactory = new web3.eth.Contract(IUniswapV2Factory.abi, UNI_FACTORY_ADDRESS)


const main = async () => {

    // Create event listener to listen to PairCreated
    uFactory.events.PairCreated({}, async (error, event) => {
    
        console.log(`New pair detected...\n`)

    })
}

main()

What ends up happening is when I run node ./myapp.js. The code gets stepped in to and logs New pair detected... to the console and then exits. This happening right away tells me that it is not executing when a new pair is detected and is instead just stepping through the code.

However, what I anticipated happening, was for the app to continue to run and log to the console only when a new pair is detected. I am sure I am overlooking something small, but any help would be appreciated.

11 months ago · Santiago Trujillo
1 answers
Answer question

0

In this context, Web3.givenProvider is null, so the HTTP provider is used.

To be able to subscribe to events, you need to use a WSS provider.

// example connection to a WSS provider
const web3 = new Web3('wss://mainnet.infura.io/ws/v3/<yourtoken>');
11 months ago · Santiago Trujillo Report
Answer question
Find remote jobs