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:

Solidity




interface IERC20 {
    function balanceOf(address _owner) external view returns (uint256);
}


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.

Solidity




function listUserTokens(address _user, address[] memory _tokenAddresses) public view returns (uint256[] memory) {
    uint256[] memory userTokenBalances = new uint256[](_tokenAddresses.length);
  
    for (uint256 i = 0; i < _tokenAddresses.length; i++) {
        IERC20 token = IERC20(_tokenAddresses[i]);
        userTokenBalances[i] = token.balanceOf(_user);
    }
  
    return userTokenBalances;
}


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.

Solidity




pragma solidity ^0.8.0;
  
// Import the ERC-20 interface
interface IERC20 {
    function balanceOf(address _owner) external view returns (uint256);
}
  
contract TokenLister {
    // Function to list user tokens
    function listUserTokens(address _user, address[] memory _tokenAddresses) public view returns (uint256[] memory) {
        uint256[] memory userTokenBalances = new uint256[](_tokenAddresses.length);
  
        for (uint256 i = 0; i < _tokenAddresses.length; i++) {
            IERC20 token = IERC20(_tokenAddresses[i]);
            userTokenBalances[i] = token.balanceOf(_user);
        }
  
        return userTokenBalances;
    }
}


Output:



How to List all Tokens of User in Solidity

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.

Similar Reads

Understanding ERC-20 Tokens

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

Listing All Tokens of a User

...