2

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.

Andrew
  • 135
  • 1
  • 5

1 Answers1

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
  • Thanks, I was able to get an old log doing this - but do you know if it only gives the most recent transaction's event? If I process several transactions (that all emit events) it only ever returns one event (this is doing logs = await web3.eth.getPastLogs({fromBlock: 0, toBlock: latest}) – Andrew Feb 07 '20 at 02:04
  • This might also be a ganache issue as I only see the most recent log in the ganache UI – Andrew Feb 07 '20 at 05:05