0

Based on the docs of ethersjs, I could use the provider.on() function to listen for events and perform some actions. However, would it still work if I don't have a websocket RPC URL?

If it still does work without a websocket RPC, how does it constantly listening for an event?

If it must have a websocket RPC to work, how else can I listen for an emitted event without using a websocket RPC in ethersjs?

3 Answers 3

1

Yes, you can do this without a websocket. provider.on() is leveraging JavaScript event handlers, and has nothing to do with websockets. JS is an event-driven language.

4
  • Behind the scene, since without web sockets, does the library constantly polling for the event every second then? Otherwise, how does it know that a new event has occurred?
    – xenon
    Apr 19, 2022 at 23:22
  • Behind the scenes, JS is an event-driven language. Read up on how the Event-Loop works for a deeper understanding. This is a good place to start developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
    – jstep
    Apr 19, 2022 at 23:56
  • To address your question about polling, it does not do any polling. It's an event-loop and a task queue. The events are processed from the task queue (which is a list of messages to be processed). You (the programmer) can add and remove events from the queue to be processed. Again, there is no polling.
    – jstep
    Apr 20, 2022 at 0:00
  • 1
    I disagree with jstep's answer re: provider.on not using polling. The source code is peppered with polling code: - github.com/ethers-io/ethers.js/blob/… - github.com/ethers-io/ethers.js/blob/…
    – kyzooghost
    Nov 12, 2022 at 16:31
1

With provider.on() you can filter the events only but can not listen them in real-time. websocket connection is essential for subscribing to real-time event listening. HTTP-based providers do not support this functionality.

0

I actually does some polling behind scenes like @kyzooghost mentioned in the comments. The event-loop nature of JS doesn't have anything to do with the type of connection used to get events in realtime.

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.