Connect to Web3
Next we need to to connect our code to the Ethereum Virtual Machine (EVM). This is done by connecting to a node on the Ethereum network. If you are developing locally the Web3 library enables you to connect via localhost.
If you plan to deploy your application you will need to connect via HTTPS or WebSockets. Infura is a fantastic free service you can use to connect to an Ethereum node. From Infura’s homepage create a new project to receive your connection url.
Interacting with smart contracts
In order to find the balance of our token we need to invoke the balanceOf() function in our token’s smart contract. This is done through the Application Binary Interface (ABI). An ABI is necessary so that you can specify which function in the contract to invoke. There could be several functions in a contract. You can hard-code the ABI of the function(s) you wish to invoke or you can call the Etherscan API to receive a complete ABI object for a given smart contract address. We will use the Etherscan API in this tutorial.
Create an account on Etherscan to obtain an API key. The Etherscan ABI endpoint requires you to provide the smart contract address of the token you are interacting with and your Etherscan API key.
To obtain the ERC20 token balance we use the balanceOf() method in our Contract object. This invokes the smart contract’s balanceOf() function and returns the result.
You now have your token balance! But the value returned will not account for the token’s decimal format. For example, the Chainlink token ($LINK) has 18 decimals. For an Ethereum wallet that contains 50 LINK tokens, the above call will return
To transform this balance into a human-friendly format we can use the Contract object to find the number of decimal places used by our token.
Now that we know the wallet’s token balance and the number of decimal places used by our token we can normalize our balance with the slice() method.
In final, our code should look like this.
If you find this article helpful it would be greatly appreciated if you could tip Ether to the address below. Thank you!