Property: March 24, 2023 8:54 AM category: 技术分享 date: 2023/03/20 slug: web3js-get-specified-token-balance status: Published summary: web3js获取区块链钱包地址指定代币余额 tags: metamask, 以太坊, 区块链, 开发 type: Post
书接上回: metamask小狐狸钱包 eth_sendTransaction接口发起指定币种交易
获取指定钱包地址默认代币
1var account = ethereum.selectedAddress2// 获取余额3ethereum.request({4 method: 'eth_getBalance',5 params: [6 account ,7 'latest'8 ]9 })10 .then((result) => {11 console.log("获取余额success--->" + result)12 let formatEther = ethers.utils.formatEther(result); //16进制的wei13 console.log(formatEther)14 })15 .catch((error) => {2 collapsed lines
16 console.error(error)17 });获取指定钱包地址指定代币
和发起指定代币交易一样,需要创建代币的智能合约实例,通过实例的方法,获取钱包地址的对应代币余额
1var account = ethereum.selectedAddress2const USDTContractAddress = "..."; // USDT合约地址3const USDTContractABI = [...]; // USDT合约ABI4// 创建一个web3实例,连接到metamask提供的provider5const web3 = new Web3(window.ethereum);6// 创建一个USDT合约实例7const USDTContract = new web3.eth.Contract(USDTContractABI, USDTContractAddress);8USDTContract.methods.balanceOf(account).call((error, result) => {9 if (error) {10 console.error(error)11 } else {12 console.log(result);13 let formatEther = ethers.utils.formatEther(result); //16进制的wei14 console.log(formatEther)15 }1 collapsed line
16});