0

I have a simple event subscription using web3:

contract.events.EventName().on('data', async event => {console.log(event)})

For some reason though, the event fires twice using web3 (in other words, the event is logged twice in this example), even though the event only fires once on the blockchain.

This also occurs for getPastEvents:

  contract.getPastEvents("Event").then(events => console.log(events))
  contract.getPastEvents("Event").then(console.log('a'))

Oddly enough, the first is fired twice, the second only once

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • First suspicion has to be that two (identical) event handlers have been attached. Maybe the function that contains the line `contract.events.EventName().on('data', ...)` gets executed twice. – Roamer-1888 Oct 20 '21 at 14:08
  • Nope, only one. If I comment it out nothing fires. If I uncomment it fires twice. – greentriangles1 Oct 20 '21 at 15:21
  • Is there a `.off()` method (as in jQuery)? If so then try `contract.events.EventName().off('data').on('data', async event => {console.log(event)})` (or similar). – Roamer-1888 Oct 20 '21 at 15:34
  • BTW, commenting/uncommenting demonstrates only that another handler isn't attached by some other line of code. It doesn't prove that this line isn't executed twice. – Roamer-1888 Oct 20 '21 at 15:39
  • There is a .off() method but nothing changed – greentriangles1 Oct 20 '21 at 16:02
  • Then it sounds like there are two 'data' events. Is there a reason why that should not be the case? – Roamer-1888 Oct 20 '21 at 17:01
  • I don't fully understand your question – greentriangles1 Oct 20 '21 at 17:46
  • I added another example of web3 firing twice in the original post above. Oddly enough, if you don't pass the callback variable it only fires once – greentriangles1 Oct 20 '21 at 18:36
  • `.then(console.log('a'))` isn't a properly constructed promise string. `.then()` accepts a function. – Roamer-1888 Oct 20 '21 at 19:06
  • When I asked "is there a reason why that should not be the case?", I mean maybe there's a reason why the event fires twice. Maybe that's the correct behaviour. I can't tell from where I'm sitting. – Roamer-1888 Oct 20 '21 at 19:09
  • True, but at least we know it's not an issue with event listeners, given that getPastEvents just grabs previous events, it doesn't listen to any future one's. What could the issue be then? – greentriangles1 Oct 20 '21 at 19:10
  • Black magic ... mystery. – Roamer-1888 Oct 20 '21 at 19:11

1 Answers1

0

The event is not firing twice, you print the log twice.

The first is in this snippet:

contract.events.EventName().on('data', async event => {console.log(event)})

And the second is in this snippet:

contract.getPastEvents("Event").then(events => console.log(events))