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​
Aug 29, 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 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.

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 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 you make your token ERC-20 compliant? ›

How to Create an ERC-20 Token
  1. Set Up your Developer Environment. First, create an Alchemy account, and set up Metamask, HardHat, and Solidity for this project. ...
  2. Write ERC-20 Token Smart Contract. ...
  3. Write a Deployment Script for your ERC-20 Token. ...
  4. Deploy your ERC-20 Token to Goerli. ...
  5. Step 4: Send Some Tokens!

How do I transfer my ERC20 token? ›

Sending an ERC-20 token takes only five steps:
  1. Import userop.js and ethers.js. You only need two libraries - ethers and userop. ...
  2. Build account preset. Userop. ...
  3. Import ERC-20 interface. The user operation will call the ERC-20 token's transfer function. ...
  4. Create the user operation. ...
  5. Send the user operation.

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
16 Quick Tips That'll Help You Stand Out in a Group Interview
E-2 Visa to Green Card Through Marriage - Frear Law
Tiny Tina Deadshot Build
Bild Poster Ikea
Breaded Mushrooms
Mate Me If You May Sapir Englard Pdf
Wmlink/Sspr
Craigslist Estate Sales Tucson
Full Range 10 Bar Selection Box
Craigslist Greenville Craigslist
Nier Automata Chapter Select Unlock
Persona 4 Golden Taotie Fusion Calculator
California Department of Public Health
Housework 2 Jab
Unlv Mid Semester Classes
979-200-6466
Craftology East Peoria Il
Aucklanders brace for gales, hail, cold temperatures, possible blackouts; snow falls in Chch
Xomissmandi
Chelactiv Max Cream
Saatva Memory Foam Hybrid mattress review 2024
Is The Yankees Game Postponed Tonight
Fort Mccoy Fire Map
Ein Blutbad wie kein anderes: Evil Dead Rise ist der Horrorfilm des Jahres
Quick Answer: When Is The Zellwood Corn Festival - BikeHike
Babbychula
8005607994
Loslaten met de Sedona methode
How to Make Ghee - How We Flourish
Jeff Nippard Push Pull Program Pdf
Dtm Urban Dictionary
Preggophili
Dashboard Unt
Mjc Financial Aid Phone Number
Striffler-Hamby Mortuary - Phenix City Obituaries
WOODSTOCK CELEBRATES 50 YEARS WITH COMPREHENSIVE 38-CD DELUXE BOXED SET | Rhino
Swgoh Boba Fett Counter
Little Caesars Saul Kleinfeld
Word Trip Level 359
The Legacy 3: The Tree of Might – Walkthrough
Edict Of Force Poe
R/Moissanite
boston furniture "patio" - craigslist
Tricare Dermatologists Near Me
FedEx Authorized ShipCenter - Edouard Pack And Ship at Cape Coral, FL - 2301 Del Prado Blvd Ste 690 33990
What is 'Breaking Bad' star Aaron Paul's Net Worth?
Victoria Vesce Playboy
Wzzm Weather Forecast
Craigslist Free Cats Near Me
Coldestuknow
Blippi Park Carlsbad
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 5744

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.