Home > Blockchain >  How to get balances with wallet address and list token addresses?
How to get balances with wallet address and list token addresses?

Time:11-15

Hi I'm new to blockchain, truffle and Solidity and I've been stuck on this problem for quite long. I want to get all token balances given a wallet address and the token contract addresses using a contract, but I keep encountering

Error: Returned error: VM Exception while processing transaction: revert

whenever I test my contract.

Here's the code of my contract in Solidity:

pragma solidity ^0.8.17;

import {IERC20} from './IERC20.sol';

contract UtilityContract {
    function getBalances(address walletAddress, address[] memory tokenAddresses) public view returns (address[] memory, uint[] memory) {
        uint len = tokenAddresses.length;
        uint[] memory balances = new uint256[](len);
        for (uint i=0; i<len; i  ) {
            balances[i] = IERC20(tokenAddresses[i]).balanceOf(walletAddress);
        }
        return (tokenAddresses, balances);
    }
}

and here's my test code:

const ADDRESS = "0xF977814e90dA44bFA03b6295A0616a897441aceC"; // some wallet address with token balance
const TOKENS = [    // token contract addresses
    "0x111111111117dC0aa78b770fA6A738034120C302",
    "0xC943c5320B9c18C153d1e2d12cC3074bebfb31A2",
];

const UtilityContract = artifacts.require('UtilityContract.sol');
contract('UtilityContract', ()=> {
    it('getBalances', async ()=> {
        const utilityContract = await UtilityContract.new();
        const output = await utilityContract.getBalances(ADDRESS, TOKENS);
        console.log(output);
    });
});

Here's a screenshot of the error: revert error

I imported the IERC20 interface to use the balanceOf function but for some reason it does not work.

CodePudding user response:

Please try this line into your code.. address() convert your wallet string to a valid wallet address format.

IERC20(tokenAddresses[i]).balanceOf(address(walletAddress));

CodePudding user response:

The error is coming from the following line

IERC20(tokenAddresses[i]).balanceOf(walletAddress);

It is most probably related with your input parameters. make sure that token address is actually valid ERC20 token.

so instead of passing token addresses directly, It is safer to create/deploy IERC20 token and pass address of the deployed token into getBalances function for testing.

  • Related