gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:35:42 24 4
gpt4 key购买 nike

我想知道,可以做些什么来获得我想要的特定 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);
}

关于reactjs - window.ethereum.request get_balance 方法,如何获取特定代币的代币数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69810084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com