ERC-20 implementation in Blockchain / Solidity - Time & Space Complexity
When working with ERC-20 tokens, it's important to understand how the time it takes to run functions changes as the number of users or transactions grows.
We want to know how the cost of operations like transferring tokens or checking balances grows with more users.
Analyze the time complexity of the following ERC-20 transfer function.
function transfer(address to, uint256 amount) public returns (bool) {
require(balanceOf[msg.sender] >= amount, "Insufficient balance");
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}
This function moves tokens from the sender to another address and updates balances.
Look for loops or repeated steps inside the function.
- Primary operation: Simple balance checks and updates.
- How many times: Each call runs these steps once, no loops or recursion.
The function does the same fixed steps no matter how many users or tokens exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 steps |
| 100 | 5 steps |
| 1000 | 5 steps |
Pattern observation: The number of operations stays the same even if more users or tokens exist.
Time Complexity: O(1)
This means the transfer function takes the same amount of time no matter how many users or tokens there are.
[X] Wrong: "The transfer function takes longer as more users hold tokens."
[OK] Correct: The function only updates balances for two addresses, so it does not check or loop through all users.
Understanding that simple token transfers run in constant time helps you explain how blockchain operations stay efficient even as networks grow.
"What if the transfer function needed to update a list of all token holders? How would the time complexity change?"