Smart Contracts & DeFi
300Hours Learn Lab Curriculum Reading | Topic: CAIA1_DIGITAL | Qualification: CAIA LEVEL1
# Smart Contracts & DeFi While first-generation blockchains focused primarily on transferring native value peer-to-peer, programmable blockchains expanded distributed ledgers into open financial infrastructure. **Smart contracts** embed deterministic business logic directly on-chain, enabling **Decentralized Finance (DeFi)**-an interconnected ecosystem of lending pools, decentralized exchanges, derivatives, and asset-management protocols operating 24/7 without banks, brokers, or clearinghouses. --- ## 1. Smart Contracts: Deterministic Code as Financial Infrastructure First conceptualized by computer scientist Nick Szabo in 1994 and popularized by Ethereum in 2015, a **smart contract** is a self-executing software program stored at a specific blockchain address. Once deployed, the contract holds digital assets and automatically executes state transitions whenever predetermined conditions are satisfied by incoming signed transactions. ### Core Properties of Smart Contracts - **Deterministic Execution**: Every validator node running the contract bytecode on identical inputs must arrive at the exact same output state; otherwise consensus breaks. - **Immutability & Transparency**: Open-source bytecode deployed on a public ledger can be audited by any counterparty prior to interacting with it, reducing bilateral agency risk-though immutability also means coding bugs cannot easily be patched unless upgradeable proxy patterns are configured. - **Composability ("Money Legos")**: Because smart contracts expose standardized public interfaces (such as ERC-20 tokens or ERC-4626 vaults), one protocol can programmatically call another within a single transaction. A yield aggregator can borrow stablecoins on one protocol, swap them on a decentralized exchange, and deposit liquidity into a third protocol atomically. - **Gas Metering**: To prevent malicious or accidental infinite loops from halting the global network (the computer-science halting problem), every computational opcode consumes **gas** paid by the transaction initiator; if gas runs out, execution reverts cleanly while fees remain paid to validators. ### The Oracle Problem Because blockchains must remain deterministic closed systems, smart contracts cannot natively query off-chain web APIs to learn equity prices, foreign-exchange rates, LIBOR/SOFR benchmarks, or hurricane wind speeds. The challenge of reliably importing external real-world data onto a trust-minimized blockchain is known as the **Oracle Problem**. - **Centralized Oracles**: Rely on a single data publisher-fast and cheap, yet reintroduce a single point of failure and manipulation risk. - **Decentralized Oracle Networks (DONs, e.g., Chainlink)**: Aggregate prices from multiple independent data providers and node operators using median filtering and economic staking incentives. - **On-Chain TWAP Oracles**: Time-Weighted Average Price feeds computed across multiple blocks inside a decentralized exchange resist single-block manipulation, whereas naive reliance on an instantaneous spot pool price exposes protocols to **flash-loan oracle manipulation attacks**. --- ## 2. The Modular DeFi Architecture DeFi replicates traditional financial primitives across five composable layers, replacing legal balance sheets with transparent on-chain liquidity pools. ```mermaid flowchart TD L1[Layer 1 Settlement: Ethereum, Solana, Bitcoin]:::blue --> L2[Layer 2 Asset Standards: Native Coins, ERC-20, Stablecoins, RWAs]:::green L2 --> L3[Layer 3 Protocol Primitives]:::purple L3 --> DEX[Decentralized Exchanges: AMMs & On-Chain Order Books]:::turquoise L3 --> LEND[Lending & Borrowing: Overcollateralized Money Markets]:::yellow L3 --> DERIV[Derivatives & Structured Vaults: Perpetuals, Options, Yield]:::lime DEX --> L4[Layer 4 Aggregators & Wallet Interfaces]:::blue LEND --> L4 DERIV --> L4 L4 --> RISK[Core DeFi Risks: Smart Contract Bugs, Oracle Exploits, MEV, Cascading Liquidations]:::red classDef blue fill:#eff6ff,stroke:#1976D2,color:#1e293b classDef green fill:#dcfce7,stroke:#009966,color:#1e293b classDef purple fill:#f5f3ff,stroke:#8A759D,color:#1e293b classDef turquoise fill:#ecfdf5,stroke:#53A97D,color:#1e293b classDef yellow fill:#fffbeb,stroke:#FFA300,color:#1e293b classDef lime fill:#f7fee7,stroke:#9E9D24,color:#1e293b classDef red fill:#fef2f2,stroke:#A11E3D,color:#1e293b ``` --- ## 3. Automated Market Makers (AMMs) and Impermanent Loss Traditional exchanges use a **Central Limit Order Book (CLOB)** matching specific buyer and seller limit orders. On early blockchains with high gas costs and 12-second block times, posting and canceling thousands of market-maker quotes on-chain was uneconomical. DeFi solved this bottleneck with **Automated Market Makers (AMMs)**-smart-contract liquidity pools funded by passive **Liquidity Providers (LPs)** that quote prices algorithmically. ### Constant Product Market Maker (CPMM) Mechanics The canonical AMM design (pioneered by Uniswap v2) maintains a **constant product invariant** between reserves $x$ of Token A and reserves $y$ of Token B: $x \cdot y = k$ Ignoring swap fees for intuition, the marginal spot price of Token A quoted in Token B is $P_A = y / x$. When a trader sells $\Delta x$ units of Token A into the pool (after deducting the pool fee $f$, e.g., $0.30\%$, leaving $\Delta x_{\text{eff}} = \Delta x (1 - f)$), the pool returns $\Delta y$ units of Token B such that $(x + \Delta x_{\text{eff}})(y - \Delta y) = k$: $\Delta y = y - \frac{k}{x + \Delta x_{\text{eff}}} = \frac{y \cdot \Delta x_{\text{eff}}}{x + \Delta x_{\text{eff}}}$ Larger trades relative to pool depth experience convex **price impact (slippage)**-the pool can never run completely out of either asset because price asymptotically approaches infinity as reserves approach zero. Arbitrageurs continuously trade against the pool whenever its internal price diverges from external markets, keeping the AMM synchronized with global prices while paying swap fees to LPs. ### Impermanent Loss (Divergence Loss) Because arbitrageurs buy the appreciating asset from the AMM pool at slightly stale prices and replenish the pool with the depreciating asset, an LP always ends up holding *less* of the winning token and *more* of the lagging token than if they had simply held the initial 50/50 portfolio outside the pool (**HODL**). If the price ratio of Token A relative to Token B moves by a factor $r = P_1 / P_0$, the percentage underperformance of a full-range 50/50 CPMM position relative to holding (excluding earned fees) is **Impermanent Loss ($\text{IL}$)**: $\text{IL}(r) = \frac{2\sqrt{r}}{1 + r} - 1$ Notice that $\text{IL}(r) \le 0$ for *any* price divergence $r \neq 1$, whether prices rise or fall, and becomes **permanent** if the LP withdraws liquidity before the price ratio reverts to $r = 1$. Newer designs-such as **concentrated liquidity** (Uniswap v3, where LPs focus capital within custom price bands $[P_{\min}, P_{\max}]$) and **StableSwap** invariants (Curve, flattening curvature near a 1:1 peg)-boost capital efficiency and cut trader slippage, though concentrated ranges also amplify impermanent loss if prices exit the chosen band. --- ## 4. Decentralized Lending, Health Factors, and Flash Loans ### Overcollateralized Money Markets Because public blockchains are pseudonymous and lack credit bureaus or wage-garnishment recourse, DeFi lending protocols (such as Aave and Compound) operate as **overcollateralized pooled money markets**: - Depositors supply assets to a shared liquidity pool and receive interest-bearing receipt tokens (e.g., `aUSDC`). - Borrowers lock volatile collateral (e.g., ETH or WBTC) and draw loans up to a maximum **Loan-to-Value (LTV)** ratio (say $75\%$). - Borrowing and lending rates adjust algorithmically based on the pool's **utilization rate** $U = \text{Total Borrowed} / \text{Total Supplied}$, using a **kinked interest-rate curve** that raises rates steeply above an optimal utilization kink (e.g., $U^* = 80\%$ or $90\%$) to attract fresh deposits and preserve withdrawal liquidity. - **Health Factor ($HF$) & Automated Liquidations**: Protocol solvency is policed via the borrower's Health Factor: $HF = \frac{\text{Collateral Value} \times \text{Liquidation Threshold}}{\text{Total Debt Value}}$ Whenever $HF