The reentrancy rule is a security rule designed to prevent reentrancy vulnerabilities. It flags code patterns where state changes (such as updating a mapping or balance) happen after an external call or transfer (like msg.sender.transfer() or msg.sender.send()).
To avoid this vulnerability, follow the Checks-Effects-Interactions pattern:
- Checks: Validate conditions (e.g.,
require statements). - Effects: Update the contract's internal state (e.g.,
shares[msg.sender] = 0;). - Interactions: Perform external calls or transfers (e.g.,
msg.sender.transfer(amount);).
### 👍 Correct Pattern (Checks-Effects-Interactions)
```solidity
contract A {
mapping(address => uint) private shares;
function b() external {
uint amount = shares[msg.sender];
// Effect: Update state BEFORE the transfer
shares[msg.sender] = 0;
// Interaction: Perform the transfer
msg.sender.transfer(amount);
}
}
👎 Incorrect Pattern (Vulnerable)
contract A {
mapping(address => uint) private shares;
function b() external {
uint amount = shares[msg.sender];
// Interaction: Perform the transfer
msg.sender.transfer(amount);
// Effect: State change happens AFTER the transfer (Vulnerable!)
shares[msg.sender] = 0;
}
}