How to Get the Balance of an Ethereum Wallet Address in Code
See How to Connect to Ethereum in Code to understand the first part of this how to that creates the connection to the Ethereum blockchain.
- Create the connection to the Ethereum Blockchain
- Call the web3.eth.getBalance function
Why wrap this in a separate function (getEthBalance)? We do this because the web3 function returns a Javascript promise, and we want to wait for it to execute before we print out the results.
The getBalance function returns the balance in WEI (the smallest measure of ETH). So we use web3.utils to convert the returned balance from WEI to ETH.
NOTE: This code can be used with any of the available Ethereum networks (mainnet, test — Kovan, Rinkeby, etc). To do this just replace the Infura URL with the correct Etheruem network’s URL.
To continue the fun, see the Web3js docs, and extend the code to do more!
If this was helpful, give me some claps and share!