xwillorg
xwillorg

Reputation: 3

Getting all newly minted ERC721 contracts with an ethereum node

I want to log all new minted ERC712 tokens. I have already connected a node and can get the current block number.

async function init() {
  const customHttpProvider = new ethers.providers.JsonRpcProvider(url)
  customHttpProvider.getBlockNumber().then((result) => {
    console.log("Current block number: " + result)
  })
}

Now my question is, how can I filter for the token type of the contract? Do i need to loop through every transaction in the block and listen for contract transactions?

Thank you very much for the help, this is my first post.

Upvotes: 0

Views: 2985

Answers (1)

Ahmad Gorji
Ahmad Gorji

Reputation: 424

You can do it via Contract.on() function. here is the doc.

To make a filter of a contract, first you have to declare a contract object.

To declare a contract object you must have contract address and contract ABI.

Contract address is known to anyone and you can get it from etherscan (or other sites alike, dependent on network scanner).

As you are using ethers.js, you do not have to equal contract ABI of contract in JavaScript as it is in etherscan! You can simply use ERC721 standard interface! Which you can find it here

So if we take a look at _mint() function in ERC721 standard contract (here) it emits Transfer event and if you want just to take mint tokens log, this interface is enough.

If you look at mint emit also you notice it always use address(0) as sender which is 0x0000000000000000000000000000000000000000.

So you can code like this:

//making contract object!

const smallContractABI  = ['event Transfer(address indexed from, address indexed to, uint256 value)']
const contractAddress = CONTRACT_ADDRESS_YOU_ARE_LOOKING_AFTER;
const contract = new ethers.Contract(contractAddress, smallContractABI, customHttpProvider);

//here I can show you 2 ways.
//First way:
//Filtering

let filter = contract.filters.Transfer('0x0000000000000000000000000000000000000000', null, null) 

//Note that null is not necessary if you are just filtering first argument, but if you want
//just filter second argument, you have to set first argument null.
//For example when you want to specify transfer events when
//a transfer has been reached a specific address. then you filter like this:
//let filter = contract.filters.Transfer(null, ADDRESS, null) 

//Listening to events

contract.on(filter, (from, to, amount, event) =>{
   //code here
}

//Second way:
//You do not have to filter
contract.on("Transfer", (from, to, amount, event) => {
   if (from == '0x0000000000000000000000000000000000000000'){
      //code here
   }
}

Both ways do one thing but first way is recommended!

Upvotes: 1

Related Questions