0
0
Blockchain / Solidityprogramming~5 mins

Access control patterns in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Access control patterns
O(1)
Understanding Time Complexity

When we control who can do what in a blockchain, we use access control patterns. It's important to know how the cost of checking permissions grows as more users or roles are added.

We want to find out how the time to check access changes when the number of users or roles increases.

Scenario Under Consideration

Analyze the time complexity of the following access control check in a smart contract.


mapping(address => bool) public admins;

function isAdmin(address user) public view returns (bool) {
    return admins[user];
}

function addAdmin(address user) public {
    require(admins[msg.sender], "Not authorized");
    admins[user] = true;
}
    

This code checks if a user is an admin by looking up a mapping, and allows existing admins to add new admins.

Identify Repeating Operations

Look for repeated actions that affect time cost.

  • Primary operation: Accessing the mapping to check if a user is an admin.
  • How many times: Each time the function is called, the mapping is accessed once.
How Execution Grows With Input

The time to check if a user is an admin stays about the same no matter how many admins exist.

Input Size (number of admins)Approx. Operations
101 mapping lookup
1001 mapping lookup
10001 mapping lookup

Pattern observation: The operation count stays constant even as the number of admins grows.

Final Time Complexity

Time Complexity: O(1)

This means checking access takes the same amount of time no matter how many users or roles there are.

Common Mistake

[X] Wrong: "Checking if a user is an admin takes longer as more admins are added."

[OK] Correct: The mapping lookup is direct and does not depend on the number of admins, so the time stays constant.

Interview Connect

Understanding how access control checks scale helps you design efficient smart contracts that stay fast as they grow. This skill shows you can think about real-world blockchain performance.

Self-Check

"What if we stored admins in a list instead of a mapping? How would the time complexity change?"