1

I am trying to get Token Balance using plain javascript, no nodejs or web3.

With web3 and nodejs I can do:

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);
        }
    })
}

Any suggestions?

3

Using 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)
);
  • is not needed to pass ABI to getTokenBalance? – Eduardo Jan 12 '18 at 17:24
  • What is getTokenBalance? – user19510 Jan 12 '18 at 17:35
  • that is a function I wrote :D, sorry, I was trying to ask if when getting balance of a ERC20 Token, we do not need to send ABI too?, I send it when using web3 – Eduardo Jan 12 '18 at 19:38
  • I'm not sure what you mean. The ABI tells you what functions are available. We already know that balanceOf is available, since that's part of the interface of an ERC20 token. – user19510 Jan 12 '18 at 19:41
  • I am newbie on this, thanks for the explanation, you rock! – Eduardo Jan 12 '18 at 19:42
0

You can also use Etherscan api!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.