Tokens

在不使用 nodejs 的情況下獲取代幣餘額

  • December 5, 2018

我正在嘗試使用純 javascript 獲取令牌餘額,沒有 nodejs 或 web3。

使用 web3 和 nodejs,我可以做到:

exports.getTokenConfirmedBalance = function(node, query, abi) {
   return new Promise((resolve, reject) => {
       try {
           var provider = new web3.providers.HttpProvider(node.url);
           var w3 = new web3(provider);

           var tokenContract = new w3.eth.Contract(abi, query.token_address, {from: query.pub_address});

           tokenContract.methods.balanceOf(query.pub_address).call().then(function (balance) {
               resolve(balance);

           }).catch(function(error) {
               reject(error)
           })

       } catch(error) {
           console.log(error);
           reject(error.message);
       }
   })
}

有什麼建議麼?

使用eth_call

const tokenAddress = "0x123abc";
const account = "0x456def";

// Hex encoding needs to start with 0x.
// First comes the function selector, which is the first 4 bytes of the
//   keccak256 hash of the function signature.
// ABI-encoded arguments follow. The address must be left-padded to 32 bytes.
const data = '0x' +
 keccak_256.hex('balanceOf(address)').substr(0, 8) +
 '000000000000000000000000' + account.substr(2);     // chop off the 0x

// You can send this to any node.
fetch('https://mainnet.infura.io/APIKeyGoesHere', {
 method: 'POST',
 body: JSON.stringify({
   jsonrpc: "2.0",
   id: 1,
   method: "eth_call",
   params: [{
     to: tokenAddress,
     data: data,
   }, 'latest'],
 }),
 headers: new Headers({
   'Content-Type': 'application/json'
 }),
}).then(response =>
 response.json()
).then(json =>
 console.log(json.result)
);

引用自:https://ethereum.stackexchange.com/questions/36036