I deployed my smart contract to the network and building frontend which will interact with the smart contract. The problem is when I get the event logs using web3.contract.getPastEvents(), it returns all the events that is occurred so far. My smart contract emits lots of events a day, so one year later, there will be so many event logs saved, and this means the getPastEvents() function would return big data. However, I only need 100 latest events. This is my current code which returns all events.

const events = await factory.getPastEvents('allEvents', {
        filter: { from: account },
        fromBlock: 0,
        toBlock: 'latest'

How can filter 100 latest events only? Of course, I can filter using block number but I can't ensure how many blocks would contain exactly 100 events. Any solution?

1 Answer 1


You cannot directly get the past 100 events because web3 does not know how many events there are in each blocks before checking them.

However, you could achieve that indirectly by getting the past Events of the last, say, 100 blocks. If there are less than 100 events in the result, check the 100 previous blocks and add those events to the first result. Then iterate over past blocks in that way until you have 100 events in your list.

  • Thank you for answering. But is there any other way? It will take so much time to iterate blocks, when we don't have enough events in the recent blocks.
    – intelmin
    Jun 21, 2021 at 20:35
  • Not that I know of.
    – Undead8
    Jun 21, 2021 at 23:50
  • You could also subscribe to new events and delete the oldest ones when your list reaches 100.
    – Undead8
    Jun 21, 2021 at 23:50

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.