【问题标题】:window.ethereum.request get_balance method, how do I get the tokens amount of specific token?window.ethereum.request get_balance 方法,如何获取特定token的token数量?
【发布时间】:2021-12-16 23:03:56
【问题描述】:

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

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 中使用代币合约吗!?
  • 我几乎没有,但你的意思是什么?虽然我确实弄清楚了如何进行交易,但是我还不知道如何使用不同的令牌
  • 要获得一个地址的代币余额,你必须使用它的合约来这样做。

标签: reactjs web3 ethers.js


【解决方案1】:

我使用 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-20
    • 2019-11-13
    • 2020-07-15
    • 2017-07-10
    • 1970-01-01
    • 2019-12-01
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多