如何获取钱包地址和列表代币地址的余额?

问题描述 投票:0回答:2

嗨,我是区块链、松露和 Solidity 的新手,我已经被这个问题困扰了很长时间。我想使用合约获取给定钱包地址和代币合约地址的所有代币余额,但我一直遇到

错误:返回错误:处理事务时出现VM异常:还原

每当我测试我的合同时。

这是我在 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);
    }
}

这是我的测试代码:

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);
    });
});

错误截图如下: revert error

我导入了IERC20接口来使用balanceOf函数,但不知为何不起作用

javascript testing blockchain solidity truffle
2个回答
0
投票

请在您的代码中尝试这一行.. address() 将您的钱包字符串转换为有效的钱包地址格式。

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


0
投票

只是在这里补充一下,如果你在智能合约之外得到它,你可以考虑像 Covalent 这样的 API。他们有一个余额端点,允许您获取地址的所有 ERC20 令牌

© www.soinside.com 2019 - 2024. All rights reserved.