Web3 by Example: Account Balances

An Ethereum account is an entity with an ether (ETH) balance that can send transactions on Ethereum. Accounts can be user-controlled or deployed as smart contracts.

Account balance is the number of wei owned by this address. Wei is a denomination of ETH and there are 1e+18 wei per ETH.

Import the ethers package that can interact with the Ethereum Blockchain and its ecosystem.

Setup the provider. A Provider in ethers is a read-only abstraction to access the blockchain data.

Also, you can change the default provider. For example, using the alchemy provider.

The getBalance method returns the balance of the given address.

If ens is supported by network, you can use it to replace the address.

Finally, let's use the formatEther utils to format the balance.

balance.js

const { ethers } = require("ethers");
(async () => {
const provider = new ethers.getDefaultProvider("goerli");
const balance = await provider.getBalance(
"0x67CF3bF40b2b3b3D68F6c361AEf81F8AEb2dB637"
);
console.log(ethers.utils.formatEther(balance));
})();

output

❯ node balance.js
3.523785565427238379

Next example: Account Token Balances