[Ethereum] How to get only past 2 days events using getPastEvents everytime

dappseventsreactsolidityweb3js

How can the following query be modified to only fetch the past two days worth of events:

const events= await MyContract.getPastEvents("eventName", {
  fromBlock: 0,
  toBlock: "latest"
});

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 the getPastEvents function to limit to that range:

const events= await MyContract.getPastEvents("EventName", {
  fromBlock: (await web3.eth.getBlockNumber()) - 12343,
  toBlock: "latest"
});
Related Topic