📖 Scenario: You are creating a simple blockchain contract to store and retrieve user balances. This contract uses a mapping to link each user's address to their balance.
🎯 Goal: Build a Solidity contract that uses a mapping to store balances for addresses, set a balance for one user, and then retrieve and display that balance.
📋 What You'll Learn
Create a mapping named balances that links address to uint
Create a uint variable named initialBalance and set it to 100
Write a function setBalance that sets the initialBalance for the sender's address in balances
Write a function getBalance that returns the balance of the sender's address
Print the balance of the sender after setting it
💡 Why This Matters
🌍 Real World
Mappings are used in blockchain contracts to store data linked to user addresses, like balances, permissions, or votes.
💼 Career
Understanding mappings is essential for blockchain developers to manage user data efficiently and securely in smart contracts.
Progress0 / 4 steps
1
Create the mapping to store balances
Create a mapping named balances that links address to uint inside a contract named BalanceTracker.
Blockchain / Solidity
Hint
Think of mapping as a dictionary where each address has a number (uint) balance.
2
Add an initial balance variable
Inside the BalanceTracker contract, create a uint variable named initialBalance and set it to 100.
Blockchain / Solidity
Hint
This variable will hold the starting balance for users.
3
Write a function to set the sender's balance
Add a public function named setBalance inside BalanceTracker that sets the sender's balance in balances to initialBalance.
Blockchain / Solidity
Hint
Use msg.sender to get the address calling the function.
4
Write a function to get the sender's balance and print it
Add a public view function named getBalance inside BalanceTracker that returns the sender's balance from balances. Then, write a comment showing how to call setBalance and getBalance to print the balance.
Blockchain / Solidity
Hint
The view keyword means the function does not change the contract state.
Practice
(1/5)
1. What is the primary purpose of mapping in blockchain smart contracts?
easy
A. To create user interfaces
B. To store a list of all keys used
C. To perform complex mathematical calculations
D. To connect keys to values for fast data lookup
Solution
Step 1: Understand the role of mapping
Mappings are used to link a key to a value, allowing quick access to data based on the key.
Step 2: Compare options
Only To connect keys to values for fast data lookup correctly describes this purpose; others describe unrelated functions.
Final Answer:
To connect keys to values for fast data lookup -> Option D
Quick Check:
Mapping = key-value fast lookup [OK]
Hint: Mappings link keys to values quickly [OK]
Common Mistakes:
Thinking mappings store all keys explicitly
Confusing mappings with arrays or lists
Assuming mappings perform calculations
2. Which of the following is the correct syntax to declare a mapping from address to uint in Solidity?
easy
A. mapping(address, uint) balances;
B. mapping(address => uint) public balances;
C. mapping[address => uint] balances;
D. mapping(address => uint) balances()
Solution
Step 1: Recall Solidity mapping syntax
The correct syntax uses parentheses with key type, arrow, and value type: mapping(keyType => valueType) visibility name;
Step 2: Check each option
mapping(address => uint) public balances; matches the correct syntax. Options A, C, and D have syntax errors like using commas instead of =>, wrong brackets, or function-like declaration.
Final Answer:
mapping(address => uint) public balances; -> Option B
Quick Check:
Correct mapping syntax uses (key => value) [OK]
Hint: Use parentheses and arrow for mapping syntax [OK]
Common Mistakes:
Using square brackets instead of parentheses
Missing visibility keyword like public
Using commas instead of =>
3. Consider the Solidity code:
mapping(address => uint) public balances;
function setBalance(address user, uint amount) public {
balances[user] = amount;
}
function getBalance(address user) public view returns (uint) {
return balances[user];
}
// After calling setBalance(0x1234..., 50), what does getBalance(0x1234...) return?
medium
A. 50
B. Error
C. Undefined
D. 0
Solution
Step 1: Understand setBalance effect
The function sets the balance of the given address to the specified amount, here 50.
Step 2: Understand getBalance output
Calling getBalance with the same address returns the stored value, which is 50.
Final Answer:
50 -> Option A
Quick Check:
Set then get returns stored value [OK]
Hint: Set value then get returns that value [OK]
Common Mistakes:
Assuming default zero is returned after setting
Thinking mapping keys are enumerable
Expecting an error for unset keys
4. What is wrong with this Solidity code snippet?
mapping(address => uint) balances;
function addBalance(address user, uint amount) public {
balances[user] += amount;
}
function getBalance(address user) public view returns (uint) {
return balances[user];
}
medium
A. The mapping is missing initialization before use
B. The mapping keys are not stored, so balances[user] always returns zero
C. There is no error; the code works as expected
D. The mapping is not declared public, so balances cannot be read
Solution
Step 1: Check mapping declaration
Mapping does not need explicit initialization; default values are zero.
Step 2: Check function logic
addBalance adds amount to the current balance; getBalance returns it. Not declaring public means no automatic getter, but manual getter exists.
Final Answer:
There is no error; the code works as expected -> Option C
Quick Check:
Mapping defaults and manual getter work fine [OK]
Hint: Manual getter works even if mapping not public [OK]
Common Mistakes:
Assuming mapping must be public to read values
Thinking mappings need explicit initialization
Confusing mapping keys storage with values
5. You want to track ownership of unique items by users using mappings in Solidity. Which approach correctly allows you to check if a user owns a specific item ID with a direct lookup starting from the user address?
hard
A. mapping(address => mapping(uint => bool)) ownsItem; // nested mapping user to item ID to ownership
B. mapping(uint => address) itemToOwner; // maps item ID to owner address
C. mapping(address => uint) ownerToItem; // stores one item per user
D. mapping(address => uint[]) userItems; // mapping to array of item IDs
Solution
Step 1: Understand ownership tracking needs
We need to check if a user owns a specific item ID, so a direct boolean check is best.
Step 2: Analyze options
Only mapping(address => mapping(uint => bool)) ownsItem; // nested mapping user to item ID to ownership provides a nested mapping(address => mapping(uint => bool)) ownsItem, allowing direct ownsItem[user][itemID] lookup from the user address. A limits to one item per user; B requires starting from item ID; D requires searching an array.
Final Answer:
mapping(address => mapping(uint => bool)) ownsItem; // nested mapping user to item ID to ownership -> Option A
Quick Check:
Nested mapping allows direct ownership check [OK]
Hint: Use nested mapping for user-item ownership check [OK]
Common Mistakes:
Using single mapping limiting one item per user
Using arrays which are not mappings
Confusing item-to-owner with user-to-item ownership check
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.