Complete the code to declare a withdrawal function that sends funds to a user.
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount, "Insufficient funds");
payable(msg.sender).[1](amount);
}The transfer function is used to send Ether to the user safely.
Complete the code to update the user's balance after withdrawal.
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount, "Insufficient funds");
balances[msg.sender] [1] amount;
payable(msg.sender).transfer(amount);
}We subtract the withdrawn amount from the user's balance using -=.
Fix the error in the withdrawal pattern to prevent reentrancy attacks.
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount, "Insufficient funds");
balances[msg.sender] [1] amount;
payable(msg.sender).transfer(amount);
}To prevent reentrancy, update the balance before transferring funds. The operator -= subtracts the amount.
Fill both blanks to implement the Checks-Effects-Interactions pattern correctly.
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount, "Insufficient funds");
balances[msg.sender] [1] amount;
payable(msg.sender).[2](amount);
}First subtract the amount from balance using -=, then transfer funds with transfer.
Fill all three blanks to create a safe withdrawal function using the withdrawal pattern.
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.");
}Check if balance is greater or equal to amount with >=, subtract amount from balance with -=, and use call to send Ether safely.