Search code examples
eventsethereumethers.js

What does contract.filters return in ethers.js?


I came across ethers.js library's event filters function contract.filters. See below codes from ethers.js documentation.

https://docs.ethers.org/v5/concepts/events/

abi = [
  "event Transfer(address indexed src, address indexed dst, uint val)"
];

contract = new Contract(tokenAddress, abi, provider);

// List all token transfers *from* myAddress
contract.filters.Transfer(myAddress)
// {
//   address: '0x6B175474E89094C44Da98b954EedeAC495271d0F',
//   topics: [
//     '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
//     '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72'
//   ]
// }
  1. What is in the returned value inside topics:[], what is each string value represent? Is each event represented in its transaction hash?
  2. And also what is the sort order of each event? Would the latest event be the first in the topics array?

Thank you!

I also looked at solidity's documentation on events but still not sure.


Solution

  • What is in the returned value inside topics:[], what is each string value represent? Is each event represented in its transaction hash?

    Since this event is non-anonymous (most events are; missing the anonymous keyword at the end of the event definition), topics[0] represents the event signature.

    Event signature is a keccak256 hash of the event name and argument types.

    In this case hash of string Transfer(address,address,uint256) (uint is an alias for uint256 and the longer version is used for signatures).

    Following topics items are the indexed params. Since there's 2 indexed params in your event, the total size of the array should be 3 (1 signature + 2 indexed params). I'm not sure why the 3rd item is missing from the code in your question.

    And also what is the sort order of each event? Would the latest event be the first in the topics array?

    They are sorted by the order of their execution. So the following code returns EventB, then EventA and finally EventB.

    pragma solidity ^0.8;
    
    contract MyContract {
      event EventA();
      event EventB();
    
      function foo() external {
        emit EventB();
        emit EventA();
        emit EventB();
      }
    }