Sample code to request the balance in ERC20 tokens held by a specific Ethereum address at a specific Contract address.
// Based on : https://ethereum.stackexchange.com/questions/36036/get-token-balance-without-using-nodejs
// CUSTOM VARIABLES
// You'll need to set 'infuraApiKey' as a private RunKit environment variable:
// https://runkit.com/settings/environment
// 'tokenContractAddress', and 'accountAddress' can also be set to override the
// default values set here.
// Infura : https://infura.io/signup
const infuraApiKey = process.env.infuraApiKey
// The address of the ERC20 token contract (0x...)
// An example contract address (TNT) is: 0x08f5a9235b08173b7569f83645d2c7fb55e8ccd8
// https://etherscan.io/address/0x08f5a9235b08173b7569f83645d2c7fb55e8ccd8
const tokenContractAddress = process.env.tokenContractAddres || '0x08f5a9235b08173b7569f83645d2c7fb55e8ccd8'
// The Ethereum address of the account that has a balance to be checked (0x...)
// An example address that holds TNT is: 0xdDFFF2b78463AB1cA781e853BB888FDfd06083d3
// https://etherscan.io/address/0xdDFFF2b78463AB1cA781e853BB888FDfd06083d3#tokentxns
const accountAddress = process.env.accountAddres || '0xdDFFF2b78463AB1cA781e853BB888FDfd06083d3'
// Dependencies
const BigNumber = require('bignumber.js')
const Web3 = require('web3');
const web3 = new Web3()
const keccak_256 = require('js-sha3').keccak256
const request = require('request')
const rp = require('request-promise')
const retry = require('async-retry')
const retryOptions = {
retries: 10,
factor: 1.0,
minTimeout: 750,
onRetry: (error) => { console.error(`retrying : ${error.message}`) }
}
// 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' +
accountAddress.substr(2) // chop off the 0x
const postURI = 'https://mainnet.infura.io/' + infuraApiKey
var postResp = await retry(async bail => {
let resp = await rp({
method: 'POST',
uri: postURI,
body: {
jsonrpc: "2.0",
id: 1,
method: "eth_call",
params: [{
to: tokenContractAddress,
data: data,
}, 'latest'],
},
headers: {
'content-type': 'application/json'
},
json: true
})
return resp
}, retryOptions)
// Log the full result object below
console.log(postResp)
// Since this example is testing balance checking for the
// Tierion Network Token (TNT) we display the balance as `grains`
// which are the smallest unit of a TNT token.
let balance = web3.toDecimal(postResp.result)
let tnt = balance/100000000
console.log(`Balance : ${tnt} TNT (${balance} TNT grains)`)