How to Build an ERC20 Token Balance App with QuickNode Token API | QuickNode (2024)

14 min read

Overview

Making a dApp that requires ERC20 token data can be tedious since there are numerous tokens, and one needs to query each token contract to get the data. This guide will show how we can build a ERC20 token balance app with QuickNode Token API.

Prefer a video walkthrough? Follow along with Radek and learn how to Build an ERC20 Token Balance App with the QuickNode Token API.

Subscribe to our YouTube channel for more videos!

Subscribe

What You Will Need

What You Will Do

  • Learn about the traditional method of fetching ERC20 token data.
  • Learn about QuickNode Token API and its different methods.
  • Boot a QuickNode Ethereum node with Token API.
  • Create a React app to display ERC20 token balances of a particular wallet using QuickNode Token API and Ethers.js library along with Tailwind CSS for styling.

The Traditional way

To get token data like the balance for a specific ERC20 token, one needs to query the smart contract of that particular token. Multiple smart contracts need to be queried when you want to obtain data for multiple tokens. In this process, one needs to query the contract with the help of contract ABI; this creates a lot of redundant code, which also needs to be maintained. Learn how to get token balances using this method in this guide.

QuickNode Token API makes this process very easy and short. In the next section, we will learn more about the Token API and its methods.

What is QuickNode's Token API?

QuickNode Token API is an API using which a user can get token metadata, balances, and transfer histories of ERC20 tokens for a wallet on the Ethereum mainnet. While using the Token API, the user must make a method call to the QuickNode RPC without the need to query smart contracts. The following are the methods of QuickNode Token API:


  • qn_getTokenMetadataByContractAddress: A user can get metadata of a specific ERC20 by using that token's contract address.
  • qn_getTokenMetadataBySymbol: Using this method, a user can get metadata of a specific ERC20 by using that token's symbol (WETH, USDT, MATIC, etc).
  • qn_getWalletTokenBalance: A user can get all the ERC20 tokens of a wallet address along with their balances.
  • qn_getWalletTokenTransactions: The transfer history of a particular ERC20 token for a wallet address can be retrieved; the wallet address and the token's contract address need to be used as parameters.

Now that we have learned about QuickNode Token API, let us boot a QuickNode Ethereum mainnet endpoint and create a small Token app in the upcoming sections.

Booting QuickNode endpoint with Token API

Token API is an adjacent product to the QuickNode RPC, so it only works with the QuickNode RPC endpoints. Let us quickly get a free QuickNode Ethereum mainnet node, as the Token API is also included with the free plan.

How to Build an ERC20 Token Balance App with QuickNode Token API | QuickNode (1)

Copy and keep the HTTP Provider link, as we will need it in the next section.

How to create an ERC20 Token Balance App with QuickNode Token API

Now that we know about the Token API and have a QuickNode RPC with Token API let us create a small React app to show balances of ERC20 tokens for a given address. To do so, let us install some libraries/dependencies we will use.

Copy-paste the following into your terminal/command prompt

This will create a new directory, token_wallet, with the required React components.

We will need Ethers.js (version 5.7) to connect our QuickNode node to the React app and Tailwind CSS for styling our React app. Go to the recently created directly and copy-paste the following in your terminal/command prompt to install ethers and Tailwind CSS:

cd token_wallet
npm install ethers@5.7
npx tailwindcss init -p

We need to let Tailwind know about the file's path, which needs styling, so open your project directory in a code editor, open the tailwind.config.js file, and modify the config to look like this:

/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{html,js,jsx}"],
theme: {
extend: {},
},
plugins: [],
}

After saving the above file, navigate to src/index.js in your code editor and add the following line between lines 9 and 10:

<link href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="stylesheet" />

This will import Tailwind's utility classes.

The app we are creating will have a form input field and a submit button. Once an address is input and the button is clicked, using the Token API, ERC20 token data will be retrieved for the imputed address and displayed

Start building by going to src/app.js in your code editor and pasting the following code:

import { useState } from 'react';
import { ethers, utils } from "ethers";

function App() {
//State variables
const [tokens, setTokens] = useState([])
const [address, setAddress] = useState('')
}
export default App;

In the above code, on

Line 1-2: we're importing the React useState hook to track our input wallet address and ethers library to connect our app with the Ethereum blockchain using QuickNode.

Line 4-7: Starting our React app named App and declaring two state variables to store token data and another to store input address, respectively.

Now add the following on line 9:

 //Function to handle form submission
