Liquidity pools in Blockchain / Solidity - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with liquidity pools in blockchain, it is important to understand how the time to process transactions grows as more users interact with the pool.
We want to know how the number of operations changes as the pool size or number of swaps increases.
Analyze the time complexity of the following liquidity pool swap function.
function swap(uint amountIn, address tokenIn, address tokenOut) public returns (uint amountOut) {
uint reserveIn = reserves[tokenIn];
uint reserveOut = reserves[tokenOut];
amountOut = getAmountOut(amountIn, reserveIn, reserveOut);
reserves[tokenIn] += amountIn;
reserves[tokenOut] -= amountOut;
return amountOut;
}
This code swaps tokens by calculating output amount and updating reserves in the liquidity pool.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing and updating reserves for two tokens.
- How many times: Each swap call does these operations once; no loops or recursion inside.
The time to process each swap stays about the same no matter how many swaps have happened before.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 swaps | 10 operations (one per swap) |
| 100 swaps | 100 operations |
| 1000 swaps | 1000 operations |
Pattern observation: The work grows linearly with the number of swaps, as each swap is handled independently.
Time Complexity: O(1)
This means each swap operation takes a fixed amount of time, regardless of how many swaps have happened before.
[X] Wrong: "Swapping tokens takes longer as the pool grows because more tokens are involved."
[OK] Correct: The swap function only updates reserves for the two tokens involved, so the time does not increase with pool size.
Understanding how operations scale in blockchain functions like liquidity pools shows you can reason about efficiency and user experience in decentralized apps.
"What if the swap function needed to update reserves for all tokens in the pool? How would the time complexity change?"
Practice
Solution
Step 1: Understand liquidity pool function
Liquidity pools let users trade tokens directly without needing a middleman like an exchange.Step 2: Compare options to definition
Only To allow users to trade tokens directly without a middleman describes this function correctly; others describe unrelated blockchain features.Final Answer:
To allow users to trade tokens directly without a middleman -> Option AQuick Check:
Liquidity pools enable direct token trading = B [OK]
- Confusing liquidity pools with token creation
- Thinking liquidity pools mine blocks
- Assuming liquidity pools store passwords
Solution
Step 1: Identify data structure for mapping users to shares
A dictionary (key-value pairs) is best to map user names to their share amounts.Step 2: Check options for dictionary syntax
shares = {'user1': 100, 'user2': 50} uses a dictionary with user keys and numeric values, which is correct syntax and logic.Final Answer:
shares = {'user1': 100, 'user2': 50} -> Option AQuick Check:
Use dictionary for user-share mapping = A [OK]
- Using lists instead of dictionaries for key-value pairs
- Incorrect tuple ordering for mapping
- Using string instead of structured data
pool = {'tokenA': 1000, 'tokenB': 2000}
new_tokenA = 100
new_tokenB = 200
pool['tokenA'] += new_tokenA
pool['tokenB'] += new_tokenB
price_ratio = pool['tokenB'] / pool['tokenA']
print(round(price_ratio, 2))What is the printed output?
Solution
Step 1: Calculate updated token amounts in pool
tokenA = 1000 + 100 = 1100; tokenB = 2000 + 200 = 2200Step 2: Compute price ratio and round
price_ratio = 2200 / 1100 = 2.0; rounded to 2 decimals is 2.0Final Answer:
2.0 -> Option CQuick Check:
2200 รท 1100 = 2.0 [OK]
- Dividing before adding new tokens
- Rounding incorrectly
- Mixing tokenA and tokenB values
pool = {'tokenA': 500, 'tokenB': 1000}
new_tokenA = 50
new_tokenB = 100
pool['tokenA'] =+ new_tokenA
pool['tokenB'] =+ new_tokenB
print(pool)What is the bug?
Solution
Step 1: Identify operator usage in assignment
The code uses '=+' which is not a valid operator; it assigns positive new_tokenA instead of adding.Step 2: Correct operator for addition assignment
The correct operator is '+=' to add new_tokenA to pool['tokenA'] and similarly for tokenB.Final Answer:
The operator '=+' is incorrect; should be '+=' -> Option BQuick Check:
Use '+=' to add values in place [OK]
- Confusing '=+' with '+=' operator
- Assuming print needs no parentheses in Python 3
- Thinking keys are misspelled
{'Alice': 300, 'Bob': 700}. Which code correctly returns a new dictionary with user names and their share percentages rounded to 2 decimals?Solution
Step 1: Calculate total shares correctly
Sum the values of the shares dictionary to get total tokens contributed.Step 2: Compute percentage per user and round
Use dictionary comprehension to divide each user's amount by total, multiply by 100, and round to 2 decimals.Final Answer:
def calc_shares(shares): total = sum(shares.values()) return {user: round(amount / total * 100, 2) for user, amount in shares.items()} -> Option DQuick Check:
Sum values, divide each, round = correct share % [OK]
- Summing keys instead of values
- Returning list instead of dictionary
- Using length instead of sum for total
