Retrieve the balance of an ERC-20 token | INFURA (2024)

In this tutorial, using Web3.js, you'll retrieve the balance of an ERC-20 token in an account, using the account address and the token contract.

Prerequisites

Steps

1. Create a project directory

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

mkdir retrieveBalance

Change into the new directory:

cd retrieveBalance

2. Install required packages

Install the web3 package in the project directory:

npm install web3

3. Set up the script

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

const { Web3 } = require("web3");
const web3 = new Web3(
new Web3.providers.HttpProvider(
"https://mainnet.infura.io/v3/<YOUR_API_KEY>",
),
);

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

4. Set the ABI

You'll only use the balanceOf method, so you don’t need the entire ABI for ERC-20 smart contracts. In the retrieveBalance.js file, define the ABI for the balanceOf method by adding the following to the script:

const balanceOfABI = [
{
constant: true,
inputs: [
{
name: "_owner",
type: "address",
},
],
name: "balanceOf",
outputs: [
{
name: "balance",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
];

5. Select a token address

To retrieve the balance of a token, you need the contract address of the token. You can find this in the tokens section of a block explorer such as Etherscan.

This example uses a DAI token contract. However, you can use any ERC-20 token contract address. Copy the token contract address you wish to use.

Retrieve the balance of an ERC-20 token | INFURA (1)

6. Request the token balance

Define the addresses to use in the retrieveBalance.js script:

const tokenContract = "0x6b175474e89094c44da98b954eedeac495271d0f";
const tokenHolder = "0xf326e4de8f66a0bdc0970b79e0924e33c79f1915";

Define contract using web3.eth.Contract(), passing the balanceOfABI and the token contract address tokenContract as parameters:

const contract = new web3.eth.Contract(balanceOfABI, tokenContract);

Next, call methods.balanceOf() on the contract and pass the tokenHolder address. This call sends a request to your Infura endpoint to request the token balance in the tokenHolder account address.

Create the below async function getTokenBalance that accomplishes this by interacting with the tokenContract.

async function getTokenBalance() {
const result = await.contract.methods.balanceOf(tokenHolder).call();
console.log(result)
}

getTokenBalance();

7. Convert the token units

By default, calling balanceOf returns the balance value in wei, which is the smallest unit in Ethereum, equal to 0.000000000000000001 Ether (10-18).

Use web3.utils.fromWei(result, "ether") to get the actual number of DAI tokens, by adding the following line to the async function:

const formattedResult = web3.utils.fromWei(result, "ether");

Also, update your console.log(format):

console.log(formattedResult);

8. Run the script

Complete code

Here is the complete code for retrieveBalance.js. Before running it make sure you replace <YOUR_API_KEY> with your Infura API key.

const { Web3 } = require("web3");
const web3 = new Web3(
new Web3.providers.HttpProvider(
"https://mainnet.infura.io/v3/<YOUR_API_KEY>",
),
);

const balanceOfABI = [
{
constant: true,
inputs: [
{
name: "_owner",
type: "address",
},
],
name: "balanceOf",
outputs: [
{
name: "balance",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
];

// DAI token contract
const tokenContract = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
// A DAI token holder
const tokenHolder = "0x075e72a5eDf65F0A5f44699c7654C1a76941Ddc8";
const contract = new web3.eth.Contract(balanceOfABI, tokenContract);

async function getTokenBalance() {
const result = await contract.methods.balanceOf(tokenHolder).call();
const formattedResult = web3.utils.fromWei(result, "ether");
console.log(formattedResult);
}

getTokenBalance();

Run the script using the following command:

  • Command
  • Example
node retrieveBalance.js
Retrieve the balance of an ERC-20 token | INFURA (2024)

FAQs

Retrieve the balance of an ERC-20 token | INFURA? ›

Using the QuickNode Token API

Alternatively, you can easily retrieve the balance of an ERC20 token using the QuickNode Token API. The Token API allows users to easily retrieve aggregated token data such as balances by wallet, token transfers, and token details (such as metadata and decimal places).

How to get ERC20 token balance? ›

Using the QuickNode Token API

Alternatively, you can easily retrieve the balance of an ERC20 token using the QuickNode Token API. The Token API allows users to easily retrieve aggregated token data such as balances by wallet, token transfers, and token details (such as metadata and decimal places).

Can you recover ERC-20 tokens? ›

If you accidentally sent ERC-20 tokens to your wallet address that does not support ERC-20 tokens, you may retrieve the ERC-20 token by importing the address to another wallet interface that supports ERC-20 tokens.

How do I check my ERC-20 address balance? ›

You can retrieve the Token balance (ERC-20, BEP-20 or compatible) of an address via the following methods: Get token balance from an address (by Smart Contract): v3 REST API endpoint. Get balances from an address: v4 DATA API endpoint.

How do I withdraw my ERC-20 tokens? ›

Withdraw an ERC20 token
  1. Add the sender and recipient addresses​ Open Ronin Bridge. ...
  2. Choose the token and amount​ ...
  3. Confirm your withdrawal​ ...
  4. Receive the tokens in your Ethereum wallet​
Jun 26, 2024

How do I convert my ERC-20 tokens to cash? ›

Safely exchange your ERC20 tokens through Ledger

In the Ledger Live app Swap tab, select any ERC20 tokens and the accounts of origin and destination. Enter the amount you want to exchange and check the rate. Before confirming the swap, you'll see a summary on Ledger Live.

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

Do ERC-20 tokens have value? ›

The barrier to entry for creating ERC-20 token sets is low (it's really just a matter of deploying a relatively simple 'contract' to the Ethereum network), so the number of sets is measured in the thousands. For this reason, most sets actually have very little value. Some, however, are worth billions.

Where are ERC-20 tokens stored? ›

ERC 20 tokens can be stored in virtually any cryptocurrency wallet. Importantly, when using them, remember to write down the key phase. This consists of between 12 and 24 words. This is the password for access, in case your funds are lost.

How much does it cost to mint an ERC20 token? ›

Basic ERC20 tokens typically handle basic functions such as money transfer and storage. Simple estimates to create a basic ERC20 token fall between $5,000 and $10,000. These costs include token creation, development, testing, and implementation.

Where is my ERC money? ›

To confirm receipt, call the Internal Revenue Service's business helpline at (800) 829-4933. When calling the IRS for a status update, have your federal employee identification number (EIN) and tax return information readily available.

How do I find my ERC20 token address? ›

Find your wallet address: Go to the wallet or click on receive button and the alphanumeric wallet address will be revealed there. Copy the address to share it with others: Copy and paste the address to share it with others. Always copy and share your address to ensure that you do not make a mistake.

How do I check my Ethereum wallet address balance? ›

You can also check your balance and transaction history on an Ethereum blockchain explorer like EthVM. A blockchain explorer offers a full history of your activity. All you have to do is search your public Ethereum address, which is the 42 character string beginning with '0x'.

Can you cash out tokens? ›

Cashing out means selling crypto coins or tokens in exchange for fiat money and then withdrawing the money to your bank account. It helps to know the differences among the basic types of trading platforms and exchanges.

What can you do with ERC-20 tokens? ›

The ERC20 standard has ushered in plenty of benefits for the Ethereum ecosystem and the broader blockchain and DeFi spaces: Interoperability: ERC-20 tokens can be easily traded, exchanged, and integrated into various Ethereum-based applications, enhancing usability and interoperability between dApps.

Where can I check my ERC-20 transaction? ›

Go to the Etherscan website at https://etherscan.io. Etherscan is one of the most popular blockchain explorations for checking transactions and other information on the Ethereum network.

How do I view ERC-20 tokens on Ledger Live? ›

How to view your ERC20 token in Ledger Live. If you already have an Ethereum account with ERC20 tokens, you can view your tokens in Ledger Live. On the Accounts page, click on Show tokens under the Ethereum account that holds the tokens.

How do I get my ERC20 token listed on exchange? ›

The Main Requirements to Getting Listed on a Crypto Exchange
  1. Compliance with regulations. The token must adhere to local and international regulatory standards. ...
  2. Technical requirements. Compatibility with the exchange's infrastructure is crucial. ...
  3. Financial audits. ...
  4. Community and marketing. ...
  5. Documentation.
Jun 6, 2024

Top Articles
USPS Boxes 101: Sizes, Prices & Restrictions
How superstitious are you when it comes to your wedding dress? | Bourton Hall
9.4: Resonance Lewis Structures
Truist Bank Near Here
Splunk Stats Count By Hour
Shoe Game Lit Svg
Craftsman M230 Lawn Mower Oil Change
What to Do For Dog Upset Stomach
Workday Latech Edu
Undergraduate Programs | Webster Vienna
Ou Class Nav
Walgreens On Nacogdoches And O'connor
Washington, D.C. - Capital, Founding, Monumental
Help with Choosing Parts
Nalley Tartar Sauce
De beste uitvaartdiensten die goede rituele diensten aanbieden voor de laatste rituelen
Watch The Lovely Bones Online Free 123Movies
Wausau Marketplace
Vigoro Mulch Safe For Dogs
Nhl Tankathon Mock Draft
Culver's Flavor Of The Day Taylor Dr
Busted News Bowie County
Sef2 Lewis Structure
Naya Padkar Gujarati News Paper
Why Are Fuel Leaks A Problem Aceable
Craig Woolard Net Worth
Criterion Dryer Review
10 Best Places to Go and Things to Know for a Trip to the Hickory M...
Ardie From Something Was Wrong Podcast
Abga Gestation Calculator
Our 10 Best Selfcleaningcatlitterbox in the US - September 2024
Sinfuldeed Leaked
Angel del Villar Net Worth | Wife
Evil Dead Rise - Everything You Need To Know
Shaman's Path Puzzle
Of An Age Showtimes Near Alamo Drafthouse Sloans Lake
Adecco Check Stubs
Vitals, jeden Tag besser | Vitals Nahrungsergänzungsmittel
The Mad Merchant Wow
Western Gold Gateway
Games R Us Dallas
Property Skipper Bermuda
Сталь aisi 310s российский аналог
Bob And Jeff's Monticello Fl
Mississippi weather man flees studio during tornado - video
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
How to Install JDownloader 2 on Your Synology NAS
Matt Brickman Wikipedia
Spn 3464 Engine Throttle Actuator 1 Control Command
Houston Primary Care Byron Ga
OSF OnCall Urgent Care treats minor illnesses and injuries
Itsleaa
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6091

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.