Search code examples
ethereumblockchainpolygonbsc

Is there a way to get a specific event for a contract?


I'm going to run a contract in Ethereum, Binance, Polygon, and Clayton.

Is there a best practice for polling events that occur in a contract?

I want to get the event by requesting, not by subscribing to it.

If we use EtherScan api, are all sequences decisively guaranteed?

The goal is to send requests periodically and store all the specific events that occurred in the contract in db.

I'd appreciate your help.


Solution

  • When you query the raw blockchain data, each event log contains logIndex, which is the position of the event within the block.

    Example with web3js:

    const pastEventLogs = await web3.eth.getPastLogs({
        fromBlock: 16168375,
        toBlock: 16168375,
        address: "0xdAC17F958D2ee523a2206206994597C13D831ec7", // USDT on Ethereum
        topics: [
            web3.utils.keccak256("Transfer(address,address,uint256)")
        ]
    });
    

    returns

    ...
        address: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
        blockHash: '0x026c2f62c8ad51b1e28c5fe6885c6025b2c4145aef08b65feb10b6e20dd2c0bc',
        blockNumber: 16168375,
        data: '0x0000000000000000000000000000000000000000000000000000000001618bd0',
        logIndex: 732,
    ...
    

    Authors of 3rd party APIs (e.g. Etherscan) can chose to order their results according to the logIndex but they can also chose different ordering.