0
0
Blockchain / Solidityprogramming~3 mins

Why Checks-Effects-Interactions pattern in Blockchain / Solidity? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if a tiny change in your code order could stop hackers from stealing millions?

The Scenario

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?

The Problem

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 Solution

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.

Before vs After
Before
if(balance >= amount) {
  send(amount);
  balance -= amount;
}
After
if(balance >= amount) {
  balance -= amount;
  send(amount);
}
What It Enables

This pattern makes your smart contracts safer and more reliable by preventing common security bugs related to external calls.

Real Life Example

When building a decentralized bank, using Checks-Effects-Interactions ensures that users can't trick the system into withdrawing more money than they have.

Key Takeaways

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.