0
0
Blockchain / Solidityprogramming~5 mins

Receive and fallback functions in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Receive and fallback functions
O(n)
Understanding Time Complexity

When a smart contract receives Ether, it uses special functions called receive and fallback. Understanding how long these functions take to run helps us know how the contract behaves as more transactions come in.

We want to see how the time to handle incoming payments grows as the number of calls increases.

Scenario Under Consideration

Analyze the time complexity of the following Solidity contract snippet.


contract SimpleWallet {
    event Received(address, uint);
    
    receive() external payable {
        emit Received(msg.sender, msg.value);
    }

    fallback() external payable {
        // fallback logic
    }
}
    

This contract uses receive to accept Ether and emit an event, and fallback to handle other calls.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Each call to receive or fallback runs once per transaction.
  • How many times: Once per incoming transaction; no loops inside these functions.
How Execution Grows With Input

Each transaction triggers the receive or fallback function once, so the work grows directly with the number of transactions.

Input Size (n)Approx. Operations
1010 function calls
100100 function calls
10001000 function calls

Pattern observation: The total work increases in a straight line as more transactions arrive.

Final Time Complexity

Time Complexity: O(n)

This means the time to handle all incoming calls grows directly with the number of calls.

Common Mistake

[X] Wrong: "The receive or fallback function runs multiple times inside one transaction, so complexity is higher."

[OK] Correct: Each transaction triggers these functions only once, so no repeated loops happen inside them by default.

Interview Connect

Knowing how receive and fallback scale helps you design contracts that handle payments efficiently and predict costs as usage grows.

Self-Check

"What if the fallback function included a loop over an array of stored addresses? How would the time complexity change?"