Re-entrancy
Re-entrancy occurs when a contract makes a call back into the contract that called it, e.g. Contract A
calls Contract B
but then Contract B
makes a call back into Contract A
.
To mitigate security concerns there are two approaches that are commonly used:
- Implement a guard: detect when a re-entrancy occurs
- Defensive programming: perform calls after all state changes have been made
Re-entrancy Guard
Sway provides a stateless re-entrancy guard, which reverts at run-time when re-entrancy is detected.
To use the guard we must import it.
use reentrancy::reentrancy_guard;
Then call it in a contract function.
fn deposit() {
reentrancy_guard();
// code
}
Checks-Effects-Interactions Pattern
The pattern states that all state (storage) changes should be made before a call is made.
fn withdraw() {
// Step 1. Perform any state changes to update balance
// Step 2. After all state changes make a call
}