That means the same code will give you:
- the ETH balance on the Ethereum network
- the BNB balance on the Binance Smart Chain
- the FTM balance on the Fantom network
- the AVAX balance on the Avalanche network
And so on.
Here is the full code to get the balance of an address:
const ethers = require("ethers") const provider = new ethers.providers.Web3Provider(YOUR_PROVIDER_HERE) const address = "0x5b8f1310A956ee1521A7bB56160451C786289aa9" // get the balance of the address above (in Wei) const balanceInWei = await provider.getBalance(address) // convert the balance to a readable unit (Ether) const balance = ethers.utils.formatEther(balanceInWei)
To get the balance of an address, we use the
getBalance function and pass in the address that we want to get the balance of.
You can also pass an ENS domain instead of an address in the parameters of the
That function returns a promise that returns the balance when it resolves and that balance is of type
BigNumber because it's the balance in Wei which is the smallest sub-unit of Ether and has 18 decimals. We use that unit for Ethereum and other tokens amounts because we want to avoid using floaters and always use integers.
That's how the Ethereum network is built.
To convert that balance into Ether, we use the
ethers.utils.formatEther function that takes in parameters a
BigNumber and returns that same number in Ether (as a string).
And that's it 🎉
Thank you for reading this article