Web3.js: How to Track ERC-20 Token Transfers (+ Specific Address/Token)
ERC-20 tokens have become an essential part of the Ethereum ecosystem; if you’ve interacted with DeFi before, you’ve almost definitely interacted with ERC-20 tokens.
How can we track these programmatically with hundreds of token transactions happening every minute? By utilizing web3.js and adding some ABI and event tracking magic, we’re able to!
If you’d like to learn more about tracking NFTs instead, read more about Tracking NFT (ERC-721/1155) Transfers. Additionally, you can also read more about Retrieving the Balance of an ERC-20 Token.
Setting Up Our Project
This tutorial makes use of Web3.js v1.x.x. Not all functionality might work with Web3.js v4.
Please create a new folder in which we can work on our project, then install web3js using npm
npm install web3
Ensure you have your Infura account set up and have access to your endpoint URL. Feel free to read more about getting started with Infura.
At the top of our new Javascript file, we can add the following to import the web3js library that we just installed and connect to the Infura websockets endpoint:
const Web3 = require("web3");
const web3 = new Web3("wss://mainnet.infura.io/ws/v3/<YOUR_PROJECT_ID>");
Make sure to replace API_KEY with your actual Infura API KEY.
Reading ERC-20 Events
Almost every fungible token on the Ethereum blockchain uses the ERC-20 token spec, which defines a set of required events and event emitters so interfaces that interact with the Ethereum chain can treat every token the same.