const handleSubmit = (e) => {
e.preventDefault();
setAddress(address);
fetchTokens()
.then(data => {
setTokens(data.assets)
})
.catch(err => setTokens([]))
}

//Function to fetch tokens
const fetchTokens = async () => {
if (!utils.isAddress(address)){
alert('Please enter a valid Ethereum wallet address')
return;
}
const provider = new ethers.providers.JsonRpcProvider("YOUR-QUICKNODE-HTTP-URL-HERE");
const tokens = await provider.send("qn_getWalletTokenBalance", {
wallet: address,
contracts: [
'0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', //WETH
'0xdAC17F958D2ee523a2206206994597C13D831ec7', //USDT
'0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0', //MATIC
'0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72', //ENS
]
});
return tokens
}

Replace YOUR-QUICKNODE-HTTP-URL-HERE with QuickNode's HTTP Provider link we got in the last step.

In the above code, on

Line 10-18: We're writing a function handleSubmit to handle the form submission event; basically, it is changing the state of the address variable to store the imputed address's value, then calling the function fetchTokens, then changing the state of the tokens variable to store token data.

Line 20-37: A function fetchTokens to fetch tokens. First, an if statement to check if the input address is a valid Ethereum address or not using the ethers isAddress function. Then connecting to QuickNode Ethereum node. Making a Token API call to get wallet tokens by passing the address as a parameter along contract addresses of WETH, USDT, MATIC, and ENS to get these specific token's data. Then Returning tokens

On line 38, paste the following code:

