Last active
November 23, 2021 12:32
-
-
Save offlinehacker/30b9a1c542de3ca243d923ef22156ba4 to your computer and use it in GitHub Desktop.
Subscribe to ERC20 Transfer events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Contract, getDefaultProvider, utils } from "ethers"; | |
const provider = getDefaultProvider("homestead"); | |
const abi = [ | |
"function symbol() view returns (string)", | |
"function decimals() view returns (uint8)", | |
"event Transfer(address indexed from, address indexed to, uint value)", | |
]; | |
const topicFilter = utils.id("Transfer(address,address,uint256)"); | |
async function handler(log) { | |
const hash = log.transactionHash; | |
const contract = new Contract(log.address, abi, provider); | |
let logDescription, symbol, decimals; | |
try { | |
logDescription = contract.interface.parseLog(log); | |
symbol = await contract.symbol(); | |
decimals = await contract.decimals(); | |
} catch (err) { | |
return; | |
} | |
const [from, to, value] = logDescription.args; | |
const amount = `${utils.formatUnits(value, decimals)} ${symbol}`; | |
console.log(`New Transfer ${hash}\n\tfrom: ${from}\n\tto: ${to}\n\tamount: ${amount}`); | |
} | |
provider.on({ topics: [topicFilter] }, handler); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Contract, getDefaultProvider, utils } from "ethers"; | |
import { Log } from "@ethersproject/abstract-provider"; | |
import { LogDescription } from "@ethersproject/abi"; | |
const provider = getDefaultProvider("homestead"); | |
const abi = [ | |
"function symbol() view returns (string)", | |
"function decimals() view returns (uint8)", | |
"event Transfer(address indexed from, address indexed to, uint value)", | |
]; | |
const topicFilter = utils.id("Transfer(address,address,uint256)"); | |
async function handler(log: Log) { | |
const hash = log.transactionHash; | |
const contract = new Contract(log.address, abi, provider); | |
let logDescription: LogDescription, symbol: string, decimals: number; | |
try { | |
logDescription = contract.interface.parseLog(log); | |
symbol = await contract.symbol(); | |
decimals = await contract.decimals(); | |
} catch (err) { | |
return; | |
} | |
const [from, to, value] = logDescription.args as any; | |
const amount = utils.formatUnits(value, decimals); | |
console.log( | |
`New Transfer ${hash}\n\tfrom: ${from}\n\tto: ${to}\n\tamount: ${amount} ${symbol}` | |
); | |
} | |
provider.on( | |
{ | |
topics: [topicFilter], | |
}, | |
handler | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment