Core DeFi Primitives - The Building Blocks | DeFi Fundamentals on XRPL | XRP Academy - XRP Academy
3 free lessons remaining this month

Free preview access resets monthly

Upgrade for Unlimited
Skip to main content
beginner60 min

Core DeFi Primitives - The Building Blocks

Learning Objectives

Explain the six core DeFi primitives and articulate the specific problem each solves

Understand the mechanics of order book DEXs versus AMMs, including the constant product formula

Describe how lending protocols work including overcollateralization, interest rate models, and liquidation mechanics

Differentiate stablecoin types and assess the risk profile of each approach

Recognize how primitives compose to create complex DeFi applications—and the systemic risks this creates

Traditional finance has building blocks too: checking accounts, savings accounts, loans, stocks, bonds, derivatives. Each serves a specific function. Combined, they create the financial system we know.

  • Solves a specific problem
  • Can function independently
  • Can combine with other primitives
  • Has a specific risk profile

The "composability" of DeFi primitives is often called "money Legos"—you can snap them together in novel ways. A yield aggregator might deposit your stablecoins into a lending protocol, use the receipt tokens as collateral for a loan, swap the borrowed assets on a DEX, and deposit the result into a liquidity pool—all in one transaction.

This composability enables innovation impossible in traditional finance. It also creates hidden dependencies and systemic risks. Understanding each primitive—what it does, how it works, what can go wrong—is foundational to navigating DeFi safely.


  • Hold your assets safely
  • Match buyers with sellers fairly
  • Execute trades honestly
  • Not front-run your orders
  • Remain solvent

FTX demonstrated what happens when centralized exchanges violate that trust.

The Solution: Decentralized exchanges enable trading without trusting a central party. You maintain custody of your assets until the moment of trade, and the trade settles atomically on-chain.

The traditional model: buyers and sellers post orders specifying price and quantity. A matching engine pairs compatible orders.

ORDER BOOK MECHANICS

Buy Orders (Bids): Sell Orders (Asks):
$99.00 - 100 units $101.00 - 50 units
$98.50 - 200 units $101.50 - 75 units
$98.00 - 150 units $102.00 - 100 units

Spread: $101.00 - $99.00 = $2.00

  • Market order: Pay $101.00 (best ask)
  • Limit order at $99.50: Wait for seller
  • Market order: Receive $99.00 (best bid)
  • Limit order at $100.50: Wait for buyer
  • Orders stored on-ledger
  • Matching happens during consensus
  • Partial fills supported
  • Auto-bridging through XRP for better rates
  • Price discovery through supply/demand
  • Large orders can be filled without moving price (if liquidity exists)
  • Professional traders can provide tight spreads
  • More capital efficient for liquid markets
  • Requires active market makers
  • Illiquid pairs have wide spreads
  • Order management complexity
  • Can be front-run if order flow visible

The revolutionary alternative: instead of matching buyers and sellers, use a mathematical formula and liquidity pools.

AMM BASIC CONCEPT

Traditional Order Book:
Buyer ←→ Exchange ←→ Seller
(Exchange matches orders)

Automated Market Maker:
Trader ←→ Liquidity Pool ←→ Trader
(Formula determines price)

The pool holds both assets:
Pool: 1,000 ETH + 2,000,000 USDC
Implied price: 2,000,000 / 1,000 = $2,000/ETH
```

The Constant Product Formula (x * y = k)

The most common AMM model, pioneered by Uniswap:

CONSTANT PRODUCT EXPLAINED

Pool state: x ETH * y USDC = k (constant)
Example: 1,000 ETH * 2,000,000 USDC = 2,000,000,000 (k)

- Pool must maintain k = 2,000,000,000
- New ETH in pool: 1,000 - 10 = 990 ETH
- Required USDC: 2,000,000,000 / 990 = 2,020,202 USDC
- You pay: 2,020,202 - 2,000,000 = 20,202 USDC
- Effective price: 20,202 / 10 = $2,020.20/ETH

Note: Price moved from $2,000 to $2,020.20
Larger trades = more price impact (slippage)

Why This Works:

AMM INCENTIVE STRUCTURE

Liquidity Providers (LPs):
├── Deposit equal value of both assets
├── Receive LP tokens representing share
├── Earn trading fees (0.3% typical)
├── Accept impermanent loss risk

Traders:
├── Trade against the pool anytime
├── Pay fees to LPs
├── Experience slippage on large trades
├── No counterparty needed

Arbitrageurs:
├── Keep AMM prices aligned with market
├── Buy when AMM price < market price
├── Sell when AMM price > market price
├── Essential for price accuracy
  • Always available (no need for counterparty)

  • Anyone can provide liquidity

  • Simple to understand and use

  • Works for any token pair

  • Impermanent loss for LPs

  • Capital inefficient (full range liquidity)

  • Slippage on large trades

  • Subject to sandwich attacks

DEX TRACK RECORD

Successes:
✓ Uniswap: $2T+ cumulative volume, never hacked
✓ XRPL DEX: 12+ years operation, no major exploit
✓ Curve: Dominant for stablecoin swaps
✓ Genuine permissionless trading achieved

Failures/Issues:
✗ Low liquidity pairs: massive slippage
✗ MEV exploitation: sandwich attacks extract value
✗ Some DEX frontends compromised (not protocols)
✗ Regulatory pressure on some DEXs
```

The Honest Assessment: DEXs work. They've processed trillions in volume and demonstrated that permissionless trading is possible. They're one of DeFi's clearest successes. However, they're not perfect—MEV, slippage, and liquidity fragmentation remain real issues.


  • Credit checks
  • Income verification
  • Applications and approval
  • Specific collateral types accepted
  • Geographic/legal restrictions

The Solution: DeFi lending enables instant, permissionless loans using crypto as collateral. No credit check—the collateral speaks for itself.

DeFi LENDING MECHANICS

Step 1: Lenders deposit assets
├── Deposit 10,000 USDC into Aave
├── Receive aUSDC tokens (receipt)
├── Earn interest from borrowers
└── Can withdraw anytime (if liquidity exists)

Step 2: Borrowers provide collateral
├── Deposit 5 ETH as collateral ($10,000 value)
├── Collateral locked in protocol
├── Can borrow against it
└── Must maintain collateral ratio

Step 3: Borrowers take loans
├── Borrow up to 80% of collateral value
├── 5 ETH ($10,000) → Can borrow $8,000
├── Pay interest (variable rate)
└── No approval, no credit check

Step 4: Repayment or liquidation
├── Repay loan + interest → Retrieve collateral
├── OR: Collateral value drops
├── If collateral ratio falls below threshold
└── Liquidation: Collateral sold to repay debt
```

The key difference from traditional lending: DeFi loans are overcollateralized.

OVERCOLLATERALIZATION

Traditional loan:
├── Borrow $100,000 for house
├── House is collateral
├── Loan-to-Value (LTV): 80-95%
├── Bank trusts you'll pay (credit score)
└── If you don't pay: Foreclosure (slow, expensive)

DeFi loan:
├── Deposit $10,000 ETH as collateral
├── Can borrow: $5,000-8,000 (50-80% LTV)
├── Protocol doesn't care who you are
├── If collateral drops: Automatic liquidation
└── Instant, algorithmic, no trust required

Why overcollateralization?
├── No identity = No credit check
├── No legal recourse = Must be self-securing
├── Volatile collateral = Buffer needed
├── Instant liquidation = No collection process
└── Protocol must always remain solvent
```

DeFi lending uses algorithmic interest rates based on utilization:

UTILIZATION-BASED INTEREST RATES

Utilization = Borrowed / Deposited

Example pool: 10M USDC deposited, 6M borrowed
Utilization = 60%

Typical rate curve:
Utilization    Borrow Rate    Supply Rate
0-80%          2-10%          1-8%
80-90%         10-50%         8-40%
90-100%        50-200%+       40-160%+

Why it works:
├── Low utilization → Low rates → Encourages borrowing
├── High utilization → High rates → Encourages deposits
├── Very high utilization → Extreme rates → Emergency response
└── Self-balancing supply and demand

When collateral value drops, liquidation protects lenders:

LIQUIDATION EXAMPLE

Initial position:
├── Collateral: 5 ETH @ $2,000 = $10,000
├── Borrowed: 7,000 USDC
├── Health factor: $10,000 / $7,000 = 1.43
├── Liquidation threshold: 1.0 (example)
└── Status: Safe

ETH drops to $1,500:
├── Collateral: 5 ETH @ $1,500 = $7,500
├── Borrowed: 7,000 USDC + interest
├── Health factor: $7,500 / $7,100 = 1.06
└── Status: Getting close

ETH drops to $1,400:
├── Collateral: 5 ETH @ $1,400 = $7,000
├── Borrowed: 7,100 USDC
├── Health factor: $7,000 / $7,100 = 0.99
└── Status: LIQUIDATABLE

Liquidation process:
├── Liquidator repays portion of debt
├── Receives collateral at discount (5-15%)
├── Protocol remains solvent
├── Borrower loses collateral
└── Happens automatically, instantly
LENDING PROTOCOL ASSESSMENT

Successes:
✓ Aave: $10B+ TVL, functional liquidations
✓ Compound: Pioneer, generally works
✓ Billions borrowed and repaid
✓ Model has proven viable

Failures/Issues:
✗ Oracle manipulation attacks (some protocols)
✗ Illiquid collateral = bad debt (some cases)
✗ Governance attacks (Compound incident)
✗ Cascading liquidations in crashes

Key insight:
The model works for liquid, overcollateralized loans.
Problems arise with exotic collateral, low liquidity,
or attempts to reduce collateralization requirements.
```


  • Pricing goods/services
  • Storing value short-term
  • DeFi strategies (hard to plan with moving target)
  • Paying salaries/expenses

The Solution: Tokens designed to maintain stable value (usually $1 USD).

STABLECOIN TAXONOMY
  1. FIAT-BACKED (Custodial)
  1. CRYPTO-BACKED (Overcollateralized)
  1. ALGORITHMIC (Uncollateralized)
HOW FIAT-BACKED STABLECOINS WORK
  1. You send $1,000 to Circle
  2. Circle deposits in regulated bank
  3. Circle mints 1,000 USDC to your wallet
  4. You can use USDC in DeFi
  5. Redemption: Send USDC back, receive $1,000

Reserve composition (varies):
├── Cash in bank accounts
├── Short-term Treasury bills
├── Money market funds
├── Sometimes: Commercial paper (riskier)
└── Attested monthly by accounting firms

What can go wrong:
├── Bank holding reserves fails (SVB scare)
├── Issuer commits fraud (Tether concerns)
├── Regulatory seizure
├── Redemption gate during crisis
└── Loss of banking relationships
```

RLUSD (Ripple's stablecoin):

RLUSD SPECIFICS

Issuer: Ripple (NYDFS regulated)
Backing: USD and short-term Treasuries
Chains: XRPL and Ethereum
Attestation: Monthly reserve reports

Significance for XRPL DeFi:
├── First regulated stablecoin native to XRPL
├── Enables stable trading pairs
├── Institutional-grade credibility
├── Required for serious DeFi ecosystem
└── Still small vs USDC/USDT
HOW DAI WORKS (MakerDAO)
  1. Deposit $150 ETH into Maker Vault
  2. Borrow up to $100 DAI against it
  3. Use DAI in DeFi
  4. Repay DAI + stability fee to retrieve ETH
  5. If ETH drops, vault liquidated

Why it works:
├── Always more collateral than debt
├── Liquidations maintain solvency
├── Decentralized (no single issuer)
├── Censorship resistant (in theory)
└── Survives without trusted custodian

Complications:
├── Capital inefficient (need 150%+ collateral)
├── Liquidation risk for vault owners
├── Complex governance
├── Still has centralized collateral (USDC in reserves)
└── Less simple than fiat-backed
```

WHY ALGORITHMIC STABLECOINS FAIL

The theory:
├── No collateral needed
├── Supply expands/contracts algorithmically
├── When above $1: Mint more (supply up, price down)
├── When below $1: Burn supply (supply down, price up)
└── Sounds elegant

The reality (Terra/UST):
├── Works in calm markets
├── Stress test: Large sell pressure
├── Algorithm mints companion token (LUNA)
├── LUNA price drops from dilution
├── Less value backing UST
├── More UST sold (bank run)
├── More LUNA minted
├── Death spiral to zero
└── $40B+ destroyed

Lesson:
Algorithmic stablecoins without substantial collateral
have a fundamental fragility. When confidence breaks,
the system cannot recover. Most have failed.
```

STABLECOIN TRACK RECORD

Proven reliable:
✓ USDC: Maintained peg through 2022-2023 chaos
✓ USDT: Controversial but functional for years
✓ DAI: Survived multiple market crashes
✓ RLUSD: Too new for track record, but regulated

Proven failures:
✗ UST (Terra): $40B death spiral
✗ IRON (Iron Finance): Bank run
✗ Many others: Various failures
✗ Pattern: Undercollateralized = fragile

For XRPL DeFi:
├── RLUSD: Best option (regulated, backed)
├── Other issued currencies: Check issuer reputation
├── No native algorithmic stables (probably good)
└── Stablecoin availability critical for DeFi growth
```


  • Monitoring many protocols
  • Moving funds between opportunities
  • Paying gas fees for each move
  • Compounding rewards frequently
  • Expertise across protocols

The Solution: Smart contracts that automatically optimize yield across protocols.

YIELD AGGREGATOR MECHANICS
  1. You deposit assets into aggregator
  2. Aggregator deploys to highest-yield opportunities
  3. Automatically compounds rewards
  4. Automatically rebalances as rates change
  5. You withdraw with accumulated yield

Example strategy:
├── Deposit USDC into Yearn vault
├── Yearn deposits to Aave (earning 5%)
├── Monitors Compound (currently 4.5%)
├── If Compound rises to 6%, moves funds
├── Compounds interest daily
├── Deducts performance fee (10-20%)
└── You get optimized yield minus fees
```

COMMON YIELD AGGREGATOR STRATEGIES

Simple lending:
├── Move funds to highest-rate lending protocol
├── Low risk, low extra yield
└── Mainly saves gas and monitoring time

LP optimization:
├── Provide liquidity to AMM pools
├── Auto-compound trading fees
├── May add leverage
└── Higher yield, higher risk

Leveraged farming:
├── Deposit collateral
├── Borrow against it
├── Deposit borrowed funds
├── Repeat (loop)
├── Amplifies yield AND risk
└── Liquidation risk if market moves

Complex DeFi strategies:
├── Combine multiple protocols
├── Exploit temporary opportunities
├── May include governance token farming
└── Highest yield, highest complexity/risk
```

YIELD AGGREGATOR SPECIFIC RISKS

Smart contract risk (compounded):
├── Aggregator contract itself
├── Plus every protocol it interacts with
├── One vulnerability = potential total loss
└── More complex = more attack surface

Strategy risk:
├── Strategy may have flaws
├── Market conditions may change
├── Withdrawal timing matters
└── "Yield" might come from token emissions (not sustainable)

Governance risk:
├── Aggregator governance could make bad decisions
├── Strategy changes without notice
├── Fee increases
└── Migration risks

Dependency risk:
├── Relies on multiple protocols
├── Oracle dependencies
├── Liquidity dependencies
└── Correlated failures possible
```


  • Broker accounts
  • Approval processes
  • Counterparty trust
  • Geographic restrictions
  • Market hour limitations

The Solution: On-chain derivatives enabling leveraged exposure and hedging without intermediaries.

DeFi DERIVATIVE LANDSCAPE

Perpetual swaps:
├── Futures without expiration
├── Funding rate keeps price aligned
├── Up to 50x leverage (some platforms)
├── Examples: dYdX, GMX
└── Most popular DeFi derivative

Options:
├── Right to buy/sell at specific price
├── More complex than perpetuals
├── Examples: Dopex, Lyra
└── Still relatively small market

Synthetic assets:
├── Tokens tracking real-world prices
├── Stocks, commodities, forex
├── Oracle-dependent
├── Examples: Synthetix
└── Regulatory gray area
```

PERPETUAL SWAP MECHANICS

Basic concept:
├── Contract tracking asset price
├── No expiration date
├── Long or short with leverage
├── Funding rate balances longs/shorts
└── Margin/liquidation mechanics

Funding rate:
├── If more longs: Longs pay shorts
├── If more shorts: Shorts pay longs
├── Keeps perp price near spot price
├── Paid every 8 hours typically
└── Can be significant cost

Example:
├── BTC spot: $60,000
├── Open 10x long with $1,000 margin
├── Position size: $10,000
├── BTC rises 5%: +$500 (50% gain on margin)
├── BTC falls 5%: -$500 (50% loss on margin)
├── BTC falls 10%: Position liquidated
└── Leverage amplifies gains AND losses
```

DeFi DERIVATIVE RISKS

Oracle risk:
├── Price feeds determine profit/loss
├── Oracle manipulation = unfair liquidations
├── Flash crashes can liquidate good positions
└── Critical dependency

Liquidity risk:
├── Needs counterparty for every trade
├── Illiquid markets = wide spreads
├── Large positions hard to exit
└── Cascading liquidations possible

Smart contract risk:
├── Complex logic = more bugs
├── Leverage amplifies impact
├── Historical: Several exploits
└── Higher stakes = higher target

Regulatory risk:
├── Derivatives heavily regulated traditionally
├── DeFi derivatives = gray area
├── Enforcement actions possible
└── Uncertain legal status
```


COMPOSABILITY EXAMPLE: FLASH LOAN ARBITRAGE
  1. Borrow $10M USDC from Aave (flash loan, no collateral)
  2. Swap to ETH on Uniswap ($10M → 5,000 ETH)
  3. Swap ETH to USDC on Sushiswap (5,000 ETH → $10,050,000)
  4. Repay $10M + fee to Aave
  5. Keep $50,000 - fee profit

Why this matters:
├── Impossible in traditional finance
├── No capital required
├── Atomic: Either all happens or none
├── Keeps prices aligned across DEXs
└── Genuinely novel financial primitive
```

COMPOSABILITY RISK: HIDDEN DEPENDENCIES

Scenario:
├── Protocol A uses Protocol B's price oracle
├── Protocol B uses Protocol C's liquidity
├── Protocol C uses Protocol A's stablecoin
└── Circular dependency

If any link breaks:
├── Protocol C liquidity crisis
├── Protocol B price oracle fails
├── Protocol A stablecoin depegs
├── All three collapse together
└── Users in any protocol affected

Real example: Terra/Luna + Anchor
├── UST (stablecoin) backed by LUNA
├── Anchor (lending) offered 20% on UST
├── UST demand propped up LUNA price
├── LUNA price backed UST
├── Circular: When one broke, both collapsed
└── $40B+ destroyed
```

COMPOSABILITY RISK CHECKLIST

For any DeFi position, ask:
□ What protocols does this depend on?
□ What oracles provide price data?
□ Where does the yield actually come from?
□ What happens if any dependency fails?
□ Are there circular dependencies?
□ How correlated are the failure modes?

Red flags:
├── Can't identify yield source
├── Depends on many protocols
├── Circular token dependencies
├── Oracle with single source
├── "Too good to be true" yields
└── Complex strategies you don't understand
```


DEXs work at scale. Both order book (XRPL) and AMM (Uniswap) models have processed trillions in volume. Permissionless trading is a solved problem.

Overcollateralized lending works. Aave, Compound, and MakerDAO have facilitated billions in loans with functional liquidation mechanisms. The model is sound for appropriate collateral.

Fiat-backed stablecoins maintain pegs. USDC and USDT have proven resilient. They're boring but functional—exactly what stablecoins should be.

Composability enables genuine innovation. Flash loans, yield optimization, and complex strategies are possible only because primitives can interact permissionlessly.

⚠️ Long-term sustainability of yields. Many yields depend on token emissions or temporary incentives. Equilibrium yields may be lower than current rates.

⚠️ How protocols behave in extreme stress. We've seen some crashes, but a true system-wide crisis hasn't fully tested all protocols simultaneously.

⚠️ Regulatory treatment of each primitive. DEXs, lending, stablecoins, and derivatives may face different regulatory outcomes.

📌 Algorithmic stablecoins without substantial collateral. The track record is clear: they fail under stress. Terra/Luna was not an anomaly—it was a pattern.

📌 Undercollateralized lending. Attempts to reduce collateralization requirements have generally led to bad debt and losses.

📌 Complex yield strategies you don't understand. If you can't explain where the yield comes from, you don't understand the risks. Don't invest.

📌 Assuming composability is free. Each additional protocol dependency adds risk. Complex strategies have complex failure modes.

DeFi primitives are genuine financial innovations. DEXs enable permissionless trading. Lending protocols enable permissionless credit. Stablecoins enable stable value in volatile markets. These primitives work—when designed conservatively and used appropriately. The failures have come from pushing boundaries: algorithmic stablecoins without collateral, lending with exotic assets, complex strategies with hidden risks. Understanding each primitive's mechanics and limitations is essential to using DeFi safely.


Assignment: Create a visual diagram showing how DeFi primitives interact in a typical yield farming strategy.

Requirements:

Part 1: Choose a Strategy

  • Stablecoin lending on Aave
  • ETH/USDC LP on Uniswap
  • Leveraged yield farming on a specific protocol
  • A strategy from a yield aggregator (Yearn vault)

Part 2: Map the Primitives

  • Which primitives are involved (DEX, lending, stablecoin, etc.)
  • How assets flow between them
  • Where yield comes from at each step
  • What fees are paid at each step
  • What dependencies exist

Part 3: Identify Dependencies

  • What oracle does it use?
  • What happens if that primitive fails?
  • Are there circular dependencies?
  • What's the weakest link?

Part 4: Risk Assessment

Create a risk matrix:

Primitive Dependency Failure Mode Impact Probability

Part 5: Yield Source Analysis

  • Where does each source of yield come from?

  • Is the yield sustainable or subsidized?

  • What would equilibrium yield be without incentives?

  • Is the yield worth the risks identified?

  • Accuracy of primitive identification: 25%

  • Completeness of dependency mapping: 25%

  • Quality of risk assessment: 25%

  • Honest yield source analysis: 25%

Time investment: 2-3 hours
Value: This mapping process reveals hidden risks and should be done for any DeFi strategy before investing


Knowledge Check

Question 1 of 5

(Tests Understanding):

  • Uniswap documentation: Protocol mechanics
  • XRPL DEX documentation: Order book mechanics
  • Paradigm research: "Analysis of Uniswap Markets"
  • Aave documentation: Protocol mechanics and risk parameters
  • MakerDAO documentation: DAI and vault mechanics
  • Gauntlet: Risk analysis frameworks
  • Circle: USDC reserve attestations
  • Ripple: RLUSD documentation
  • Academic: "The Fragility of Algorithmic Stablecoins"
  • "DeFi Protocols as Lego Blocks" - Various academic papers
  • Flash loan attack post-mortems
  • Trail of Bits: DeFi security research

For Next Lesson:
Now that you understand the primitives, we'll examine what can go wrong. Lesson 4 covers the DeFi Risk Taxonomy—categorizing and quantifying the many ways DeFi participants lose money.


End of Lesson 3

Total words: ~5,600
Estimated completion time: 60 minutes reading + 2-3 hours for deliverable

Key Takeaways

1

Six core primitives form DeFi's foundation.

DEXs (trading), lending protocols (borrowing/lending), stablecoins (stable value), yield aggregators (optimization), derivatives (leverage/hedging), and the composability that connects them all.

2

DEXs work via order books or AMMs.

Order books match buyers and sellers (XRPL model). AMMs use liquidity pools and mathematical formulas (Uniswap model). Both have proven functional with different trade-offs.

3

Lending protocols require overcollateralization.

Without credit checks, loans must be self-securing through excess collateral. Attempts to reduce this requirement generally fail.

4

Stablecoin type determines risk profile.

Fiat-backed (USDC, RLUSD) are simplest and most reliable. Crypto-backed (DAI) work but are complex. Algorithmic (UST) have mostly failed catastrophically.

5

Composability is both DeFi's superpower and its systemic risk.

Primitives can combine in novel ways, enabling innovation. But dependencies create correlated failure risks that are difficult to assess. ---