Track ERC-20 token transfers | INFURA (2024)

In this tutorial, you'll track ERC-20 token transfers from a specific address using the Web3 JavaScript library.

Prerequisites

Steps

1. Create a project directory

Create a new directory for your project. This can be done from the command line:

mkdir trackERC20

Change into the new directory:

cd trackERC20

2. Install required packages

Install the web3 package in the project directory:

npm install web3

info

This example has been written for web3js v4.x. It may not work for earlier versions.

3. Set up the script

Create a file called trackERC20.js. At the top of file, add the following lines to import the web3.js library and connect to the Infura WebSocket endpoint:

const { Web3 } = require("web3");

async function main(){
const web3 = new Web3("wss://mainnet.infura.io/ws/v3/<YOUR_API_KEY>");
...
}
main();

Make sure to replace <YOUR_API_KEY> with your Infura API key.

4. Set the ABI

Define the ERC-20 ABI by adding the following to the script:

 const abi = [
{
constant: true,
inputs: [],
name: "symbol",
outputs: [
{
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "decimals",
outputs: [
{
name: "",
type: "uint8",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
];

5. Subscribe to contract events

You can subscribe to the events that token contracts emit, allowing you to track every new token transfer as it occurs.

Add the following filter to the script, which tells the web3.eth.subscribe function in web3.js which events to track:

 let options = {
topics: [web3.utils.sha3("Transfer(address,address,uint256)")],
};

Then, initiate the subscription by passing along the filter:

 let subscription = await web3.eth.subscribe("logs", options);

info

In step 3, you wrap the whole script in an async function main(), because top level await is not allowed except in recent JavaScript versions.

You can also add the following lines to the script to see whether the subscription started successfully or if any errors occurred:

 subscription.on("error", (err) => {
throw err;
});
subscription.on("connected", (nr) =>
console.log("Subscription on ERC-20 started with ID %s", nr),
);

6. Read ERC-20 transfers

You can set the listener for the subscription created in step 5 by adding the following lines to the script:

 subscription.on("data", (event) => {
if (event.topics.length == 3) {
...
}
});

info

To verify that the Transfer event you catch is an ERC-20 transfer, these lines check to see whether the length of the topics array equals 3. This is because ERC-721 events also emit a Transfer event but contain four items instead.

Because you can't read the event topics on their own, you must decode them using the ERC-20 ABI. Edit the listener as follows:

 subscription.on("data", (event) => {
if (event.topics.length == 3) {
let transaction = web3.eth.abi.decodeLog(
[
{
type: "address",
name: "from",
indexed: true,
},
{
type: "address",
name: "to",
indexed: true,
},
{
type: "uint256",
name: "value",
indexed: false,
},
],
event.data,
[event.topics[0], event.topics[1], event.topics[2]],
);

You can now retrieve the sender address (from), receiving address (to), and the number of tokens transferred (value, though yet to be converted, see step 7) from the transaction object.

7. Read contract data

Even though you retrieve a value from the contract, this isn't the actual number of tokens transferred. ERC-20 tokens contain a decimal value, which indicates the number of decimals a token should have. You can directly call the decimals method of the smart contract to retrieve the decimal value, after which you can calculate the correct number of tokens sent.

note

It is optional for ERC-20 contracts to implement these methods (see EIP-20: ERC-20 Token Standard), so you check for errors and fall back to default values.

Outside the subscription.on() listener created in step 6, define a new method that allows you to collect more information from the smart contract:

 async function collectData(contract) {
try {
var decimals = await contract.methods.decimals().call();
}
catch {
decimals = 18n;
}
try {
var symbol = await contract.methods.symbol().call();
}
catch {
symbol = '???';
}
return { decimals, symbol };
}

info

Since you’re already requesting the decimals value from the contract, you can also request the symbol value to display the ticker of the token.

Inside the listener, call the collectData function every time a new ERC-20 transaction is found. You can also calculate the correct decimal value:

 subscription.on("data", (event) => {
if (event.topics.length == 3) {
let transaction = web3.eth.abi.decodeLog(
...
);

const contract = new web3.eth.Contract(abi, event.address);
collectData(contract).then((contractData) => {
var unit = Object.keys(web3.utils.ethUnitMap).find(
(key) => web3.utils.ethUnitMap[key] == (BigInt(10) ** contractData.decimals)
);
if (!unit) {
// Simplification for contracts that use "non-standard" units, e.g. REDDIT contract returns decimals==8
unit = "wei"
}
const value = web3.utils.fromWei(transaction.value, unit);
console.log(
`Transfer of ${value+' '.repeat(Math.max(0,30-value.length))} ${
contractData.symbol+' '.repeat(Math.max(0,10-contractData.symbol.length))
} from ${transaction.from} to ${transaction.to}`,
);

8. Track a specific address

You can track a specific sender address by reading the from value of the decoded transaction object. Add the following line to the listener created in step 6, replacing <SENDER_ADDRESS> with the Ethereum address to track:

 if (transaction.from == "<SENDER_ADDRESS>") {
console.log("Specified address sent an ERC-20 token!");
}

You can also track a specific recipient address receiving any tokens by tracking the transaction.to value:

 if (transaction.to == "<RECIEVING_ADDRESS>") {
console.log("Specified address received an ERC-20 token!");
}

9. Track a specific token

You can track a specific address sending a specific ERC-20 token, by checking for both transaction.from (the token sender) and event.address (the ERC-20 smart contract). Add the following line to the listener created in step 6, replacing <SENDER_ADDRESS> with the Ethereum address to track, and <CONTRACT_ADDRESS> with the smart contract address to track:

 if (
transaction.from == "<SENDER_ADDRESS>" &&
event.address == "<CONTRACT_ADDRESS>"
) {
console.log("Specified address transferred specified token!");
}

You can also track any transactions for a specific ERC-20 token, regardless of the sender or recipient:

 if (event.address == "<CONTRACT_ADDRESS>") {
console.log("Specified ERC-20 transfer!");
}

10. Run the script

Run the script using the following command:

  • Command
  • Example output
node trackERC20.js

Complete code overview

const { Web3 } = require("web3");

async function main(){
const web3 = new Web3("wss://mainnet.infura.io/ws/v3/<YOUR_API_KEY>");

let options = {
topics: [web3.utils.sha3("Transfer(address,address,uint256)")],
};

const abi = [
{
constant: true,
inputs: [],
name: "symbol",
outputs: [
{
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "decimals",
outputs: [
{
name: "",
type: "uint8",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
];

let subscription = await web3.eth.subscribe("logs", options);

async function collectData(contract) {
try {
var decimals = await contract.methods.decimals().call();
}
catch {
decimals = 18n;
}
try {
var symbol = await contract.methods.symbol().call();
}
catch {
symbol = '???';
}
return { decimals, symbol };
}

subscription.on("data", (event) => {
if (event.topics.length == 3) {
let transaction = web3.eth.abi.decodeLog(
[
{
type: "address",
name: "from",
indexed: true,
},
{
type: "address",
name: "to",
indexed: true,
},
{
type: "uint256",
name: "value",
indexed: false,
},
],
event.data,
[event.topics[0], event.topics[1], event.topics[2]],
);

const contract = new web3.eth.Contract(abi, event.address);
collectData(contract).then((contractData) => {
var unit = Object.keys(web3.utils.ethUnitMap).find(
(key) => web3.utils.ethUnitMap[key] == (BigInt(10) ** contractData.decimals)
);
if (!unit) {
// Simplification for contracts that use "non-standard" units, e.g. REDDIT contract returns decimals==8
unit = "wei"
}
// This is logging each transfer event found:
const value = web3.utils.fromWei(transaction.value, unit);
console.log(
`Transfer of ${value+' '.repeat(Math.max(0,30-value.length))} ${
contractData.symbol+' '.repeat(Math.max(0,10-contractData.symbol.length))
} from ${transaction.from} to ${transaction.to}`,
);

// Below are examples of testing for transactions involving particular EOA or contract addresses
if (transaction.from == "0x495f947276749ce646f68ac8c248420045cb7b5e") {
console.log("Specified address sent an ERC-20 token!");
}
if (transaction.to == "0x495f947276749ce646f68ac8c248420045cb7b5e") {
console.log("Specified address received an ERC-20 token!");
}
if (
transaction.from == "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D" &&
event.address == "0x6b175474e89094c44da98b954eedeac495271d0f"
) {
console.log("Specified address transferred specified token!");
} // event.address contains the contract address
if (event.address == "0x6b175474e89094c44da98b954eedeac495271d0f") {
console.log("Specified ERC-20 transfer!");
}
});
}
});

subscription.on("error", (err) => {
throw err;
});
subscription.on("connected", (nr) =>
console.log("Subscription on ERC-20 started with ID %s", nr),
);

}
main();
Track ERC-20 token transfers | INFURA (2024)

FAQs

How do I track my ERC20 token? ›

Track ERC-20 token transfers
  1. Create a project directory​ Create a new directory for your project. ...
  2. Install required packages​ Install the web3 package in the project directory: ...
  3. Set up the script​ ...
  4. Set the ABI​ ...
  5. Subscribe to contract events​ ...
  6. Read ERC-20 transfers​ ...
  7. Read contract data​ ...
  8. Track a specific address​
Sep 5, 2024

How long does ERC-20 transfer take? ›

CoinList waits for 30 confirmations to consider an ETH or ERC-20 transaction final. Although typically this should only take about ~ 5 minutes, this can take anywhere from 5 minutes to 4 hours. Especially during periods of high network congestion, the transaction can take longer.

Is ERC-20 traceable? ›

Just as with traditional Ether tokens, all transactions involving ERC20 tokens are recorded on the Ethereum blockchain, providing traceability of all token transfers and operations on the network.

How do I approve an ERC-20 transfer? ›

If you want the user to give approval to your contract, it needs to be done through a separate transaction. User calls approve() on the token contract directly from their own address (not through another contract), and passes the AccruedInterest address as the first argument.

Can you track Ethereum transactions? ›

Etherscan is one of the most widely used Ethereum blockchain explorers. It offers a comprehensive suite of tools for tracking Ethereum transactions, smart contracts, and token transfers. Etherscan provides detailed information about each transaction, including the date, amount, and gas fees.

How do I track my token holders? ›

With the Token Holder API, you can retrieve the total number of token holders. By using the uniq field and getting unique Holder_Address values, you can find the number of token holders on a specific date.

How to check ERC status? ›

The most direct way to check your IRS ERC refund status is to call the IRS at 1-877-777-4778.

Why is my ERC taking so long? ›

There are marked IRS delays due to the agency reviewing large ERC credit claims – at least twice – before issuing them. The process began after a recommendation from the Treasury Inspector General for Tax Administration (TIGTA).

What is the average ERC processing time? ›

With the stricter compliance reviews in place during this period, existing ERC claims will go from a standard processing goal of 90 days to 180 days – and much longer if the claim faces further review or audit. The IRS may also seek additional documentation from the taxpayer to ensure it is a legitimate claim.

What is a token tracker? ›

The Token Tracker enables FANs to check which payouts for a token have already been claimed, helping them make more informed investment decisions.

How much is ERC-20 worth? ›

ERC20 to USD
AmountToday at 12:19 am
1 ERC20$0.0037
5 ERC20$0.0187
10 ERC20$0.0375
50 ERC20$0.1875
4 more rows

How many ERC-20 tokens are there? ›

ERC-20 tokens are custom user cryptocurrencies created on Ethereum, based on the successful ERC-20 Token Standard. Currently, there are over 500,000 ERC-20 tokens in existence, most of which have no market value. See the full list here.

How can I get my ERC faster? ›

File Form 941-X promptly: If you've already filed your tax return without claiming the ERC and later discover you're eligible, submit Form 941-X as soon as possible. The sooner you file the amended return, the faster the IRS can process your claim and issue your ERC refund.

How do I check my ERC-20? ›

The ERC-20 Contract Address deployed through Remix can be found in Testnet Explorer. After accessing Testnet Explorer, you can check tokens by selecting 'Token > Tokens List'. Find the name of the token entered when creating the ERC-20 contract, check the Contract Address, and copy it.

How do I verify an ERC-20 transaction? ›

To verify and sign an unsupported ERC20 token transaction:
  1. From the Verify selector screen, press the right button to review the Selector parameter: ...
  2. Press the right button to navigate to Approve. ...
  3. Press the right button to review the following parameter: ...
  4. Verify the address then press the right button.

How do I access my ERC20 token? ›

Step-by-step guide to using Alchemy to find all ERC-20 tokens owned by an address
  1. Step 1: Install Node and the NPM. Install Node and the Node Package Manager (NPM) on the local machine. ...
  2. Step 2: Sign up for an Alchemy account and create an app. ...
  3. Step 3: Create a Node project. ...
  4. Step 4: Get the token balances of an address.
Mar 13, 2024

How do I check my ERC-20 wallet? ›

You will be taken to a wallet overview.
  1. At the top, the checksummed version of your address will be displayed. ...
  2. Just below your address, you will see tabs for your portfolio overview, your ETH balance, NFTs, and other ERC-20 tokens. ...
  3. Click on the entry in the 'Hash' column to see the details of that transaction.

Why is my ERC20 token not showing? ›

Check if your ERC20 token is supported

Although your Ledger device can secure most Ethereum ERC20 tokens, not all ERC20 tokens are supported by the Ledger Live app. Non-supported ERC20 token deposits will not show in Ledger Live and will not create a transaction record in the Latest operations section in Ledger Live.

How do I check my Ethereum token? ›

You can enter the address of any wallet or smart contract address on the Ethereum blockchain. Entering an address will take you to an address landing page. An address page contains an overview of the addresses assets such as ETH balance and the value of all the ERC-20 tokens held by that address.

Top Articles
What improvements are allowed for Capital Gains Tax?
What kind of Insurance Do You Need for Your Airbnb Property? | Baselane
The Atlanta Constitution from Atlanta, Georgia
Midflorida Overnight Payoff Address
South Park Season 26 Kisscartoon
Rabbits Foot Osrs
Z-Track Injection | Definition and Patient Education
Deshret's Spirit
Toonily The Carry
Pollen Count Los Altos
South Bend Tribune Online
Slmd Skincare Appointment
Guardians Of The Galaxy Vol 3 Full Movie 123Movies
123Moviescloud
Nonuclub
Diablo 3 Metascore
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
Chastity Brainwash
Adam4Adam Discount Codes
How to Create Your Very Own Crossword Puzzle
Pickswise Review 2024: Is Pickswise a Trusted Tipster?
Self-Service ATMs: Accessibility, Limits, & Features
Sef2 Lewis Structure
‘The Boogeyman’ Review: A Minor But Effectively Nerve-Jangling Stephen King Adaptation
R. Kelly Net Worth 2024: The King Of R&B's Rise And Fall
Pirates Of The Caribbean 1 123Movies
Jeff Nippard Push Pull Program Pdf
Disputes over ESPN, Disney and DirecTV go to the heart of TV's existential problems
BJ 이름 찾는다 꼭 도와줘라 | 짤방 | 일베저장소
Apparent assassination attempt | Suspect never had Trump in sight, did not get off shot: Officials
Local Collector Buying Old Motorcycles Z1 KZ900 KZ 900 KZ1000 Kawasaki - wanted - by dealer - sale - craigslist
Afni Collections
Free T33N Leaks
Usa Massage Reviews
R/Mp5
Otis Inmate Locator
Grove City Craigslist Pets
Star News Mugshots
Haunted Mansion Showtimes Near Cinemark Tinseltown Usa And Imax
Pch Sunken Treasures
Blue Beetle Movie Tickets and Showtimes Near Me | Regal
Domina Scarlett Ct
Bella Thorne Bikini Uncensored
Publictributes
Doordash Promo Code Generator
Top 40 Minecraft mods to enhance your gaming experience
60 Days From May 31
Unit 11 Homework 3 Area Of Composite Figures
Server Jobs Near
Meee Ruh
Ihop Deliver
Provincial Freeman (Toronto and Chatham, ON: Mary Ann Shadd Cary (October 9, 1823 – June 5, 1893)), November 3, 1855, p. 1
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6207

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.