Web3.js – How to Get Past Events and Watch Future Events Separately

eventsweb3js

As discussed before I managed to get past events via

myContract.myEvent({}, { fromBlock: 0, toBlock: 'latest' }).get((error, results) => {

But it seems that for future events I need to watch for them via

myContract.myEvent().watch((error, result) => {

That is real odd in that I need to implement two event handlers – one for past and one for future events. Is there currently a cleaner way of handling this?

Best Answer

Semantically, past events are a finite list, while future events are an infinite list (i.e. stream). The latter can encompass the former, but not the other way around, i.e. you could represent all past and future events as a stream. This is not built in, but it wouldn’t be hard to implement if you really wanted to:

function allEvents(ev, cb) {   
  ev({}, { fromBlock: 0, toBlock: 'latest' }).get((error, results) => {
    if(error) return cb(error)
    results.forEach(result => cb(null, result))
    ev().watch(cb)   
  }) 
}

...

allEvents(myContract.myEvent, (error, e) => {
  ...
})
Related Topic