A source-cited reference library 399 modules · 19 subdomains · 5 domains
Research Library
Decentralized Finance (DeFi) Protocols

Finance / Digital Assets

Decentralized Finance (DeFi) Protocols

Borrowing, trading, and interest implemented as public programs on blockchains — how the primitives work, and the documented failure modes that finance-as-code inherits.

Executive brief

DeFi protocols reproduce core finance — money-like tokens, exchange, and lending — as autonomous smart contracts. Their design removes counterparties and substitutes code; their documented failure modes are accordingly code-shaped: bad collateral logic, manipulated price feeds, and single-transaction exploits.

Overview and context

The Ethereum coin on the right sits on the layer where this market lives: programmable blockchains — ledgers that also execute programs — arrived in 2015 and made it possible to deploy financial logic that no human operates. Everything in this document is a program in that sense: stablecoins, which maintain a target value; automated market makers (AMMs), which price and trade against pooled reserves; lending pools, which lend against posted collateral; and bridges, which move assets between different ledgers. The economic functions are old — each reproduces an institution centuries deep — but every one of them now runs, unattended, at the speed of the chain: any account may call the program, twenty-four hours a day, with the only referee being the code's own arithmetic.

That sentence — the only referee is the arithmetic — is the document's whole risk thesis. Traditional finance distributes its trust across charters, audits, capital requirements, and regulators; DeFi concentrates it in the code and the data feeds the code consumes. When both are right, the systems run exactly as designed (the constant-product exchange example on the right is the canonical case, and the arithmetic is genuinely elegant). When either is wrong, the failures are the documented ones in the chart and table on the right — depegs, oracle manipulation, and exploits — and they do not wait for business hours or for anyone's approval to happen.

A physical Ethereum coin rendering on a dark background
The programmable layer's emblem — code that holds and moves value by its own arithmetic. Rendering via Wikimedia Commons.

The primitives

Stablecoins hold a target value — one dollar, by convention — through two documented designs: collateralized issuance (a reserve of assets backs every token) and algorithmic issuance (the supply itself adjusts to hold the peg by contract arithmetic). The price chart on the right shows the two designs' documented fates in one frame: during March 2023's banking-sector stress, a large fully-collateralized token broke to roughly $0.87 before its reserve was confirmed and it restored within days; in 2020's market crash the largest decentralized-collateral token's trading pool price dipped toward $0.90 before its auction mechanics corrected it; and in May 2022 the flagship algorithmic design collapsed to under a cent — not because of a hack but because the peg-holding arithmetic that had powered its rise reversed itself under selling pressure. Automated market makers price swaps by a published invariant — the product of the two pooled reserves stays constant through any swap (the example code derives it) — so anyone can verify the pricing at any moment; the same invariant produces the impermanent-loss economics that the table records as the AMM row's cost. Lending pools lend against collateral the borrower posts, liquidating when its value falls below a factor — a mechanism whose failure mode (the second code block computes a liquidation price in miniature) is cascade risk during volatile hours. Bridges move assets across chains by locking on one ledger and minting a representation on another; the largest documented failures of the era — the Ronin bridge loss in 2022, in the hundreds of millions of dollars — were compromise of a bridge's validator set, the human perimeter around otherwise sound code.

Documented depeg depth of the four reference events — the bottom price the page states against the $1.00 target.

UST · May 2022≈$0.02
USDC · Mar 2023≈$0.87
DAI · Mar 2020≈$0.90
xUSD · Nov 2025≈$0.08
The two collateralized designs broke briefly and restored; the two algorithmic designs did not, which is the section's frame for the whole stablecoin discussion.

The table is the four-primitive summary the prose refers to, with the failure each one is known for.

PrimitiveDesign ideaFailure the page records
StablecoinsCollateralized or algorithmic pegAlgorithmic collapse below a cent, May 2022
AMMsPricing by a pooled-reserve invariantImpermanent loss; spot-price oracle feeds
Lending poolsOver-collateralized loans, automated liquidationCascade liquidations in fast markets
BridgesLock-and-mint through a validator setValidator-set compromise, Ronin, 2022
The rows are the page's own four primitives, and the third column is the code-shaped risk each one inherits.

