[Ethereum] Ethers.js filters events (Only new events)

ethers.jseventssolidity

I have an event set up in the Contract.

Contact Packages
   emit Spend(msg.sender, msg);

   function sendPackage(msg) external payable returns(bool) {
     require(
       msg.value == price,
       'Please send the correct amount of ETH to make send a message'
     );

     emit Spend(msg.sender, msg);
     return true;
}

And a script in NodeJS that listens to new events.

The intention is to kick off some NodeJS code whenever a new event on the contract takes place.

But whenever I start the script, the Contract.on(.. fires and the last event is passed to it, even though the event fired a hour ago.

Is there a way to config the callback to NOT include previous events?

  Contract.on('Spend', (sender, event) => {
    console.log(sender);
    console.log(event);
  });

EDIT

I've tried to use Contact.once and the same result occurs.

Best Answer

get the startblock number from provider

const startBlockNumber = await provider.getBlockNumber();

then check that with the blocknumber recieved from event.

Full code:

const startBlockNumber = await provider.getBlockNumber();
provider.once("block", () => {
    transactionsContract.on(
        "Transfer",
        (from, to, amount, timestamp, message, blockNumber) => {
            if (blockNumber <= startBlockNumber) {
                console.log("old event");
                return;
            }
            console.log({
                from,
                to,
                amount,
                timestamp,
                message,
                blockNumber,
            });
        }
    );
});
Related Topic