Skip to content

Borrow/Lend System - How Lending Pools Work

TL;DR

Borrowing:

  • Borrow assets from a pool of lenders to use as margin or spot trading capital
  • Pay interest (APY) based on utilization - higher utilization = higher rates
  • Interest accrues continuously and is paid periodically (typically hourly)
  • Requires margin maintenance (can be liquidated if undercollateralized)

Lending:

  • Lend surplus assets to earn yield from borrower interest payments
  • Yield = utilization × borrow_rate × (1 - exchange_fee)
  • Lower yield when utilization is low (not all your capital is borrowed)
  • Can redeem lends subject to available liquidity

Interest Rate Model (Aave-style):

  • Rates scale with utilization via a two-slope curve
  • Below optimal utilization (~70%): gentle rate increase
  • Above optimal utilization: steep rate increase (incentivizes more lenders)

Key Difference from Perps: You borrow from other users (limited liquidity), not the exchange (infinite liquidity).


Table of Contents

  1. Why Borrow/Lend Exists
  2. How Borrowing Works
  3. How Lending Works
  4. Interest Rate Model
  5. Margin & Liquidation
  6. Borrow/Lend vs Perpetuals
  7. Throttling & Safety Mechanisms
  8. Key Files

1. Why Borrow/Lend Exists

The Problem It Solves

In traditional spot trading, you need the full amount of an asset to trade:

  • Want to buy 1 BTC at $100k? You need $100k USDC.
  • Want to sell 1 BTC? You need 1 BTC.

Borrow/Lend enables:

  1. Spot Margin Trading - Trade with leverage using borrowed capital
  2. Short Selling - Borrow an asset to sell, buy back later at lower price
  3. Capital Efficiency - Use one asset as collateral to access another
  4. Yield Generation - Earn passive income by lending idle assets

Example: Shorting SOL on Spot

Without borrow/lend:

You: Have $10,000 USDC, think SOL will drop
Problem: Can't short on spot without owning SOL

With borrow/lend:

1. Deposit $10,000 USDC as collateral
2. Borrow 100 SOL (at $100/SOL)
3. Sell 100 SOL → receive $10,000 USDC
4. SOL drops to $80
5. Buy back 100 SOL for $8,000
6. Repay 100 SOL borrow
7. Profit: $2,000 (minus interest)

2. How Borrowing Works

When You Borrow

  1. Check existing lends - If you have lends in the same asset, they're redeemed first (prevents flash loan scenarios)
  2. Validate against book limits - Total borrowed can't exceed pool capacity or utilization caps
  3. Validate margin - Must have IMF (Initial Margin Fraction) to open
  4. Pay entry fee - Prorated interest for the current interval
  5. Create borrow position - Tracked with negative net_quantity

Borrow Execution Flow

User calls borrow(symbol, quantity)


Check if user has existing lends

        ├─ Yes → Redeem lend first (offset borrow)


Validate book state (Open? Under limit?)


Check utilization: (borrowed + new) / lent < max_utilization

        ├─ Too high → Error: BorrowLendMaxUtilization


Check margin: margin_fraction > IMF

        ├─ Insufficient → Error: InsufficientMargin


Execute borrow:
  - Update book: borrowed_quantity += quantity
  - Track position in open_borrows set
  - Charge entry fee (interest to end of interval)
  - Emit BorrowLendEvent

Entry Fee (Why You Pay Immediately)

When you borrow mid-interval, you pay interest for the remainder of that interval upfront:

Interval: 1 hour (3600000 ms)
You borrow at: 15 minutes into interval
Remaining: 45 minutes

Entry fee = borrow_rate × quantity × (45 min / 1 year)

This prevents gaming: you can't borrow just before interest payment,
then repay right after to avoid paying.

Key file: /engine/src/models/borrow_lend_book.rs:395-430

What You Can Borrow

ConstraintDescription
Max UtilizationCan't push utilization above threshold (e.g., 95%)
Open Borrow Lend LimitHard cap on total borrowed amount
ThrottleRate limit on how fast utilization can increase
MarginMust maintain IMF after borrowing

3. How Lending Works

When You Lend

  1. Check existing borrows - If you have borrows in the same asset, they're repaid first (reduces debt)
  2. Validate against book limits - Total lent can't exceed pool capacity
  3. Create lend position - Tracked with positive net_quantity

Lend Execution Flow

User calls lend(symbol, quantity)


Check if user has existing borrows

        ├─ Yes → Repay borrow first (reduce debt)


Validate book state (Open?)


Check limits: lent + new < open_borrow_lend_limit

        ├─ Exceeded → Error


Execute lend:
  - Update book: lent_quantity += quantity
  - Track position in open_lends set
  - Emit BorrowLendEvent

How You Earn Yield

Your yield depends on three factors:

Lend Yield = lent_quantity × lend_rate × time_fraction

Where:
  lend_rate = utilization × borrow_rate × (1 - fee)

Simplified:

Your share of borrowed assets × Interest they pay × Your cut (after exchange fee)

Example Yield Calculation

You lend: 10,000 USDC
Total lent: 100,000 USDC
Total borrowed: 70,000 USDC
Borrow rate: 10% APY
Exchange fee: 10%

Utilization = 70,000 / 100,000 = 70%

Your lend_rate = 70% × 10% × (1 - 10%) = 6.3% APY

Over 1 hour:
  Yield = 10,000 × 6.3% × (1 hour / 8760 hours)
        = 10,000 × 0.063 × 0.000114
        = $0.072

Not much per hour, but compounds!
Annual: ~$630 on $10,000

Redeeming Lends

You can withdraw your lends, subject to liquidity:

Max redeemable = lent_quantity - borrowed_quantity / max_utilization

Example:
  Lent: 100,000 USDC
  Borrowed: 70,000 USDC
  Max utilization: 95%

  Max redeemable = 100,000 - 70,000/0.95 = 100,000 - 73,684 = 26,316 USDC

If utilization is at max, you cannot redeem until:

  • Borrowers repay
  • New lenders deposit

4. Interest Rate Model

Aave-Style Two-Slope Curve

Backpack uses an Aave-inspired interest rate model with two slopes:

                    Interest Rate

                         │                        ╱
                         │                      ╱
                         │                    ╱   Slope 2 (steep)
                         │                  ╱
                         │          ┌─────╱
                         │        ╱ Kink point
                         │      ╱
                         │    ╱  Slope 1 (gentle)
                         │  ╱
                         │╱
        ─────────────────┼───────────────────────────
                         │ Optimal    100%  Utilization
                         │ (~70%)

The Formula

rust
// From: /core/types/src/math/borrow_lend_aave_interest.rs

if utilization < optimal_utilization {
    rate = base_rate + (utilization / optimal) × slope_one
} else {
    rate = base_rate + slope_one +
           ((utilization - optimal) / (1 - optimal)) × slope_two
}

Example Parameters

ParameterValueMeaning
optimal_utilization70%Where the kink occurs
base_variable_borrow_rate0%Minimum rate
variable_rate_slope_one25%Rate at optimal utilization
variable_rate_slope_two60%Additional rate above optimal

Rate Examples

UtilizationBorrow RateCalculation
0%0%Just base rate
35%12.5%0 + (35/70) × 25%
70% (optimal)25%0 + 25% (kink point)
85%55%0 + 25% + ((85-70)/(100-70)) × 60%
100%85%0 + 25% + 60% (max)

Why This Design?

Utilization RangeBehaviorPurpose
0% - optimalGentle increaseEncourage borrowing, capital efficiency
optimal - 100%Steep increaseDiscourage over-borrowing, attract lenders

The steep slope above optimal utilization creates urgency:

  • Borrowers: "Rates are expensive, I should repay"
  • Lenders: "High yields! I should lend more"

This self-balances the pool toward optimal utilization.


5. Margin & Liquidation

Borrow Positions Are Margin Positions

Just like perpetual futures, borrow/lend positions can be liquidated if your account becomes undercollateralized.

Margin Requirements

ThresholdPurposeTypical Value
IMF (Initial Margin Fraction)Required to open borrow2-20%
MMF (Maintenance Margin Fraction)Liquidation threshold1-10%

How Borrows Affect Equity

Net Equity = Collateral Value + Unrealized PnL - Borrow Liability

Where:
  Collateral Value = Σ(asset_balance × mark_price × (1 - haircut))
  Borrow Liability = Σ(borrowed_quantity × mark_price)

Liquidation Flow

Account margin_fraction drops below MMF


Liquidation triggered


Borrow positions can be ADL'd (forced closed)

        ├─ Lenders may be ADL'd if redemption liquidity insufficient


Account equity restored above MMF

Example: Borrow Liquidation

Initial State:
  Collateral: $10,000 USDC
  Borrow: 50 SOL @ $100 = $5,000 liability
  Equity: $10,000 - $5,000 = $5,000
  Margin Fraction: $5,000 / $5,000 = 100%

SOL price rises to $180:
  Collateral: $10,000 USDC (unchanged)
  Borrow: 50 SOL @ $180 = $9,000 liability
  Equity: $10,000 - $9,000 = $1,000
  Margin Fraction: $1,000 / $9,000 = 11.1%

If MMF = 10%, still safe.
If SOL hits $200:
  Equity: $10,000 - $10,000 = $0
  Margin Fraction: 0% → LIQUIDATED

Key insight: Borrowing an asset that appreciates = losing money (your debt grows).


6. Borrow/Lend vs Perpetuals

Key Differences

AspectBorrow/LendPerpetual Futures
Liquidity SourceOther users (limited pool)Exchange (infinite)
Utilization CapYes (can't borrow > lent)No
Interest TypeContinuous APY based on utilizationFixed funding rate (8hr)
Entry CostEntry fee (prorated interest)None
Position SideAsymmetric (borrow=debt, lend=credit)Symmetric (long/short)
RedemptionSubject to liquidityDirect settlement
Use CaseSpot margin, short sellingLeveraged speculation

When to Use Each

ScenarioBest Choice
Short-term leveraged betPerps (no entry fee, predictable funding)
Spot margin tradingBorrow/Lend
Short selling spot assetsBorrow/Lend
Earning yield on idle assetsLend
Delta-neutral strategiesBoth (depends on rates)

Interest vs Funding

Borrow/Lend:
  Rate changes with utilization
  You pay: borrowed_quantity × APY × time
  Rate can spike during high demand

Perpetuals:
  Rate changes with perp premium vs spot
  You pay/receive: position_notional × funding_rate
  Paid at fixed intervals (typically 8hr)

7. Throttling & Safety Mechanisms

Why Throttling?

Without limits, a single user could:

  1. Borrow all available liquidity instantly
  2. Prevent other users from redeeming lends
  3. Manipulate interest rates

Throttle Mechanism

┌─────────────────────────────────────────────────────────┐
│                    Utilization Throttle                  │
├─────────────────────────────────────────────────────────┤
│                                                          │
│  utilization_threshold: 80%  ← Below this, no throttle  │
│  utilization_bound: 85%      ← Current max allowed      │
│  update_fraction: 10%        ← How fast bound moves     │
│                                                          │
│  Each interest interval:                                 │
│    bound moves toward 100% by update_fraction           │
│                                                          │
└─────────────────────────────────────────────────────────┘

How it works:

  • Below threshold (80%): No restriction
  • Above threshold: Can only borrow up to current utilization_bound
  • Bound slowly increases each interval
  • Prevents rapid utilization spikes

Max Utilization Cap

max_utilization: 95% (typical)

Even with throttle fully relaxed, utilization cannot exceed this.
Ensures lenders always have some redemption liquidity.

Book States

StateBorrowsRepaysLendsRedeems
OpenAllowedAllowedAllowedAllowed
RepayOnlyBlockedAllowedBlockedAllowed
ClosedBlockedBlockedBlockedBlocked

8. Key Files

ComponentLocation
Core Borrow/Lend Logic
Execute borrow/lend/engine/src/engine/borrow_lend/mod.rs
Command handlers/engine/src/engine/borrow_lend/commands.rs
Query handlers/engine/src/engine/borrow_lend/queries.rs
Book State
BorrowLendBook struct/engine/src/models/borrow_lend_book.rs
Book types/core/types/src/models/borrow_lend.rs
Interest Rates
Interest payment processing/engine/src/engine/interest.rs
Aave interest model/core/types/src/math/borrow_lend_aave_interest.rs
Throttle logic/core/types/src/math/borrow_lend_throttle.rs
Margin & Clearing
Borrow clearing/engine/src/clearing_house/clearing/borrow_lend.rs
Position settlement/engine/src/clearing_house/settlement/borrow_lend.rs
Position margin traits/engine/src/traits/position_margin.rs
Liquidation
Liquidation orchestration/engine/src/engine/liquidation/mod.rs
ADL selection/liquidator/src/context/backstop/positions.rs

Summary

QuestionAnswer
What is borrow/lend?Pool-based lending where users borrow from other users
When would I borrow?Spot margin trading, short selling, capital efficiency
How do I earn yield?Lend assets to the pool, earn interest from borrowers
How are rates determined?Aave-style utilization curve (two slopes)
Can I be liquidated?Yes, if your margin fraction drops below MMF
How is it different from perps?Limited liquidity, continuous interest vs fixed funding
What prevents abuse?Utilization caps, throttling, entry fees