The snippet is the invariant the prose says the example code derives, stated in its smallest form.

# The constant product, as the section describes it
x * y = k          # two pooled reserves, one constant
# a swap changes x and y but must keep the product
(x + dx) * (y - dy) = k
# the same rule that prices a trade creates impermanent loss
The third line is the section's point: the pricing rule and the AMM row's cost are the same arithmetic seen from two sides.

The examples

The first code block derives the AMM invariant: two reserves, one product, and a swap that must respect it — read it as economics made testable, since the same three lines can be checked against any pool's on-chain numbers. The second computes the liquidation threshold of a small collateralized loan — the number at which the pool takes the collateral — because every borrower in a lending pool is effectively running exactly this calculation against their own position, whether they know it or not. Both are arithmetic only; both are the honest spine of systems whose complexity otherwise hides what is, at base, a price and a threshold.

Comparative data and specs

The table on the right is this document's spine: the four protocol classes, one row each — the finance function it reproduces, the design idea, and the documented failure example that defines its risk.

Interpreted: the rows share a texture — each failure is the code doing exactly what it was written to do in conditions its authors priced badly, or trusting data (an oracle, a validator set) that turned out controllable. That is the field's real lesson, and the legal shelf's documents are its complement: a DeFi position is a claim on code and collateral, and the question of what law that claim carries — securities law, property law, or neither — is a live legal question this library treats in its Legal shelf rather than pretending one answer covers it.

Protocol classFinance function reproducedDesign ideaDocumented failure example
StablecoinsMoney-like tokenCollateralized or algorithmic pegAlgorithmic collapse to <$0.01 (May 2022)
AMMsExchangePricing by pooled-reserve invariantImpermanent loss; spot-price oracle feeds
Lending poolsCreditOver-collateralized loans, automated liquidationCascade liquidations in fast markets
BridgesCross-ledger mobilityLock-and-mint via validator setValidator-set compromise, ~$600M (2022)

The four primitives and the failure each is known for.

Documented depeg depth of the three reference events — bottom price reached against the $1.00 target.

UST · May 2022≈$0.02
USDC · Mar 2023≈$0.87
DAI · Mar 2020≈$0.90
xUSD · Nov 2025≈$0.08

Reading — collateralized designs broke briefly and restored within days; the algorithmic designs (2022, 2025) did not restore. The cascade section covers how the 2025 failure propagated through lending protocols holding the token.

Actionable steps for analysts

  1. Read the invariant, then the code

    For any protocol being analyzed, identify the invariant (its published constant, its collateral factor, its peg mechanism) and then read the code paths that touch it. The two example blocks are the working template: nearly everything material reduces to a constant and a threshold, and everything that is not one of those two is where the risk lives — governance, upgradability, and the data feeds.

  2. Locate the oracle before trusting the price

    A protocol's price is only as honest as its feed: find where the code gets its numbers — which oracle, how often, with what deviation guard — because the documented manipulation failures are attacks on the feed, not the math. A feed sourced from one pool's spot price is the classic vulnerability; time-weighted or wide-quorum feeds reduce but do not eliminate it.

  3. Price the exit

    Compute the liquidation threshold (the second example block) before entering any collateralized position, and recompute it after every price move that matters. Documented cascade failures share one shape: many positions with the same threshold, all struck together by one fast movement — individual arithmetic is the defense that exists at the position level.

  4. Treat bridges as the perimeter

    Cross-chain assets introduce a second trust: the bridge's validator set. Before using any bridged asset, read what the bridge runs — how many validators, what controls their keys, who insures what — because the bridge is the seam where this document's code-shaped failures become human-shaped ones. The Ronin disclosure in the sources is the canonical study, written up by the protocol itself.

The table restates the four steps as the constant or threshold each one asks the analyst to find.

