ethers.js icon indicating copy to clipboard operation
ethers.js copied to clipboard

Subscribe.on fires past events

Open leinss opened this issue 3 years ago • 4 comments

Ethers Version

5.6.5

Search Terms

subscribe new events filter

Describe the Problem

Hi,

when I am subscribing to a contract's events I am also seeing past events even the filter fromBlock: 'latest' is set.

Am I doing something incorrectly?

   import { useProvider } from "wagmi";

    const provider = useProvider();

    const contract = await new ethers.Contract(
    address,
    abi,
    provider
  );

    const listener: Listener = (id: BigNumber, user: string) =>
    console.dir("id", id.toString(), "user", user)

    contract.on(
    // "CancelOrderEvent",
    {
      topics: [utils.id("CancelOrderEvent(uint256,address)")],
      fromBlock: "latest",
    },
    listener
  )

I should mention, I am using wagmi however, I don't think that changes the way ethers works as I just work with the ethers.Contract.

Help appreciated, cheers 🙏🏼

Code Snippet

No response

Contract ABI

No response

Errors

No response

Environment

Ethereum (mainnet/ropsten/rinkeby/goerli), node.js (v12 or newer), Hardhat, Ganache

Environment (Other)

No response

leinss avatar Jun 10 '22 09:06 leinss

I'm unfamiliar with wagmi, but you shouldn't need to use await when using new in JavaScript, and the Contract contractor is synchronous.

You also cannot pass a fromBlock into the contract.on, as it accepts the EventFilter type. For your purpose you should be able to use the string "CancelOrderEvent".

But neither of those should affect your code... Can you try your code outside of wagmi to see if has anything to do with that?

ricmoo avatar Jun 17 '22 07:06 ricmoo

I'm getting previous events fired with contract.on using ganache testnet. Can I assume this is an artifact of ganache?

kvanstee avatar Jun 24 '22 01:06 kvanstee

It doesn't seem that fromBlock is honoured properly with the latest version of Ethers...

hickscorp avatar Jul 04 '22 13:07 hickscorp

Thanks! I have found the bug.

Yes, this was introduced with the fix for networks which have non-consistent event indexing (e.g. Polygon and BSC).

This fix will go out in v5.7.0.

ricmoo avatar Jul 20 '22 20:07 ricmoo

This has been published in v5.7.0.

Let me know if you still experience any problems.

Thanks! :)

ricmoo avatar Aug 19 '22 21:08 ricmoo