0
0
Blockchain / Solidityprogramming~10 mins

Withdrawal patterns in Blockchain / Solidity - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a withdrawal function that sends funds to a user.

Blockchain / Solidity
function withdraw(uint amount) public {
    require(balances[msg.sender] >= amount, "Insufficient funds");
    payable(msg.sender).[1](amount);
}
Drag options to blanks, or click blank then click option'
AsendFunds
Bapprove
Cdeposit
Dtransfer
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'deposit' instead of 'transfer' to send funds.
Using 'approve' which is for token allowances, not sending Ether.
2fill in blank
medium

Complete the code to update the user's balance after withdrawal.

Blockchain / Solidity
function withdraw(uint amount) public {
    require(balances[msg.sender] >= amount, "Insufficient funds");
    balances[msg.sender] [1] amount;
    payable(msg.sender).transfer(amount);
}
Drag options to blanks, or click blank then click option'
A-=
B*=
C+=
D/=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+=' which would increase the balance incorrectly.
Using '*=' or '/=' which are not appropriate here.
3fill in blank
hard

Fix the error in the withdrawal pattern to prevent reentrancy attacks.

Blockchain / Solidity
function withdraw(uint amount) public {
    require(balances[msg.sender] >= amount, "Insufficient funds");
    balances[msg.sender] [1] amount;
    payable(msg.sender).transfer(amount);
}
Drag options to blanks, or click blank then click option'
A-=
B+=
C=
D*=
Attempts:
3 left
💡 Hint
Common Mistakes
Updating balance after transfer, which can cause reentrancy.
Using '=' which overwrites balance incorrectly.
4fill in blank
hard

Fill both blanks to implement the Checks-Effects-Interactions pattern correctly.

Blockchain / Solidity
function withdraw(uint amount) public {
    require(balances[msg.sender] >= amount, "Insufficient funds");
    balances[msg.sender] [1] amount;
    payable(msg.sender).[2](amount);
}
Drag options to blanks, or click blank then click option'
A-=
Bsend
Ctransfer
D+=
Attempts:
3 left
💡 Hint
Common Mistakes
Sending Ether before updating balance.
Using 'send' which returns a boolean and requires extra checks.
5fill in blank
hard

Fill all three blanks to create a safe withdrawal function using the withdrawal pattern.

Blockchain / Solidity
function withdraw(uint amount) public {
    uint balance = balances[msg.sender];
    require(balance [1] amount, "Insufficient funds");
    balances[msg.sender] [2] amount;
    (bool success, ) = payable(msg.sender).[3]{value: amount}("");
    require(success, "Transfer failed.");
}
Drag options to blanks, or click blank then click option'
A>=
B-=
Ccall
D+=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+=' to update balance which increases it.
Using 'transfer' instead of 'call' which is safer in some cases.
Not checking the success of the call.