0
0
Blockchain / Solidityprogramming~30 mins

Withdrawal patterns in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Withdrawal Patterns
📖 Scenario: You are building a simple smart contract that manages user balances and allows withdrawals. To keep the contract safe, you want to implement a withdrawal pattern that prevents common security issues like reentrancy attacks.
🎯 Goal: Create a smart contract that stores user balances, allows deposits, and implements a safe withdrawal pattern where users can withdraw their funds securely.
📋 What You'll Learn
Create a mapping called balances to store user balances.
Create a function deposit that lets users add funds to their balance.
Create a function withdraw that lets users withdraw their balance safely using the withdrawal pattern.
Use the withdrawal pattern by first setting the user's balance to zero before sending funds.
💡 Why This Matters
🌍 Real World
Withdrawal patterns are essential in smart contracts to protect user funds and prevent attacks like reentrancy.
💼 Career
Understanding safe withdrawal patterns is critical for blockchain developers to write secure contracts and protect assets.
Progress0 / 4 steps
1
Set up the balances mapping
Create a public mapping called balances that maps address to uint to store user balances.
Blockchain / Solidity
Need a hint?

Use mapping(address => uint) public balances; to store balances for each user address.

2
Add deposit function
Create a public payable function called deposit that increases the sender's balance by msg.value.
Blockchain / Solidity
Need a hint?

Use balances[msg.sender] += msg.value; inside the deposit function.

3
Add safe withdraw function
Create a public function called withdraw that lets the sender withdraw their entire balance safely. First, store the sender's balance in a local variable amount. Then set the sender's balance to zero. Finally, send amount to the sender using payable(msg.sender).transfer(amount);.
Blockchain / Solidity
Need a hint?

Remember to set the balance to zero before transferring funds to prevent reentrancy.

4
Test withdrawal output
Add a public view function called getBalance that returns the balance of the sender. Then, write a comment showing the expected output after a deposit of 1 ether and a withdrawal.
Blockchain / Solidity
Need a hint?

The getBalance function helps check the user's balance after withdrawal.