Web3.js 获取代币余额

  1. 获取web3
var Web3 = require('web3');  
var ethereumUri = 'http://47.101.47.204:8545';  
let web3 = new Web3();  
web3.setProvider(new web3.providers.HttpProvider(ethereumUri));
  1. 获取代币abi (暂时用接口,还没研究出来获取方法)
async function getTokensABI(address){

    let AbiUrl = "http://api.etherscan.io/api?module=contract&action=getabi&address=" + address

    try {
        let res = await axios.get(AbiUrl)
        let result = res.data.result
        return result
    } catch(err){
        console.log(err)
        return "0"
    }
}
  1. 调用合约code中查询余额的方法
async function getBalanceOf(address,account){  
    let contractAbi = await getTokensABI(address)
    let ABI = JSON.parse(contractAbi)
    let myContract = new WEB3.eth.Contract(ABI,address)
    let result = await myContract.methods.balanceOf(account).call()
    return (result / basic18) + ''   // 结果是除以18位
}