StepWhat to findRisk it addresses
Read the invariantThe published constant or collateral factorCode paths outside the math
Locate the oracleThe feed, its frequency, and its deviation guardPrice-feed manipulation
Price the exitThe liquidation thresholdCascade liquidations
Treat bridges as the perimeterThe validator set and key controlHuman-perimeter compromise
The third column is the page's own failure list, which is why the steps track the risk rather than the protocol's marketing.

The flow is the reading order the section recommends before entering a position.

InvariantWhat constant does the protocol promise to hold?
FeedWhere does the price come from, and who can move it?
ThresholdAt what price is the position taken?
PerimeterWhich humans control the bridge's keys?
The order moves from code to data to position to people, which is the page's map of where each kind of failure lives.

The checklist is the four steps as the facts an analyst should be able to state after reading a protocol.

# What the four steps should establish
invariant  -> the constant, factor, or peg rule
oracle     -> the source, its cadence, its deviation guard
exit       -> the liquidation price for this position
perimeter  -> validator count and who controls the keys
code       -> where governance and upgrades can change the rules
The last line is the section's reminder that what is not the constant or the threshold is where the risk lives.

Additional context — composability and cascade risk (documented crises)

The primitives above are individually analyzable; the field's documented crises mostly happen between them, and the mechanism deserves its own section because it is the risk this document's position-level arithmetic does not capture. DeFi's composability — protocols calling protocols, assets pledged as collateral inside other assets' lending markets — means a single instrument's failure propagates by design. The documented cascade sequence: when a token that functions as collateral loses its value, every position collateralized by it breaches its threshold simultaneously; automated liquidations then sell the collateral into thin markets, depressing prices further, which breaches more thresholds — a feedback loop that runs at chain speed with no human in the loop to slow it.

Two documented cases anchor the mechanism's scale. The May 2022 collapse of the algorithmic design in the chart above erased an estimated forty-five billion dollars of linked value in days and took most of the sector's lending platforms that held it with them. The November 2025 cascade in specialist risk-monitoring coverage followed the same anatomy in miniature and in concentrated form: a fund loss at a collateral provider fed through a yield token that fell from its dollar target to roughly $0.08 within hours, and the resulting bad debt propagated through lending protocols holding it — coverage of the event documented aggregate losses in the hundreds of millions and forced emergency protocol governance responses. The 2025 coverage's structural lesson matches 2022's: protocols with diversified reserves and segmented collateral weathered the cascade badly-connected ones suffered; automated circuit breakers and adaptive thresholds entered design practice as a direct consequence.

The reading for an analyst: position-level checks (the liquidation threshold of the example above) are necessary and insufficient — the portfolio question is not "can this position survive a price move" but "what does my asset hold, and what holds what I hold." Diligence across a protocol's collateral composition, its reserve attestations, and the protocols upstream of it is the cascade-era answer, and it is why the field's post-2022 design practice treats reserve transparency and third-party audits as ordinary expectations rather than features.

The table sets the two documented cascades side by side at the scale the page states.

CaseTrigger describedScale stated
May 2022 algorithmic collapsePeg arithmetic reversed under selling pressureAn estimated $45 billion of linked value in days
November 2025 cascadeFund loss at a collateral provider fed through a yield token to about $0.08Hundreds of millions in aggregate losses
The page's point is that the second is the first in miniature, not a different kind of event.

The flow is the documented cascade sequence the section names.

Collateral fallsA token used as collateral loses value.
Thresholds breachEvery position backed by it breaches at once.
Liquidations sellAutomated selling hits thin markets and depresses prices.
More breachesThe loop runs at chain speed with no human pause.
The loop is the section's mechanism; its lesson is that position-level arithmetic cannot see the links between positions.

The list restates the section's portfolio-level diligence as questions.

# Cascade-era diligence, from the section
position -> can this position survive a price move?
asset    -> what does my asset hold?
upstream -> what holds what I hold?
reserve  -> is composition attested and audited?
design   -> are breakers and thresholds adaptive?
# the first line is necessary; the next four are the actual question
The first line is the check the page says is insufficient on its own, and the rest are its replacement.

On-Chain Risk Indicators

On-chain risk indicators utilize publicly available blockchain data to measure market sentiment, valuation extremes, and investor behavior. Unlike traditional financial metrics that rely on exchange-reported data, these indicators are derived directly from transaction records, making them resistant to manipulation and available in real-time. Three widely documented composite indicators—MVRV, NUPL, and SOPR—provide insights into Bitcoin's market cycles by analyzing the relationship between current prices and historical acquisition costs.

MVRV (Market Value to Realized Value) compares Bitcoin's market capitalization (current price multiplied by circulating supply) to its realized capitalization (the sum of each coin's value when it was last moved on-chain). An MVRV ratio above 1 indicates that, on average, coins are trading at a profit relative to their last movement price, while values below 1 suggest average losses. Historically, MVRV values exceeding 3.0 have coincided with market tops, while values below 1.0 have marked significant bottoms. The indicator helps identify periods of excessive greed or fear by showing whether the market collectively believes coins are worth more or less than what investors paid for them.

NUPL (Net Unrealized Profit/Loss) expresses the difference between market cap and realized cap as a percentage of market cap, revealing whether the aggregate Bitcoin holdings are in net profit or loss. Calculated as (Market Cap - Realized Cap) / Market Cap, NUPL ranges from -1 (100% of coins in loss) to 1 (100% of coins in profit). Readings above 0.75 have historically signaled euphoric markets prone to correction, while readings below 0.25 have indicated capitulation phases where long-term holders begin accumulating. NUPL's strength lies in its ability to quantify investor sentiment without relying on surveys or indirect proxies, providing a direct measure of the market's psychological state based on actual transaction data.

SOPR (Spent Output Profit Ratio) analyzes whether coins are being spent at a profit or loss by comparing the realized value of spent outputs (their price when sold) to their value at creation (their price when last received). An SOPR above 1 indicates that, on average, coins are being sold at a profit, while values below 1 indicate average losses during spending. The metric is particularly useful for identifying capitulation events: sustained SOPR values below 1 during price declines suggest weak hands are exiting, while a rebound above 1 during accumulation phases indicates renewed confidence. Like MVRV and NUPL, SOPR is calculated exclusively from blockchain data, requiring no external price feeds or subjective inputs, making it a transparent tool for assessing market structure.

The table compares the three indicators by formula and by the threshold the page states for each.

IndicatorFormula statedThresholds the page records
MVRVMarket cap divided by realized capAbove 3.0 tops; below 1.0 bottoms
NUPL(Market cap minus realized cap) divided by market capAbove 0.75 euphoria; below 0.25 capitulation
SOPRRealized value of spent outputs divided by value at creationAbove 1 profit; below 1 loss
The three thresholds are the page's own, and all three share the same premise: compare today's price with what holders actually paid.

The formulas are written out below exactly as the prose states them, with the ranges it gives.

MVRV = market cap / realized cap
market cap   = current price x circulating supply
realized cap = sum of each coin's value at its last on-chain move
# above 1: average profit; below 1: average loss

NUPL = (market cap - realized cap) / market cap
# range -1 (all coins in loss) to 1 (all in profit)

SOPR = realized value of spent outputs / value at creation
# above 1: sold at profit; below 1: sold at loss
The block is the section's arithmetic in its own terms, and the comment on each one is the reading the page assigns.

The flow shows what the shared premise buys the analyst: a sentiment reading derived from the ledger alone.

Blockchain recordsTransaction timestamps and prices, no external feed.
Cost basisRealized cap sums what coins last moved at.
ComparisonsMVRV, NUPL, and SOPR each compare price with that basis.
ReadingProfit, loss, euphoria, or capitulation, from the data alone.
The last box is the section's claim about why these indicators resist manipulation: their input is the ledger itself.

The table records what each indicator's reading is said to signal, as the section states it.

IndicatorHigh readingLow reading
MVRVAbove 3.0 has coincided with topsBelow 1.0 has marked bottoms
NUPLAbove 0.75 signals euphoria prone to correctionBelow 0.25 indicates capitulation
SOPRAbove 1: coins sold at a profitBelow 1: coins sold at a loss; sustained weakness suggests weak hands exiting
The page labels these readings as historical tendencies, not laws, and the thresholds are the ones it gives.

Primary sources and media links

The AMM invariant — the constant-product pricing of a pooled exchange, derived; check it against any pool's numbers.

# Example: constant-product market maker (math only)
import math
x, y, k = 10_000, 10_000, 10_000 * 10_000  # reserves

def swap(dx):                    # sell dx of X for Y
    global x, y
    dy = y - k / (x + dx)        # output, minus the fee
    assert abs((x + dx) * (y - dy) - k) < 1e-6
    x, y = x + dx, y - dy
    return dy

print(round(swap(500), 3))       # slippage grows with size:
# larger trades move the pool price - the invariant enforces it.

The liquidation threshold — the price at which a collateralized loan is taken; every borrower in a pool runs this math.

# Example: minimum collateral ratio (math only)
def liquidation_price(debt, collateral, factor):
    # pool liquidates when collateral/debt < factor
    return debt * factor / collateral

# borrow 10,000 against 750 of asset, 90% factor
p = liquidation_price(10_000, 750, 0.9)
print(round(p, 2))   # -> 12.0 asset price floor:
# below this, the pool takes the collateral.

Quick reference — the rules at a glance

This page's rules all follow from one sentence: the only referee is the arithmetic. For a stablecoin, which of the two designs is held is the first question, because collateralized issuance broke and restored while algorithmic issuance did not. For an automated market maker, the rule is to read the invariant and accept its cost, since the same constant product that prices a swap also produces impermanent loss. For a lending pool, the rule is to compute the liquidation threshold before entering and recompute it after every move that matters. For a bridge, the rule is to treat the validator set as the perimeter, because the largest documented loss of the era was a compromise of that set rather than of the code. Across all four, the page's deeper rule is that position-level checks are necessary and insufficient: composability means a failure travels through whatever holds the asset, at chain speed and without a human pause. The page's practical answer is diligence across collateral composition, reserve attestations, and the protocols upstream, which is why it says transparency and audits became ordinary expectations after 2022. The table and flow below gather the rules for reuse.

The table collects the page's rules as a working sequence, one primitive per row plus the cross-cutting lesson.

PrimitiveRuleFailure it prevents
StablecoinsKnow the design and its peg arithmeticHolding an algorithmic design into a reversal
AMMsRead the invariant and price impermanent lossIgnoring the cost the constant product creates
Lending poolsCompute and recompute the liquidation thresholdCascade liquidation of the position
BridgesInspect the validator set and its key controlCompromise of the human perimeter
All fourCheck what the asset holds and what holds itComposability spreading a failure
The last row is the page's own escalation from position-level checks to a portfolio-level question, and it applies to every row above.

The flow is the reading order the page applies to any DeFi position, from the constant to the upstream links.

1. InvariantWhat constant or threshold does the code promise?
2. FeedWhere does its price come from, and who controls it?
3. ExitAt what price does the position get taken?
4. UpstreamWhat holds the asset, and what holds that?
The fourth box is the cascade-era addition, and the page treats it as part of the same inspection rather than a separate discipline.

The checklist is the page's rules reduced to one line per primitive, for reuse before a position is opened.

stablecoin -> which design, and what its peg arithmetic does
AMM        -> read the invariant; price impermanent loss
lending    -> compute and recompute the liquidation threshold
bridge     -> inspect the validator set and key control
portfolio  -> what does my asset hold, and what holds that?
practice   -> expect reserve transparency and third-party audits
Each line is one section in compressed form, and the last is the page's account of what changed in design practice after 2022.