Transaction confirmation handling in Blockchain / Solidity - Time & Space Complexity
When a blockchain transaction is sent, the system waits for confirmations to ensure it is securely recorded.
We want to understand how the time to handle these confirmations grows as the number of confirmations increases.
Analyze the time complexity of the following code snippet.
function waitForConfirmations(txHash, requiredConfirmations) {
let confirmations = 0;
while (confirmations < requiredConfirmations) {
confirmations = getConfirmations(txHash); // fetch current confirmations
sleep(1000); // wait 1 second before checking again
}
return true;
}
This code waits until a transaction reaches the required number of confirmations by repeatedly checking the current count.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that repeatedly calls
getConfirmations. - How many times: It runs until the required number of confirmations is reached.
Each confirmation requires one loop cycle, so the total checks grow directly with the number of confirmations needed.
| Input Size (requiredConfirmations) | Approx. Operations (loop cycles) |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows in a straight line as confirmations increase.
Time Complexity: O(n)
This means the time to confirm grows directly in proportion to the number of confirmations required.
[X] Wrong: "The confirmation check happens only once, so time is constant regardless of confirmations."
[OK] Correct: The code checks repeatedly until all confirmations arrive, so more confirmations mean more checks and more time.
Understanding how waiting for confirmations scales helps you reason about blockchain transaction reliability and responsiveness in real projects.
"What if the code checked confirmations in batches instead of one by one? How would the time complexity change?"