Seeing as there isn't a detailed updated answer:
As @pors mentioned, web3.js has a getPastEvents
function. You can have it run at startup, using a syntax like:
myContract.getPastEvents('MyEvent');
The docs for this function are here. You can also filter by a specific topic, set a range of blocks to check, and more. Here's an expanded example, taken straight from the docs linked above:
myContract.getPastEvents('MyEvent', {
filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
fromBlock: 0,
toBlock: 'latest'
}, function(error, events){ console.log(events); })
.then(function(events){
console.log(events) // same results as the optional callback above
});
This will not continue listening for events to the best of my knowledge. You could do this with events
, however:
MyContract.events.MyEvent()
The function takes an object with parameters as an argument, much like getPastEvents()
, see the docs here for more details. Based on the question, this would seem to be the best fit for the OP's particular use case.
(There is a similar function called allEvents
for subscribing to all events from a particular contract - docs)
@pors also suggests using subscribe
to get past events, and to continue to listen for new events. The docs are here. Note that you'll need to provide the topics
you want to listen for. (Here's an explainer for event topics, you can get the topic for your event by hashing the event signature (eg Transfer(address,address,uint256)
of the event with keccak256).
This looks to me like a race condition.
The watch
callback is executed asynchronously when data matching your filter is polled from the node. Calling myEvent.watch
is non-blocking and as such myEvent.stopWatching()
will be called immediately afterwards.
The result you will get depends on whether the polling completes in the milliseconds before stopWatching
is called.
This is non-deterministic - you might get different results each time you run it.
Best Answer
There's approximately 12,343 blocks every two days, so finding the current block number and subtracting that amount would give the block number to target. Pass that in as the
fromBlock
parameter to thegetPastEvents
function to limit to that range: