Decentralized Finance (DeFi)


Foundations, history, and advantages of DeFi; blockchain as DeFi infrastructure; DeFi primitives (transactions, tokens, custody, supply adjustment, swaps, loans); and DeFi applications (lending, derivatives, tokenization).

Topics in this chapter

  • Introduction, History, Key Issues in DeFi, and Advantages over Traditional Approach
  • Blockchain as DeFi Infrastructure: Blockchain, Cryptocurrency, The Smart Contract Platform, Oracles, Stablecoins, Decentralized Applications
  • DeFi Primitives: Transactions, Fungible and Non-fungible Tokens, Custody, Supply Adjustment, Swap, Collateralized and Uncollateralized Loans
  • DeFi Applications: Credit/Lending, Decentralized Access, Derivatives, Tokenization

Foundations and Advantages of DeFi

Historical Evolution of DeFi

The intellectual foundations of decentralized finance (DeFi) trace back to the cypherpunk movement of the 1990s, which advocated for cryptographic privacy, digital cash, and resistance to institutional control. Three overlapping waves define DeFi's evolution. Wave 1 (2009): Bitcoin demonstrated peer-to-peer value transfer without a central ledger-keeper, but its scripting language was intentionally constrained. Wave 2 (2015): Ethereum introduced a Turing-complete virtual machine and stateful smart contracts, enabling programmable escrow, multi-signature custody, and token standards such as ERC-20. Wave 3 — "DeFi Summer" (2020): Rapid proliferation of lending markets (Compound, Aave), decentralized exchanges (Uniswap), and synthetic asset platforms (MakerDAO). Total value locked (TVL) grew from under 1billiontoover1 billion to over 15 billion, driven by yield farming incentives and the composability of protocols. Architecturally, a DeFi protocol can be represented as P=(S,T,G,O)\mathcal{P} = (\mathcal{S}, \mathcal{T}, \mathcal{G}, \mathcal{O}), where S\mathcal{S} is the on-chain state, T\mathcal{T} is the transition function encoded in the smart contract, G\mathcal{G} is the governance mechanism, and O\mathcal{O} is the set of external oracles.

Key Issues in DeFi

Smart Contract Vulnerabilities: A bug in a contract's logic can lead to irrevocable loss of user funds. The most infamous category, reentrancy attacks (as exploited in the 2016 DAO hack), arises when a contract's state is updated after an external call. The formal exploit incentive model: E[π]=psuccessVprofit(1psuccess)LpenaltyCattack\mathbb{E}[\pi] = p_{success} \cdot V_{profit} - (1 - p_{success}) \cdot L_{penalty} - C_{attack}. In DeFi, LpenaltyL_{penalty} is often near zero due to pseudonymity, making any positive expected value an attractive target. Oracle Dependence: Many protocols rely on external price feeds to trigger liquidations or calculate collateral ratios. A manipulated or stale price feed can enable an attacker to drain a lending market or mint unbacked tokens. Flash loan attacks have demonstrated how an adversary can temporarily skew a DEX-based oracle within a single atomic transaction. Scalability: Base-layer throughput on Ethereum is on the order of tens of TPS. Congestion drives gas fees to levels that exclude small-value users. Layer 2 solutions (rollups, sidechains) recover throughput at the cost of some "pure" DeFi properties. Composability as Systemic Risk: If a protocol integrates mm external components, the aggregate failure probability is P(failure)=1j=1m(1pj)P(\text{failure}) = 1 - \prod_{j=1}^{m}(1 - p_j). A single compromised primitive can cascade through the entire stack.

Advantages over Traditional Finance

The canonical economic rationale for financial intermediation rests on information asymmetry, delegated monitoring, and liquidity transformation. Under traditional finance, CTradFi=c0+i=1nci+μC_{\text{TradFi}} = c_0 + \sum_{i=1}^{n} c_i + \mu, where c0c_0 is fixed regulatory compliance cost, cic_i are variable intermediary costs, and μ\mu captures agency rent. Under DeFi, CDeFi=g(θ)+εC_{\text{DeFi}} = g(\theta) + \varepsilon, where g(θ)g(\theta) is the gas fee and ε\varepsilon is the protocol fee. The wedge ΔC=CTradFiCDeFi\Delta C = C_{\text{TradFi}} - C_{\text{DeFi}} is the source of DeFi's efficiency claim. DeFi offers: deterministic execution (smart contract code is public and immutable), atomic settlement (multiple operations bundled into a single transaction), transparency (all state changes recorded on-chain), permissionless access (no identity verification or geographic restrictions), censorship resistance (no central authority can freeze funds), 24/7 operation (settlement in block time), and open source verifiability (entire economic logic is auditable). However, DeFi also introduces unique risks: over-collateralization in lending protocols creates reflexive liquidation cascades absent in traditional banking, where deposit insurance and lender-of-last-resort facilities break the feedback loop.

Blockchain as DeFi Infrastructure

The Blockchain as a Trustless State Machine

At its core, a blockchain is a decentralized, append-only ledger maintained by a network of independent, economically incentivized nodes. In DeFi, the blockchain serves as a trustless state machine: participants can transact and execute code without relying on a central authority. Formally, the blockchain can be modelled as a deterministic state transition function T:S×TS\mathcal{T}: S \times T \rightarrow S, where SS is the set of all possible system states and TT is a set of valid transactions. Consensus protocols — PoW and PoS — ensure that all honest participants eventually agree on the canonical sequence of states. The economic significance is that blockchain converts the problem of trust in a counterparty into the problem of trust in a mechanism: once a transaction is finalized, reversal requires an attacker to expend resources exceeding the economic value at stake.

Cryptocurrency

The native cryptocurrency of a smart contract platform (e.g., ETH, SOL) serves three intertwined roles: (i) the numéraire in which gas fees are paid, (ii) the reward that incentivizes validators to honestly execute consensus, and (iii) a speculative asset whose price reflects the discounted present value of expected future network usage. Under a quantity-theoretic framing, the market capitalization MM satisfies M=E[t=1Πt(1+r)t]M = \mathbb{E}\left[\sum_{t=1}^{\infty} \frac{\Pi_t}{(1+r)^t}\right], where Πt\Pi_t denotes protocol cash flows and rr is the risk-adjusted discount rate. This valuation logic makes native tokens behave like equity in a decentralized platform.

The Smart Contract Platform

A smart contract CC can be modeled as a tuple (SC,M,δC)(S_C, \mathcal{M}, \delta_C), where SCS_C is persistent storage, M\mathcal{M} is the set of callable methods, and δC:SC×M×msgSC\delta_C: S_C \times \mathcal{M} \times \text{msg} \to S_C' is the state-transition logic. The economic power of smart contracts derives from their role as commitment devices: because the code is immutable (or upgradeable only under pre-specified governance rules) and execution is automatic, parties can write contracts that are credibly self-enforcing. This eliminates the hold-up problem that plagues incomplete contracts in traditional finance. Gas solves the halting problem by metering computation: each primitive operation oio_i is priced at a fixed gas cost gig_i. The total fee is F=pgasmin(Gmax,i=1kgi)F = p_{\text{gas}} \cdot \min(G_{\max}, \sum_{i=1}^{k} g_i). Under EIP-1559, the base fee adjusts: bt+1=bt(1+GtGG18)b_{t+1} = b_t \cdot (1 + \frac{G_t - G^*}{G^*} \cdot \frac{1}{8}), creating a quasi-automatic pricing rule that dampens congestion while burning the base fee.

Oracles

Smart contracts are causally closed: they can observe only on-chain state. An oracle is a mechanism that imports off-chain data into the blockchain. Robust oracle designs aggregate reports from a decentralized set of nodes, typically using a robust statistic such as the median: p^=median{p1,p2,,pn}\hat{p} = \text{median}\{p_1, p_2, \dots, p_n\}, which tolerates up to (n1)/2\lfloor (n-1)/2 \rfloor Byzantine reporters. The economic security requires that the cost of corruption exceeds the profit from corruption: Cattack>PattackjDTVLjεC_{\text{attack}} > P_{\text{attack}} \equiv \sum_{j \in \mathcal{D}} \text{TVL}_j \cdot \varepsilon, where D\mathcal{D} is the set of dependent protocols and ε\varepsilon is the exploitable price deviation.

Stablecoins

Stablecoins are tokens designed to maintain a stable value relative to a reference asset — typically the U.S. dollar. They are the lubricant of DeFi, providing a low-risk medium for lending pools, derivatives, and liquidity provision. Three canonical designs exist: Fiat-collateralized (USDC, USDT) — a centralized issuer holds reserves RNR \geq N, with trust placed in the issuer and its auditors. Crypto-collateralized (DAI) — users lock volatile crypto assets into a vault and mint DAI up to a collateralization ratio r>100%r > 100\% (typically 150%+). The stability fee α\alpha controls supply: when DAI trades above 1,1, \alphaisloweredtoencourageminting;whenbelowis lowered to encourage minting; when below1,, \alpha$ is raised to encourage repayment. Algorithmic — supply adjusts endogenically via seigniorage-style mechanisms. History (the 2022 collapse of UST) has shown these designs to be fragile under adverse reflexivity, since the backing asset is often endogenous to the stablecoin's own demand.

Decentralized Applications (dApps)

dApps are applications whose backend logic runs on a decentralized peer-to-peer network rather than centralized servers. The frontend can be a traditional web/mobile interface, but the smart contracts provide the trustless backend. dApps combine the four infrastructure components: blockchain for state, cryptocurrency for value transfer, smart contracts for logic, and oracles for external data. The composability of dApps — often described as "money legos" — means that novel financial products can be built by stacking existing protocols.

DeFi Primitives

Transactions and Atomicity

The atomic unit of interaction in any smart-contract-enabled blockchain is the transaction: a cryptographically signed instruction originating from an externally owned account (EOA). A defining property is atomicity: a transaction either commits all of its intermediate state changes or reverts them entirely. Formally, if a transaction TT invokes a sequence of sub-calls (c1,c2,,cn)(c_1, c_2, \ldots, c_n), the post-state is Σ=δnδ1(Σ)\Sigma' = \delta_n \circ \cdots \circ \delta_1(\Sigma) if all succeed, or Σ\Sigma otherwise. Atomicity is the bedrock of composability: heterogeneous protocols — lending, swapping, derivatives — can be chained into a single transaction without counterparty risk between intermediate steps.

Fungible and Non-Fungible Tokens

Fungible Tokens (ERC-20): Standard interface — totalSupply(), balanceOf(address), transfer, approve, transferFrom. Each unit is interchangeable. Functional classes include equity tokens (residual claims on protocol cash flows), utility tokens (access rights to a service), and governance tokens (voting rights over protocol parameters). Non-Fungible Tokens (ERC-721): Each unit carries a unique identifier tokenId\text{tokenId} and associated metadata. Used to represent positions in lending protocols (Uniswap v3 liquidity positions), insurance policies, or ownership of real-world assets. The ERC-1155 multi-token standard unifies both paradigms: a single contract manages many token types, each fungible or non-fungible, reducing deployment and gas costs.

Custody

DeFi replaces custodial intermediaries with non-custodial (self-custodial) control. Ownership of an asset is identified with knowledge of a private key kk such that verify(pub(k),σ,m)=1\text{verify}(\text{pub}(k), \sigma, m) = 1. Self-custody eliminates principal–agent risk between user and custodian but concentrates key-management risk on the user. Loss of kk implies irrecoverable loss; compromise of kk implies theft without recourse. Hybrid solutions include multisignature wallets requiring mm-of-nn keys, smart-contract wallets enabling social recovery and daily limits, and MPC wallets where the private key is sharded across multiple secure enclaves.

Supply Adjustment

Mint creates new tokens and credits them to an address (e.g., MakerDAO's DAI minted against locked ETH). Burn destroys tokens, permanently removing them from circulation (e.g., Ethereum's EIP-1559 burns a portion of transaction fees). These can be combined into a bonding curve — a deterministic pricing mechanism that mints and burns tokens along a continuous curve. Let R=f(S)R = f(S) where SS is total token supply and RR is reserve asset balance. The instantaneous marginal price is P(S)=dRdSP(S) = \frac{dR}{dS}. Commonly, f(S)=aSbf(S) = a S^b with b>1b > 1 (e.g., b=2b = 2 gives linear price P(S)=2aSP(S) = 2aS).

Swap: Automated Market Makers

The transformative innovation in DeFi is the Automated Market Maker (AMM). An AMM is a smart contract that holds reserves of two tokens and algorithmically quotes exchange prices based on a deterministic invariant. The classic constant-product market maker (Uniswap v2) maintains xy=kx \cdot y = k, where xx and yy are reserves. A trader swapping Δx\Delta x for YY receives Δy=ykx+Δx=yΔxx+Δx\Delta y = y - \frac{k}{x + \Delta x} = \frac{y \cdot \Delta x}{x + \Delta x}. The effective price peff(Δx)=x+Δxyp_{\text{eff}}(\Delta x) = \frac{x + \Delta x}{y} exceeds the spot price p0=x/yp_0 = x/y; the difference is slippage (price impact). Impermanent Loss (IL): When the external price moves from p0p_0 to p1p_1, the LP's impermanent loss ratio is IL(r)=2r1+r1,rp1p0\text{IL}(r) = \frac{2\sqrt{r}}{1 + r} - 1, \quad r \equiv \frac{p_1}{p_0}. IL(r)0\text{IL}(r) \leq 0 with equality only at r=1r = 1; the loss is symmetric in log-price and convex, reflecting the fact that the LP is structurally short volatility.

Collateralized and Uncollateralized Loans

Collateralized Loans: The solvency condition requires CαDC \cdot \alpha \ge D, where CC is collateral value, DD is debt, and α\alpha is the collateral factor. If collateral value depreciates such that Cβ<DC \cdot \beta < D (where β\beta is the liquidation threshold), the position becomes undercollateralized and a liquidation event is triggered automatically, allowing third-party arbitrageurs to repay a portion of the debt in exchange for the collateral at a discounted liquidation penalty. Interest Rate Model: The utilization rate U=B/LU = B/L (total borrowed / total liquidity). The borrow rate is rb(U)=r_b(U) = \begin{cases} r_0 + m_1 U & U \le U_{opt} \ r_0 + m_1 U_{opt} + m_2 (U - U_{opt}) & U > U_{opt} \end{cases} , where m2m1m_2 \gg m_1. When liquidity is abundant, rates rise gently; when scarce, the steep slope aggressively incentivizes repayments and new deposits. Flash Loans (Uncollateralized): A loan that must be originated and repaid within a single transaction. The EVM enforces VendVstart+feesV_{end} \ge V_{start} + \text{fees}; if not met, the entire transaction reverts. This eliminates the need for collateral and enables risk-free arbitrage, liquidations, and refinancing — all within one atomic operation.

DeFi Applications

Credit/Lending

Decentralized lending protocols (Compound, Aave) use a peer-to-pool model. Liquidity providers deposit assets into shared smart contract pools; borrowers draw from these pools against posted collateral. Key mechanisms include: Overcollateralization (CαDC \cdot \alpha \ge D) to ensure solvency without credit scoring; Algorithmic interest rates (utilization-based models dynamically balancing supply and demand); Automatic liquidations (third-party arbitrageurs repay debt in exchange for discounted collateral); and Lending tokens (aTokens in Aave or cTokens in Compound that accrue interest and represent the depositor's share). The flash loan innovation — an uncollateralized loan that must be originated and repaid within a single transaction — demonstrates how atomicity and default-prevention can relax collateral requirements for arbitrage, liquidations, and refinancing, reshaping capital efficiency.

Decentralized Access

DeFi provides permissionless access to financial services: no identity verification, no minimum balance, no geographic restrictions. Any individual with an internet connection and a self-custodied wallet can interact with a smart contract. This is particularly valuable for the roughly 1.4 billion unbanked adults globally. However, the collateral requirement (CαLC \geq \alpha L) remains a binding constraint for those without initial capital — the DeFi inclusion paradox. Moreover, gas costs on Ethereum can exceed $50 during network congestion, rendering microloans uneconomical.

Derivatives

Synthetic Assets are blockchain-based tokens engineered to replicate the price action of an underlying reference asset without requiring the protocol to hold the actual asset. The primary challenge is maintaining the peg. A Funding Rate mechanism anchors the synthetic token price PSP_S to the oracle-reported spot price PXP_X: ft=k(PS,tPX,tPX,t)f_t = k \left(\frac{P_{S,t} - P_{X,t}}{P_{X,t}}\right). If PS>PXP_S > P_X, the funding rate is positive, and long position holders pay short position holders, creating an arbitrage incentive that drives PSP_S back toward PXP_X. Perpetual Futures (e.g., dYdX, GMX) use a funding rate mechanism to ensure the perpetual contract's price stays anchored to the spot index. Virtual Automated Market Makers (vAMMs) use virtual liquidity rather than real asset reserves. The price impact is calculated algorithmically, but no actual assets are swapped in the AMM. Instead, the vAMM acts as a pricing oracle and counterparty while actual collateral is locked in a separate vault, enabling leveraged trading with high capital efficiency.

Real-World Asset (RWA) Tokenization

Real-World Asset (RWA) Tokenization represents the convergence of Traditional Finance (TradFi) and DeFi, involving the issuance of digital tokens that represent legal ownership or a claim on off-chain physical or financial assets. This process unlocks the illiquidity premium embedded in assets such as real estate, private credit, and fine art. Structurally, an off-chain legal entity (e.g., a Special Purpose Vehicle) holds the asset, while a smart contract issues tokens representing fractional beneficial ownership. The reduction in the illiquidity discount λ\lambda increases the present value of the asset: Vtokenized=t=1TCFt(r+λtokenized)tV_{tokenized} = \sum_{t=1}^{T} \frac{CF_t}{(r + \lambda_{tokenized})^t} where λtokenized<λtraditional\lambda_{tokenized} < \lambda_{traditional}. MakerDAO's RWA vaults gained traction even during the bear market, generating annualized revenues nearing $150 million by allocating credit to traditional asset managers. Advantages include: (i) DeFi growth by importing trillions of dollars of illiquid TradFi value, (ii) enhanced liquidity via fractional ownership, (iii) transparency through immutable ledger records, and (iv) efficiency in settlement and lifecycle management. Risks lie in centralized intermediary layers, regulatory uncertainty, and oracle reliability for asset pricing.