0

I am trying to get the specific past events for my contract, named 'Transfer'; when I try to simply use the following code, it gives empty result.

myContract.getPastEvents("Transfer").then(function (event) {
    console.log(event);
})
//output is: []

While when I run with some optional arguments, it gives proper output as expected of two events from my contract.

myContract.getPastEvents("Transfer", { fromBlock: 25635490, toBlock: 25635656 }).then(function (event) {
    console.log(event);
})
//output is: Array[2] -- which is array of two events as expected

The contract is hosted on polygon mumbai testnet - https://mumbai.polygonscan.com/address/0x1d7f71e9dd4283B5b4431e7a51498f4C14b18715

And the reference to web3js documentation which cites that fromBlock and toBlock are optional arguments, so as a newbie I assume that it scans from block 0 to the latest block, please help me with this.

Contract.getPastEvents Docs link

fromBlock/toBlock - Number|String|BN|BigNumber (optional): The block number (greater than or equal to) from which to get events on. Pre-defined block numbers as "earliest", "latest" and "pending" can also be used.

1 Answer 1

0

The default block is used for certain methods. You can override it by passing in the defaultBlock as last parameter. The default value is "latest".

fromBlock is set as "latest" by default, that's why you have no events.

The default block parameters can be one of the following:

Number|BN|BigNumber: A block number

"earliest" - String: The genesis block

"latest" - String: The latest block (current head of the blockchain) >

"pending" - String: The currently mined block (including pending transactions)

but if you try "genesis" you may have an error similar to this: Error: Returned error: Blockheight too far in the past: eth_getLogs. Range of blocks allowed for your plan: 1000, this means that your node does not allow you to search for events older than 1000 blocks.

In this case you can try to paid solutions (moralis, infura, etc.)

1
  • Ok so that makes sense, so by default the function will search from the "latest" block and to the "latest" block, meaning a total of 1 block only.? Mar 25, 2022 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.