A beginner-friendly Solidity contract that demonstrates how one user can give another user permission to spend from their balance.
Built to learn how mapping, nested mapping, msg.sender, and require work together.
To understand how to:
- Store user balances
- Set and manage allowances between users
- Use
msg.senderto identify who is calling a function - Apply
requirechecks for validation
Contract Name: AllowanceWallet
Solidity Version: ^0.8.30
| Variable | Type | Description |
|---|---|---|
owner |
address |
The address that deployed the contract. |
balances |
mapping(address => uint256) |
Tracks how much each user owns. |
allowances |
mapping(address => mapping(address => uint256)) |
Tracks how much one user allows another to spend. |
Adds balance to the caller’s own account.
Lets a user give another address permission to spend up to a certain amount from their balance.
Includes safety checks:
- Cannot give allowance to self.
- Allowance cannot exceed current balance.
Allows a spender to spend part of the owner’s balance, if the owner gave them enough allowance.
Decreases both:
- The owner’s balance.
- The spender’s remaining allowance.
Returns the caller’s current balance.
Returns how much the spender can spend from the _owner's account.
- Alice calls
deposit(100)→ Alice’s balance = 100 - Alice calls
setAllowance(Bob, 40)→ Bob can spend 40 from Alice’s balance - Bob calls
spendFrom(Alice, 25)- Alice’s balance = 75
- Bob’s remaining allowance = 15
- Remix IDE
- Solidity
^0.8.30
- How to use nested mappings:
mapping(address => mapping(address => uint256)) - How
msg.senderidentifies who is calling a function - Why
requireis used for safety and validation - Basic contract structure and data flow between users