1

I am using the JavaScript API in my truffle tests to get the events from the contract: https://github.com/ethereum/wiki/wiki/JavaScript-API#contract-allevents

          const allEvents = instance.allEvents({
            fromBlock: 0,
            toBlock: 'latest'
          });
          allEvents.watch((err, res) => {
            console.log(res);
          });

It never stops listening so I tried adding this to the end:

          allEvents.stopWatching()

The listening stops, but nothing is ever logged, so I tried adding a delay:

          setTimeout(allEvents.stopWatching, 1000);

But the listening doesn't stop.

How do I stop listening after all the events emitted till now have been retrieved?

2
  • What version of web3 are you using? Which condition should cause to stop watching all events? If you call .stopWatching() immediately after .watch() it will stop there before any event, setTimeout might not work because allEvents.stopWatching is a function without a binding. – Ismael Sep 18 '18 at 15:27
  • web3 Version '0.20.6' included in Truffle. The condition that should cause it to stop watching is that it got all the past events, but I don't know how to identify that. – Harsha Laxman Sep 22 '18 at 15:43
1

1) Using Indexed parameters e.g address or integers can also be very useful

Examplen using ERC20.solcheck here Erc20.transfer should emit event(address _to, uint256 _amount) which can be indexed thus making it easier to filter at the front end event Transfer(address indexed _to, uint256 _amount); contract events

could be written this way, and you get events only from the indexed address and indexed amount during transfer.

Erc20.events.Transfer({ filter: { _to: recipient, _amount: amount} })
        .on("data", function(event) {
....
        }).on("error", console.error);
      }

I hope someone finds this helpful, I'm also open to correction.

0

It says that if you pass a callback function you don't need to call stopWatching(). The problem is somewhere else so just abandon the idea of using stopWatching. Could you try this implementation instead:

const allEvents = instance.allEvents({
        fromBlock: 0,
        toBlock: 'latest'
      });
      allEvents.watch((err, res) => {
        if (!error)
        console.log(res);
      });

Give me an update

1
  • Same as before, doesn't stop listening – Harsha Laxman Sep 17 '18 at 1:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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