What if a tiny change in your code order could stop hackers from stealing millions?
Why Checks-Effects-Interactions pattern in Blockchain / Solidity? - Purpose & Use Cases
Imagine you are writing a smart contract that sends money to users after verifying their balance. You first check the balance, then send the money, and finally update the balance. But what if the sending fails or the user's contract calls back unexpectedly?
Doing these steps without order can cause serious problems like reentrancy attacks, where a malicious contract tricks your contract into sending money multiple times. This makes your contract unsafe and can lead to lost funds.
The Checks-Effects-Interactions pattern helps by organizing your code: first check all conditions, then update your contract's state, and only after that interact with other contracts. This order prevents attackers from exploiting your contract during external calls.
if(balance >= amount) {
send(amount);
balance -= amount;
}if(balance >= amount) {
balance -= amount;
send(amount);
}This pattern makes your smart contracts safer and more reliable by preventing common security bugs related to external calls.
When building a decentralized bank, using Checks-Effects-Interactions ensures that users can't trick the system into withdrawing more money than they have.
Manual ordering of checks and interactions can cause security risks.
Checks-Effects-Interactions enforces a safe order: check, update, then interact.
Following this pattern protects your contract from reentrancy attacks.