1

In my dapp I'm building I want to update the contracts' balance of an ERC20 token automatically using the transfer event from the token contract. I have created the contract object using:

const ERC20Token = new ethers.Contract(address, ERC20ABI, provider)

my filters and event listeners look like this:

const filterTo = ERC20Token.filters.Transfer(null, props.contractData.address)

chainlinkToken.on(filterTo, () => {
    networkData()
    console.log('To')

})
const filterFrom = ERC20TOken.filters.Transfer(props.contractData.address)

chainlinkToken.on(filterFrom, () => {
    networkData()
    console.log('From')

}) 

props.contractData.address is the address of my contract

networkData() is a function that updates the balance in my UI

the problem is, when I send the Token (LINK in my case) the filter (filterTo) get triggered between a few hundred to over 1000 times (meaning "to" and "from" are console.logged that many times). Same thing when I use a function in my contract that spends the token (filterFrom). My guess is its recording other transfer events from the ERC20 contract, meaning the filters aren't doing anything... but even then theres too many of them. Anyone know why? Also anyone know of a good method to reliably listen for events and do something when one is emitted?

the picture is from ether.js documentation, and I followed that, what does the commented out portion mean? I kind of

0

You need to place the to and from addresses as part of the transfer event filters as follows:

const filter = ERC20Token.filters.Transfer(sender, recipient)

The line above defines a filter to capture all transfer events from sender account to recipient account. Note that both of those are EOAs for the sender and recipient of the tokens.

2
  • interesting, I'll try that out. How would that work dynamically for other users of the dapp? I cant hardcode their addresses in, can I?. Also for outgoing events, Im using chainlink oracles and I don't know who the fee goes to. Thanks!! Aug 7 '21 at 16:29
  • @NolanJannotta You could filter by sender, recipient, or both as in my answer above. You would probably just fetch the user address from their EthersJS or Web3 provider. Aug 7 '21 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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