Checks-Effects-Interactions pattern in Blockchain / Solidity - Time & Space Complexity
When working with blockchain smart contracts, it's important to understand how the order of operations affects performance.
We want to see how the Checks-Effects-Interactions pattern impacts the number of steps as input grows.
Analyze the time complexity of the following smart contract function using the Checks-Effects-Interactions pattern.
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount, "Insufficient balance"); // Check
balances[msg.sender] -= amount; // Effect
(bool success, ) = payable(msg.sender).call{value: amount}(""); // Interaction
require(success, "Transfer failed");
}
This function checks the user's balance, updates it, then sends funds safely.
Look for loops or repeated steps in this function.
- Primary operation: Single balance check and update per call.
- How many times: Exactly once per function call, no loops or recursion.
The function does a fixed number of steps regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 steps (check, update, send) |
| 100 | 3 steps |
| 1000 | 3 steps |
Pattern observation: The number of operations stays the same no matter how many users or transactions happen.
Time Complexity: O(1)
This means the function runs in constant time, doing the same amount of work each call.
[X] Wrong: "Because the function interacts with external addresses, it must take longer as more users exist."
[OK] Correct: Each call handles only one user's balance and interaction, so the work does not grow with the number of users.
Understanding this pattern shows you can write safe and efficient smart contracts, a skill that helps you build trust and avoid costly bugs.
"What if the function had to send funds to multiple addresses in a loop? How would the time complexity change?"