Every ERC-20 token contract maintains a mapping that tracks how many tokens each address owns. The balanceOf() function is how we read this information.
1// Inside the ERC-20 contract2mapping(address => uint256) private _balances;34function balanceOf(address account) public view returns (uint256) {5return _balances[account];6}
This is a 'view' function, meaning it only reads data from the blockchain - it doesn't modify anything. Because of this, calling balanceOf() is FREE and doesn't require gas.
Key insight: The balance is stored as a uint256 (unsigned 256-bit integer) in the smallest unit. For tokens with 18 decimals, 1 token = 1,000,000,000,000,000,000 (10^18) in raw units.
When you connect your wallet to a dApp, the first thing it typically does is call balanceOf(yourAddress) to display how many tokens you own. This is exactly what happens in the header of this dApp!
1// How a dApp reads your balance2const balance = await tokenContract.balanceOf(userAddress);3console.log("Raw balance:", balance.toString());4// "10000000000000000000" = 10 tokens (with 18 decimals)
Connect your wallet to mark this lesson as complete
Earn 5 EFFORT tokens