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:
Change into the new directory:
2. Install required packages
Install the web3
package in the project directory:
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.
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:
FAQs
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
- Add the sender and recipient addresses Open Ronin Bridge. ...
- Choose the token and amount ...
- Confirm your withdrawal ...
- Receive the tokens in your Ethereum wallet
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
- Step 1: Install Node and the NPM. Install Node and the Node Package Manager (NPM) on the local machine. ...
- Step 2: Sign up for an Alchemy account and create an app. ...
- Step 3: Create a Node project. ...
- Step 4: Get the token balances of an address.
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.
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
- Compliance with regulations. The token must adhere to local and international regulatory standards. ...
- Technical requirements. Compatibility with the exchange's infrastructure is crucial. ...
- Financial audits. ...
- Community and marketing. ...
- Documentation.