Receiving Ether in Blockchain / Solidity - Time & Space Complexity
When a smart contract receives Ether, it runs code to handle the incoming payment.
We want to understand how the time it takes grows as more Ether transfers happen.
Analyze the time complexity of the following Solidity code snippet.
contract ReceiveEther {
event Received(address sender, uint amount);
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
This contract receives Ether and emits an event each time it happens.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The receive function runs once per Ether transfer.
- How many times: It runs exactly once for each incoming payment.
Each Ether transfer triggers the receive function once, doing a fixed amount of work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to receive() |
| 100 | 100 calls to receive() |
| 1000 | 1000 calls to receive() |
Pattern observation: The total work grows directly with the number of transfers.
Time Complexity: O(n)
This means the total time grows linearly with the number of Ether transfers received.
[X] Wrong: "The receive function runs once and handles all Ether transfers at once."
[OK] Correct: Each transfer triggers the receive function separately, so the work adds up with each payment.
Understanding how contract functions run per transaction helps you explain how blockchain handles many users efficiently.
"What if the receive function also updated a growing list of senders? How would the time complexity change?"