This answer worked when filter.get was not deprecated, but now I am not sure how to do the same thing with subscribe - web3.eth.subscribe hears new events and acts on them after I create the subscription, but I am not sure how to get old events.
Asked
Active
Viewed 2,789 times
2
Andrew
- 135
- 1
- 5
1 Answers
5
Try this (tested with web3.js v1.2.1):
async function getPastLogs(address, fromBlock, toBlock) {
if (fromBlock <= toBlock) {
try {
const options = {
address : address,
fromBlock: fromBlock,
toBlock : toBlock
};
return await web3.eth.getPastLogs(options);
}
catch (error) {
const midBlock = (fromBlock + toBlock) >> 1;
const arr1 = await getPastLogs(address, fromBlock, midBlock);
const arr2 = await getPastLogs(address, midBlock + 1, toBlock);
return [...arr1, ...arr2];
}
}
return [];
}
...
const latest = await web3.eth.getBlock("latest");
const logs = await getPastLogs(yourContractAddress, 1, latest);
You can further optimize this by replacing 1 with your contract creation block number.
See more on function web3.eth.getPastLogs here.
goodvibration
- 26,003
- 5
- 46
- 86
logs = await web3.eth.getPastLogs({fromBlock: 0, toBlock: latest})– Andrew Feb 07 '20 at 02:04