August 2019
Intermediate to advanced
486 pages
13h 52m
English
To prevent a reentrancy attack, the state of the variables should be updated first, and then ether should be sent to a user's account as follows:
// Good Practicefunction withdraw() public { uint amount = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(amount); }
In the preceding code, we are updating the balance of the user's account to 0 (zero), and then only sending the ether to the user.
Remember to always update the relevant state variables first and then only transfer ether at the last step.
Read now
Unlock full access