Back to Lessons
Lesson 01

What is balanceOf()?

+5EFFORT
6 sections
balanceOf()
01
text

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.

02
code
solidity
1// Inside the ERC-20 contract
2mapping(address => uint256) private _balances;
3
4function balanceOf(address account) public view returns (uint256) {
5 return _balances[account];
6}
03
text

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.

04
note
Key Insight

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.

05
text

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!

06
code
javascript
1// How a dApp reads your balance
2const balance = await tokenContract.balanceOf(userAddress);
3console.log("Raw balance:", balance.toString());
4// "10000000000000000000" = 10 tokens (with 18 decimals)
Complete

Connect your wallet to mark this lesson as complete

Earn 5 EFFORT tokens