window.ethereum.request get_balance 方法,如何获取特定代币的代币数量?

window.ethereum.request get_balance method, how do I get the tokens amount of specific token?

我想知道,可以做些什么来获得我想要的特定令牌的余额而不是以太坊?

const getAccountBalance = (account) => {
        window.ethereum.request({method: 'eth_getBalance', params: [account, 'latest']})
        .then(balance => {
            setUserBalance(ethers.utils.formatEther(balance));
        })
        .catch(error => {
            setErrorMessage(error.message);
        });
    };

我使用 ethers.js 库。

当钱包连接到您的网站时,您也连接到代币合约。

let provider;
let signer;
let signerAddress;

const tokenContractAddress = TOKEN_CONTRACT_ADDRESS;
const tokenABI = TOKEN_ABI;
let tokenContract;
let userTokenBalance;

const startFunction = async () => {
    //Connect to MetaMask
    await ethereum.request({ method: 'eth_requestAccounts'});
    //get provider
    provider = new ethers.providers.Web3Provider(window.ethereum);
    //get signer (I usually use signer because when you connect to contract via signer,
    //you can write to it too, but via provider, you can only read data from contract)
    signer = provider.getSigner();
    //Get connected wallet address
    signerAddress = await signer.getAddress();
    //Connect to contract
    tokenContract = await new ethers.Contract(tokenContractAddress , tokenABI , signer);
}
startFunction();

const getAccountBalance = async () => {
    userTokenBalance = await tokenContract.balanceOf(signerAddress);
    //Note that userTokenBalance is not a number and it is bigNumber
    console.log(userTokenBalance);
}