//JSX code
return(
<div className="h-screen w-screen justify-center space-x-3">
<div className="flex justify-center space-x-3 w-screen h-14 mt-10">
<form
onSubmit={handleSubmit}
className="w-4/12 h-15 relative block overflow-hidden rounded-md border border-gray-200 px-3 pt-3 shadow-sm focus-within:border-blue-600 focus-within:ring-1 focus-within:ring-blue-600 dark:border-gray-700 dark:bg-gray-800">
<input
onChange={e => setAddress(e.target.value)}
type="text"
placeholder="Enter your Address here 🎯"
className="mt-1 w-full border-none p-0 focus:border-transparent focus:outline-none focus:ring-0 sm:text-sm"
/>
<button
type='submit'
className="rounded-lg top-1 right-1 bottom-1 border absolute w-12 justify-center bg-blue-400 text-white p-3 font-bold uppercase"
>
GO
</button>
</form>
</div>
<div className="relative top-4/12 left-1/4 overflow-x-auto justify-center space-x-3 w-6/12 h-140 m-10">
<table className="min-w-full divide-y-2 divide-gray-200 text-sm">
<thead>
<tr>
<th
className="whitespace-nowrap px-4 py-2 text-left font-medium text-gray-1000">
Name
</th>
<th
className="whitespace-nowrap px-4 py-2 text-left font-medium text-gray-900">
Symbol
</th>
<th
className="whitespace-nowrap px-4 py-2 text-left font-medium text-gray-900">
Balance
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{tokens.map((token, index) => (
<tr key={index}>
<td className="whitespace-nowrap px-4 py-2 text-gray-900">{token.name}</td>
<td className="whitespace-nowrap px-4 py-2 text-gray-900">{token.symbol}</td>
<td className="whitespace-nowrap px-4 py-2 text-gray-900">{utils.formatUnits(token.amount, token.decimals)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);

The above code is basic HTML in JS (JSX) and Tailwind styling. The few worth noting lines are:

Line 44: Calling the handleSubmit function on form submission.

Line 47: Getting the current value of the input field and setting it to setAddress.

Line 79: Mapping the token data in the tokens array.

Line 81: Printing the token's name, symbol, and balance (formatting the units based on that token's decimal values).

Note: The app will only display balances of tokens which me added in the contracts section of the RPC.

Save the file, and the final file should look like this:

import { useState } from 'react';
import { ethers, utils } from "ethers";

function App() {
//State variables
const [tokens, setTokens] = useState([])
const [address, setAddress] = useState('')

//Function to handle form submission
const handleSubmit = (e) => {
e.preventDefault();
setAddress(address);
fetchTokens()
.then(data => {
setTokens(data.assets)
})
.catch(err => setTokens([]))
}

//Function to fetch tokens
const fetchTokens = async () => {
if (!utils.isAddress(address)){
alert('Please enter a valid Ethereum wallet address')
return;
}
const provider = new ethers.providers.JsonRpcProvider("YOUR-QUICKNODE-HTTP-URL-HERE");
const tokens = await provider.send("qn_getWalletTokenBalance", {
wallet: address,
contracts: [
'0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', //WETH
'0xdAC17F958D2ee523a2206206994597C13D831ec7', //USDT
'0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0', //MATIC
'0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72', //ENS
]
});
return tokens
}

//JSX code
return(
<div className="h-screen w-screen justify-center space-x-3">
<div className="flex justify-center space-x-3 w-screen h-14 mt-10">
<form
onSubmit={handleSubmit}
className="w-4/12 h-15 relative block overflow-hidden rounded-md border border-gray-200 px-3 pt-3 shadow-sm focus-within:border-blue-600 focus-within:ring-1 focus-within:ring-blue-600 dark:border-gray-700 dark:bg-gray-800">
<input
onChange={e => setAddress(e.target.value)}
type="text"
placeholder="Enter your Address here 🎯"
className="mt-1 w-full border-none p-0 focus:border-transparent focus:outline-none focus:ring-0 sm:text-sm"
/>
<button
type='submit'
className="rounded-lg top-1 right-1 bottom-1 border absolute w-12 justify-center bg-blue-400 text-white p-3 font-bold uppercase"
>
GO
</button>
</form>
</div>
<div className="relative top-4/12 left-1/4 overflow-x-auto justify-center space-x-3 w-6/12 h-140 m-10">
<table className="min-w-full divide-y-2 divide-gray-200 text-sm">
<thead>
<tr>
<th
className="whitespace-nowrap px-4 py-2 text-left font-medium text-gray-1000">
Name
</th>
<th
className="whitespace-nowrap px-4 py-2 text-left font-medium text-gray-900">
Symbol
</th>
<th
className="whitespace-nowrap px-4 py-2 text-left font-medium text-gray-900">
Balance
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{tokens.map((token, index) => (
<tr key={index}>
<td className="whitespace-nowrap px-4 py-2 text-gray-900">{token.name}</td>
<td className="whitespace-nowrap px-4 py-2 text-gray-900">{token.symbol}</td>
<td className="whitespace-nowrap px-4 py-2 text-gray-900">{utils.formatUnits(token.amount, token.decimals)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

export default App;

Start the application by running the following:

npm start

It should look something like this.

How to Build an ERC20 Token Balance App with QuickNode Token API | QuickNode (2)

Paste an address in the input field and click on GO; you should see the balances of tokens.

How to Build an ERC20 Token Balance App with QuickNode Token API | QuickNode (3)

Get the entire code from this GitHub repo.

Conclusion

You are fantastic if you made it till here. In this tutorial, we learned about QuickNode Token API and created a ERC20 token balance app using the Token API.

Make more out of the Token API with its various methods. Join our Discord if you have any questions, or reach out to us via Twitter.

We ❤️ Feedback!

Let us know if you have any feedback or requests for new topics. We'd love to hear from you.

How to Build an ERC20 Token Balance App with QuickNode Token API | QuickNode (2024)

FAQs

How to get ERC20 token balance? ›

Retrieve the balance of an ERC-20 token
  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. Select a token address​ ...
  6. Request the token balance​ ...
  7. Convert the token units​ ...
  8. Run the script​
Sep 5, 2024

How do I create my own ERC20 token? ›

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 much does it cost to create an ERC20 token? ›

Complex Smart Contracts: Writing a basic ERC20 smart contract is fairly straightforward. Basic contracts handle important tasks such as transferring tokens between wallets, checking balances, and issuing tokens. The cost of writing a smart contract for a simple token can range from $1,000 to $5,000.

How to check ERC wallet balance? ›

In the first tab, 'Transaction History', you will find a list of all your recent transactions. In the 'ERC20 Tokens' tab, you can find your token balances. When looking for custom token information, this is where you can select a specific token to find its contract address, decimal count, and symbol.

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.

Can I create my own token? ›

Yes you can create a token that can be minted and/or burned after deploying it to the network. Simply enable the features “Can burn” and “Can mint” upon creation. These features would allow you to change the token supply after token creation.

How to create your own token on base? ›

Now let's create your first Coinbase Base Token with Token Tool
  1. Step 1: Go to Token Tool. ...
  2. Step 2: Choose the Network for Token Creation and Connect Wallet. ...
  3. Step 3: Define Your Coinbase Base token's Features. ...
  4. Step 4: Create Your Coinbase Base Token. ...
  5. Step 5: Confirm the Transaction.

How do I get all ERC20 tokens owned by an address? ›

The following is the process for using Moralis to find all ERC-20 tokens owned by an address:
  1. Step 1: Set up Moralis. Install Node. ...
  2. Step 2: Find all ERC-20 tokens owned by an address. Moralis provides a “getWalletTokenBalances” endpoint to find all ERC-20 tokens owned by an address. ...
  3. Step 3: Run the script.
Mar 13, 2024

What is the best crypto token generator? ›

If you want to create your crypto tokens then you should use the finest token generator platforms such as Cointool. App, Togen.io, and Tokenmint.

How to create Ethereum token for free? ›

Creating ERC-20 Tokens on Ethereum
  1. Step 1: Visit CoinFactory Ethereum Token Generator.
  2. Step 2: Connect your wallet. Start by connecting your wallet to the CoinFactory Generator page. ...
  3. Step 3: Choose a contract template. ...
  4. Step 4: Define Token Details.
Mar 10, 2024

What is ERC20 token generator? ›

9 min read. Feb 21, 2024. An ERC20 token generator can be a powerful tool for creating custom tokens on the Ethereum blockchain. This tool simplifies the process of token creation, making it accessible to a wider audience.

How much does it cost to create a new token? ›

Based on these factors, it can cost anywhere from $10,000 to $100,000 to build a basic Ethereum-based cryptocurrency. If you are aiming for something more complex or ambitious such as an ERC20 token or decentralized app (dApp), then costs could reach upwards of $500,000+.

How much does a smart contract cost? ›

Although it's possible to find a smart contract development company ready to help you for nearly $500, the price may reach even more than $5,000. The deployment costs directly depend on the complexity of the project.

How much is ERC20 worth? ›

ERC20 to NGN
AmountToday at 9:52 pm
1 ERC20NGN 6.07
5 ERC20NGN 30.35
10 ERC20NGN 60.69
50 ERC20NGN 303.47
4 more rows

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 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 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.

Top Articles
Burt Malkiel On Wealthfront’s Promise | Wealthfront
Avoid Systemic Risk in Stock Investing
Tlc Africa Deaths 2021
Amc Near My Location
Booknet.com Contract Marriage 2
Z-Track Injection | Definition and Patient Education
Www.craigslist Augusta Ga
Hay day: Top 6 tips, tricks, and cheats to save cash and grow your farm fast!
Optum Medicare Support
B67 Bus Time
Max 80 Orl
Iron Drop Cafe
Voyeuragency
Hair Love Salon Bradley Beach
Nj State Police Private Detective Unit
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
Dark Chocolate Cherry Vegan Cinnamon Rolls
ZURU - XSHOT - Insanity Mad Mega Barrel - Speelgoedblaster - Met 72 pijltjes | bol
Why do rebates take so long to process?
Craigslist Roseburg Oregon Free Stuff
Rapv Springfield Ma
Danielle Ranslow Obituary
3Movierulz
Craigslist Dubuque Iowa Pets
Giantbodybuilder.com
Effingham Daily News Police Report
Pixel Combat Unblocked
91 Octane Gas Prices Near Me
Ravens 24X7 Forum
Justin Mckenzie Phillip Bryant
Craigslist Lakeside Az
Whitehall Preparatory And Fitness Academy Calendar
Dr Adj Redist Cadv Prin Amex Charge
Studentvue Columbia Heights
Trap Candy Strain Leafly
Final Fantasy 7 Remake Nexus
Tyler Perry Marriage Counselor Play 123Movies
Panorama Charter Portal
Lake Kingdom Moon 31
Beaufort SC Mugshots
Tricia Vacanti Obituary
Hovia reveals top 4 feel-good wallpaper trends for 2024
Luciane Buchanan Bio, Wiki, Age, Husband, Net Worth, Actress
Tricare Dermatologists Near Me
Cch Staffnet
Paperlessemployee/Dollartree
Pickwick Electric Power Outage
855-539-4712
60 Days From August 16
Buildapc Deals
Escape From Tarkov Supply Plans Therapist Quest Guide
Pauline Frommer's Paris 2007 (Pauline Frommer Guides) - SILO.PUB
Latest Posts
Article information

Author: Dean Jakubowski Ret

Last Updated:

Views: 6182

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Dean Jakubowski Ret

Birthday: 1996-05-10

Address: Apt. 425 4346 Santiago Islands, Shariside, AK 38830-1874

Phone: +96313309894162

Job: Legacy Sales Designer

Hobby: Baseball, Wood carving, Candle making, Jigsaw puzzles, Lacemaking, Parkour, Drawing

Introduction: My name is Dean Jakubowski Ret, I am a enthusiastic, friendly, homely, handsome, zealous, brainy, elegant person who loves writing and wants to share my knowledge and understanding with you.