Created
June 19, 2021 07:37
-
-
Save arshamalh/33e6646eb793997f2cc69668bd97010a to your computer and use it in GitHub Desktop.
Finding ETH erc20 tokens balance using JavaScript and infura.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const infuraProjectID = "Write your infura projectID here" // https://infura.io/signup | |
const tokenContractAddress = "0xdac17f958d2ee523a2206206994597c13d831ec7" | |
const accountAddress = "0x757d576da3fba018b1bd9cdd05fa4ca0261792c8" | |
// Dependencies | |
const Web3 = require('web3'); | |
const web3 = new Web3() | |
const keccak_256 = require('js-sha3').keccak256 | |
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/v3/' + infuraProjectID | |
const postResp = retry(async () => { | |
return 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 | |
}) | |
}, retryOptions); | |
// Log the full result object below | |
async function showBalance() { | |
let res = await postResp | |
let balance = web3.utils.toDecimal(res.result) | |
console.log(`Balance : ${balance}`) | |
} | |
showBalance() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment