Liquidity pools help people trade cryptocurrencies easily without needing a middleman. They keep enough tokens ready so trades happen fast and smoothly.
Liquidity pools in Blockchain / Solidity
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Blockchain / Solidity
function addLiquidity(tokenA, tokenB, amountA, amountB) {
// User adds tokens to the pool
pool[tokenA] += amountA;
pool[tokenB] += amountB;
// User receives pool tokens representing their share
userPoolTokens += calculateShare(amountA, amountB);
}This is a simplified example of adding tokens to a liquidity pool.
In real blockchain code, smart contracts handle these actions securely.
Examples
Blockchain / Solidity
addLiquidity('ETH', 'DAI', 10, 20000);
Blockchain / Solidity
swap('ETH', 'DAI', 1);
Blockchain / Solidity
removeLiquidity('ETH', 'DAI', userPoolTokens);
Sample Program
This program simulates a simple liquidity pool where users add ETH and DAI tokens in the correct ratio. It tracks each user's share of the pool.
Blockchain / Solidity
class LiquidityPool { constructor() { this.pool = { ETH: 0, DAI: 0 }; this.totalShares = 0; this.shares = new Map(); } addLiquidity(user, ethAmount, daiAmount) { if (this.totalShares === 0) { this.pool.ETH += ethAmount; this.pool.DAI += daiAmount; this.totalShares = ethAmount; this.shares.set(user, ethAmount); return ethAmount; } else { const ethShare = (ethAmount * this.totalShares) / this.pool.ETH; const daiShare = (daiAmount * this.totalShares) / this.pool.DAI; if (ethShare !== daiShare) { throw new Error('Must provide tokens in correct ratio'); } this.pool.ETH += ethAmount; this.pool.DAI += daiAmount; this.totalShares += ethShare; this.shares.set(user, (this.shares.get(user) || 0) + ethShare); return ethShare; } } getPool() { return this.pool; } getUserShares(user) { return this.shares.get(user) || 0; } } const pool = new LiquidityPool(); // User Alice adds 10 ETH and 20000 DAI const aliceShares = pool.addLiquidity('Alice', 10, 20000); // User Bob adds 5 ETH and 10000 DAI const bobShares = pool.addLiquidity('Bob', 5, 10000); console.log('Pool balances:', pool.getPool()); console.log('Alice shares:', aliceShares); console.log('Bob shares:', bobShares); console.log('Alice total shares:', pool.getUserShares('Alice')); console.log('Bob total shares:', pool.getUserShares('Bob'));
Important Notes
Liquidity pools require users to add tokens in the right ratio to keep prices stable.
Users earn fees from trades that happen using their liquidity.
Smart contracts manage pools securely on the blockchain.
Summary
Liquidity pools let users trade tokens without a middleman.
Users add tokens to pools and get shares representing their part.
Pools keep token ratios balanced to set prices automatically.
Practice
1. What is the main purpose of a liquidity pool in blockchain?
easy
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]
Hint: Liquidity pools remove middlemen in token trading [OK]
Common Mistakes:
- Confusing liquidity pools with token creation
- Thinking liquidity pools mine blocks
- Assuming liquidity pools store passwords
2. Which of the following is the correct way to represent a liquidity pool share in code?
easy
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]
Hint: Use dictionaries to map users to their shares [OK]
Common Mistakes:
- Using lists instead of dictionaries for key-value pairs
- Incorrect tuple ordering for mapping
- Using string instead of structured data
3. Given this Python code simulating a liquidity pool token ratio update:
What is the printed output?
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?
medium
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]
Hint: Add tokens first, then divide for ratio [OK]
Common Mistakes:
- Dividing before adding new tokens
- Rounding incorrectly
- Mixing tokenA and tokenB values
4. This code snippet tries to update a liquidity pool but has a bug:
What is the bug?
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?
medium
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]
Hint: Use '+=' to add and assign in one step [OK]
Common Mistakes:
- Confusing '=+' with '+=' operator
- Assuming print needs no parentheses in Python 3
- Thinking keys are misspelled
5. You want to write a function that calculates each user's share percentage in a liquidity pool given a dictionary of shares like
{'Alice': 300, 'Bob': 700}. Which code correctly returns a new dictionary with user names and their share percentages rounded to 2 decimals?hard
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]
Hint: Sum values, then divide each share by total and round [OK]
Common Mistakes:
- Summing keys instead of values
- Returning list instead of dictionary
- Using length instead of sum for total
