Skip to content

Instantly share code, notes, and snippets.

@offlinehacker
Last active November 23, 2021 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save offlinehacker/30b9a1c542de3ca243d923ef22156ba4 to your computer and use it in GitHub Desktop.
Save offlinehacker/30b9a1c542de3ca243d923ef22156ba4 to your computer and use it in GitHub Desktop.
Subscribe to ERC20 Transfer events
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);
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