VOOZH about

URL: https://www.geeksforgeeks.org/solidity/how-to-list-all-tokens-of-user-in-solidity/

⇱ How to List all Tokens of User in Solidity - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to List all Tokens of User in Solidity

Last Updated : 28 Apr, 2025

Ethereum, the main blockchain stage for decentralized applications (DApps), permits designers to make many advanced resources, including tokens. This article focuses on discussing the technique to list all the tokens of a user in Solidity.

Understanding ERC-20 Tokens

ERC-20 tokens adhere to a standard interface, making them interchangeable and widely supported by various platforms and wallets.

ERC-20 tokens come with a set of essential functions:

  • balanceOf(address): Returns the token balance of a specific address.
  • transfer(address, uint256): Allows the transfer of tokens between addresses.

Let's create a simplified ERC-20 token contract for our examples:

Listing All Tokens of a User

Step 1: Import ERC-20 Interfaces

First, we need to import the ERC-20 interface into our contract to access the required functions. Create an interface like this:

This step ensures our contract can interact with ERC-20 tokens.

Step 2: Create a Function to List Tokens

Next, we'll implement a function that lists all tokens of a user. This function will loop through known ERC-20 token addresses and call the balanceOf function for each token contract, passing the user's address as an argument.

We define a function called listUserTokens, which takes the user's address and an array of token addresses as input. It then loops through the token addresses, calls balanceOf for each token contract, and stores the balances in an array.

Step 3: Deploy Your Contract and Call the Function

Deploy your contract on the Ethereum blockchain, and when calling the listUserTokens function, pass an array of ERC-20 token addresses. This will return an array of token balances for the specified user.

Output:

👁 Output

Comment

Explore