Decentralized Finance (DeFi)
DEX, lending protocols, yield farming, liquidity pools, and DeFi risks.
Overview
DeFi recreates financial services on the blockchain.
DeFi Ecosystem
Architecture Diagram
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā DeFi Protocols ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā DEX ā Lending ā Derivatives ā
ā Uniswap ā Aave ā dYdX ā
ā Sushi ā Compound ā GMX ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā Stablecoins ā
ā USDC, DAI, USDT ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Automated Market Maker (AMM)
// Constant product formula: x * y = k
contract UniswapV2Pair {
uint112 private reserve0;
uint112 private reserve1;
function swap(uint amount0In, uint amount1Out) public {
require(amount0In > 0 || amount1Out > 0);
uint balance0Before = reserve0;
uint balance1Before = reserve1;
// Update reserves
if (amount0In > 0) reserve0 += amount0In;
if (amount1Out > 0) reserve1 -= amount1Out;
// Verify constant product
require(reserve0 * reserve1 >= balance0Before * balance1Before);
}
}
Liquidity Pools
# Liquidity calculation
def add_liquidity(token0_amount, token1_amount, reserve0, reserve1):
# Calculate optimal amounts
token1_optimal = token0_amount * reserve1 / reserve0
if token1_optimal <= token1_amount:
token1_desired = token1_optimal
else:
token0_optimal = token1_amount * reserve0 / reserve1
token0_desired = token0_optimal
# Calculate LP tokens
lp_tokens = min(
token0_desired * total_lp / reserve0,
token1_desired * total_lp / reserve1
)
return lp_tokens
Yield Farming
# APY calculation
def calculate_apy(reward_rate, price_token, tvl):
daily_rewards = reward_rate * price_token
annual_rewards = daily_rewards * 365
apy = annual_rewards / tvl * 100
return apy
DeFi Risks
| Risk | Description |
|---|---|
| Smart Contract | Code vulnerabilities |
| Impermanent Loss | LP value changes |
| Oracle | Price feed manipulation |
| Governance | Protocol attacks |
Practice
Build a simple DEX with liquidity pools.