Markets III: Commodities, Energy and Crypto · Markets
23DeFi Credit and Leverage
On 11 October 2022 a trader bought a thin token on the few exchanges whose prices fed a lending venue’s oracle. Within half an hour the price the oracle reported rose more than thirteenfold. The trader’s position in the venue, now marked at that price, was worth enough to serve as collateral for borrowing everything the venue held: he borrowed and withdrew more than USD 110 million of other tokens and left the inflated collateral behind. Lending on a blockchain works without a credit officer: a program lends against collateral at a loan-to-value it knows, liquidates anyone whose collateral falls below a threshold, and prices everything with an oracle. This chapter covers the pools that do the lending, the liquidations that keep them solvent, the flash loans that exist nowhere else, the staking yield on which much of the collateral earns a return, and the two ways the system has broken: stablecoins whose peg was an algorithm, and oracles that could be bought.
23.1 Lending pools
Definition 23.1 (Lending pool, kinked interest-rate curve)
A lending pool is a smart contract that takes deposits of a token from suppliers and lends them to borrowers who post other tokens as collateral, paying suppliers the interest borrowers pay less a share kept by the protocol. A kinked interest-rate curve sets the borrow rate as a function of the pool’s utilisation, rising gently up to a target utilisation and steeply beyond it.
Utilisation is the share of supplied tokens that is lent out, as in the securities lending of One Quant Book 1, chapter 16. The pool has no maturity: suppliers can withdraw at any time, but only from what is not lent. The kink is the pool’s defence of that liquidity. Above it, borrowing becomes so expensive that borrowers repay and suppliers arrive, pulling utilisation back and leaving tokens for those who want to withdraw.
Proposition 23.2 (Supply rate)
With utilisation , borrow rate and a reserve factor kept by the protocol, suppliers earn .
Proof. Borrowers pay on the lent amount, a fraction of the supply; the protocol keeps of it. ∎
As of September 2026 — A lending protocol’s rate model and flash-loan fee
Aave’s documentation describes its v3 interest-rate strategy as based on two slopes, one below an optimal usage ratio and another from that point to 100%, with a base variable borrow rate, per reserve. Positions are over-collateralised, risk is tracked by a health factor with per-reserve liquidation thresholds, and a position with a health factor below 1 can be liquidated by anyone, who repays part of the debt and receives collateral at a discount, the liquidation bonus. In the v3 contracts a liquidation may repay at most 50% of the debt (the close factor), and all of it when the health factor is at or below 0.95 or the position is below USD 2 000. The flash-loan fee was set at 0.05% at deployment and can be changed by governance.
23.2 Liquidations
Definition 23.3 (Loan-to-value ratio, health factor, liquidation bonus)
The loan-to-value ratio of a collateral asset is the maximum a borrower may borrow per dollar of it. The health factor of an account is the sum over its collateral of value times liquidation threshold, divided by the value of its debt; below one, the account may be liquidated. The liquidation bonus is the discount at which a liquidator receives collateral for the debt it repays.
The loan-to-value ratio is a haircut (One Quant Book 1, chapter 6) applied when borrowing; the liquidation threshold, a little higher, is the haircut at which the position is taken. There is no margin call: the borrower is not asked for more collateral, it is liquidated by whoever acts first, and the bonus pays them to act. A borrower with 100 ether of collateral at a threshold of 82.5% and USD 240 000 of debt has a health factor of 1.03 at 3 000 dollars and is liquidated below 2 909.
Proposition 23.4 (Liquidation arithmetic)
A liquidator repays an amount of debt, at most the close factor times the debt, and receives collateral worth at the oracle price, with the bonus. The borrower’s health factor after a liquidation of is , where is the threshold-weighted collateral value, the debt value and the collateral’s threshold; it rises only if , which holds when the health factor was above .
Proof. The debt falls by and the threshold-weighted collateral by . The ratio with exceeds exactly when . ∎
The proposition has a sting. A position that falls far below one before anyone acts, because the price gapped or the chain was congested, can be pushed deeper by its own liquidation: each dollar repaid removes more than a dollar of threshold-weighted collateral. When the collateral left is worth less than the debt, the pool is left with bad debt that its suppliers bear.
23.3 Flash loans
Definition 23.5 (Flash loan)
A flash loan is a loan without collateral that must be repaid, with a fee, within the same transaction; if it is not, the whole transaction reverts and the loan never happened.
A flash loan has no credit risk for the lender because the chain’s atomicity enforces repayment: the transaction either ends with the pool repaid or does not exist. It lets anyone act with a pool’s capital for one transaction. The canonical use is a liquidation by a liquidator with no capital: borrow the stablecoins to repay, receive the collateral with its bonus, sell it on an automated market maker, repay the flash loan, keep the rest. In the tutorial, liquidating half of the borrower’s debt at an ether price of 2 800 seizes 45 ether, sells them for USD 124 505 in a pool of 5 000 ether, repays the USD 120 000 borrowed and USD 60 of fee, and leaves USD 4 445. The same atomicity serves attacks: a flash loan can move a price, use the moved price, and restore it, all in one transaction. Qin, Zhou, Livshits and Gervais analysed two such attacks, both in February 2020, and measured returns on investment above 500 000%.
23.4 Liquid staking, restaking and the staking yield
Definition 23.6 (Staking yield, liquid staking token, restaking)
The staking yield is the return earned by locking a proof-of-stake chain’s token with a validator (Chapter 14): new issuance and a share of fees, less penalties. A liquid staking token is a transferable token that represents staked tokens and their accruing rewards, issued by a protocol that stakes deposits on its users’ behalf. Restaking is committing already-staked tokens, or liquid staking tokens, as security for further services, for additional rewards and additional risk of their being destroyed for misbehaviour.
As of September 2026 — A staking yield
Lido’s public API reported a seven-day moving average annual percentage rate of 2.24% for its staked-ether token, stETH, on 24 September 2026, and 9.76 million ether staked through it: about 22% of the 43.8 million ether held by validators on the beacon chain that day.
The staking yield is crypto’s nearest thing to a risk-free rate for ether, and the liquid staking token is the collateral on which much of the leverage is built: deposit stETH, borrow ether, stake it, repeat, earning the staking yield on several times the capital as long as the borrow rate stays below it. The loop’s risks are the ones of any carry trade funded short: the borrow rate can rise above the yield when utilisation climbs, and the liquid staking token can trade below the value of the ether behind it when holders want to leave faster than withdrawals from staking allow, triggering liquidations of the loopers. Restaking layers further claims on the same collateral: EigenLayer’s contracts accept liquid staking tokens, beacon-chain ether and other tokens, and let each operator allocate a share of its delegated stake to be slashable by a given service.
23.5 Algorithmic stablecoins and oracle manipulation
Definition 23.7 (Algorithmic stablecoin)
An algorithmic stablecoin is a token that aims at a fixed value without holding reserves of that value, relying instead on a mechanism that exchanges it for another token of floating value created or destroyed to absorb demand.
The mechanism holds the peg only while the floating token is worth more than the stablecoins outstanding; when confidence falls, redemptions create floating tokens faster than anyone wants them, their price falls, and each redemption creates more of them. According to the SEC, Terraform Labs marketed its stablecoin UST, which was to hold its dollar peg by being exchangeable for its token LUNA, as “yield-bearing”, paying as much as 20% through its Anchor protocol; in May 2022 UST lost its peg and it and its sister tokens fell close to zero.
Definition 23.8 (Oracle manipulation)
Oracle manipulation is moving the price that an oracle reports to a smart contract, usually by trading in the thin markets it reads, in order to borrow against inflated collateral, avoid a liquidation or trigger one.
As of September 2026 — The Mango Markets case
The CFTC alleged in January 2023 that on 11 October 2022 Avraham Eisenberg, through two accounts on Mango Markets, built large leveraged positions in a swap on the MNGO token, pumped MNGO’s price on three exchanges feeding the venue’s oracle, which reported a more than thirteenfold rise in 30 minutes, and used the inflated positions as collateral to withdraw over USD 110 million, of which about USD 67 million was later returned. A jury convicted him of commodities fraud, commodities manipulation and wire fraud; on 23 May 2025 the trial judge granted his motion under Rule 29, vacating the first two counts and entering a judgment of acquittal on the third.
Proposition 23.9 (The pump that borrows a pool dry)
A pool lends up to against collateral of tokens at price and loan-to-value , with the price read from a constant-product market holding dollars. Pushing that market’s price up by a factor costs dollars and buys a fraction of its tokens. The attacker can borrow the whole pool once ; its gain from borrowing and abandoning the collateral is plus whatever the tokens bought are worth afterwards.
Proof. Keeping constant while the price rises by multiplies by and divides by . Borrowing power is , capped by the pool; the collateral is left behind. ∎
The defences follow from the formula: loan-to-value ratios that fall with the thinness of the collateral’s markets, caps on how much can be borrowed against any one collateral, oracles that read deep markets and smooth over time, and circuit breakers on sudden price moves. None of them is free: each makes the pool less useful to honest borrowers.
23.6 Tutorial: a lending pool under stress
Goal. Simulate a lending pool: the borrow rate as a kinked function of utilisation, a borrower’s health factor through a price fall, a liquidation with close factor and bonus, and a liquidation funded by a flash loan. End state: the chapter’s figures and the numbers of the text.
Liquidation and the flash loan. The engine’s two most delicate functions.
def liquidate(self, acct: Account, debt_asset: str, coll_asset: str, repay: float) -> float: """Repay up to the close factor of the debt of an account whose health is below one; returns the collateral seized, worth the repayment plus the bonus.""" if self.health(acct) >= 1: raise ValueError("account is healthy") repay = min(repay, self.close_factor * self.owed(acct, debt_asset)) seize = repay * self.prices[debt_asset] / self.prices[coll_asset] * (1 + self.bonus[coll_asset]) seize = min(seize, acct.collateral[coll_asset]) r = self.reserves[debt_asset] acct.debt[debt_asset] -= repay / r.borrow_index r.borrowed -= repay / r.borrow_index acct.collateral[coll_asset] -= seize return seize def flash_loan(self, asset: str, amount: float, callback) -> float: """Lend `amount`; `callback(amount)` must return at least amount x (1 + fee), else the loan reverts (raises) and nothing happened. Returns the fee earned by the reserve's suppliers.""" r = self.reserves[asset] if amount > r.available(): raise ValueError("insufficient liquidity") repaid = callback(amount) due = amount * (1 + self.flash_fee) if repaid < due: raise ValueError("flash loan not repaid: transaction reverts") fee = repaid - amount r.supplied += fee / r.supply_index return feeListing 23.1. Liquidation with close factor and bonus, and a flash loan that reverts unless repaid. code/firm/lendpool/firm_lendpool.py The flash liquidation. Borrow, liquidate, sell the collateral in a pool with
firm.amm, repay.def flash_liquidation(eth_price: float = 2_800.0, pool_eth: int = 5_000, fee_bps: int = 30) -> dict: """A liquidator with no capital: flash-borrow the repayment, liquidate half the debt, sell the seized ETH in a constant-product pool at the market price, repay the flash loan with its fee, keep the rest.""" p = make_pool() acct = Account({"ETH": 100.0}) p.borrow(acct, "USDC", 240_000.0) p.prices["ETH"] = eth_price result = {} def callback(amount: float) -> float: seized = p.liquidate(acct, "USDC", "ETH", amount) e18, e6 = 10**18, 10**6 usdc = cp_amount_out(int(seized * e18), pool_eth * e18, int(pool_eth * eth_price * e6), fee_bps) / e6 result.update(seized=seized, usdc=usdc) return min(usdc, amount * (1 + p.flash_fee)) repay = 0.5 * p.owed(acct, "USDC") fee = p.flash_loan("USDC", repay, callback) result.update(repay=repay, fee=fee, profit=result["usdc"] - repay - fee, health_after=p.health(acct)) return resultListing 23.2. A liquidation funded by a flash loan. code/markets-3/23-defi-credit-and-leverage/python/m3_defi.py - Run
flash_liquidation(),pump_attackover pumps from 1 to 40, andfig_defi.py.
What to change next. Let the price gap to 2 400 before the liquidation and find the pool’s bad debt; add a second liquidator competing in the same block; make the oracle a 30-minute average and recompute the pump’s cost.
23.7 Build: the lending pool engine
Purpose. The miniature firm lends, borrows and liquidates on chain: it must know its health factors, the rates it will pay as utilisation moves, the profit of a liquidation after the sale of the collateral, and the exposure of a pool it supplies to bad debt.
Interface. RateModel(base, slope1, slope2, optimal); Reserve with utilisation, rates, accrue, available; Pool with supply, borrow, health, liquidate, flash_loan. Collateral sales through firm.amm.
Rules. Debt and deposits held as scaled balances against indices; borrowing refused above the loan-to-value or the available liquidity; liquidation only below a health factor of one and at most the close factor; a flash loan that is not repaid raises and leaves no trace.
Acceptance tests. code/firm/lendpool/tests/: the kink; health factor and accrual; refusal above the loan-to-value; liquidation of a healthy account refused; seizure with the bonus; a flash loan’s fee and its revert.
Stretch. Several collateral assets with different thresholds; bad-debt accounting; isolation modes and borrow caps; the rate’s reaction to a run on deposits.
Sources and further reading
- Aave documentation: v3 overview, interest-rate strategy, flash loans; the contract LiquidationLogic in the aave-v3-origin repository. Accessed September 2026.
- EigenLayer core contracts documentation (Layr-Labs/eigenlayer-contracts, docs/README), September 2026.
- K. Qin, L. Zhou, B. Livshits and A. Gervais, “Attacking the DeFi Ecosystem with Flash Loans for Fun and Profit”, Financial Cryptography 2021 (arXiv:2003.03810).
- CFTC, press release 8647-23 (charges against Avraham Eisenberg), January 2023; United States v. Eisenberg (S.D.N.Y.), opinion and order of 23 May 2025 (Doc 220).
- SEC, press release 2023-32, “SEC Charges Terraform and CEO Do Kwon with Defrauding Investors”, 16 February 2023.
- Lido, public stETH APR and statistics endpoints; beacon-chain validator balances from a public beacon node; 24 September 2026.
23.8 Exercises
Exercise 23.1 ★
With the chapter’s rate curve, what are the borrow and supply rates at 50% and at 95% utilisation?
Solution
Solution of Exercise 23.1.
At 50%: borrow , supply . At 95%: borrow , supply .
Exercise 23.2 ★
A borrower has 50 ether of collateral (threshold 82.5%) and USD 100 000 of debt. At what ether price is it liquidated?
Solution
Solution of Exercise 23.2.
dollars.
Exercise 23.3 ★
Why does a flash loan carry no credit risk for the pool?
Solution
Solution of Exercise 23.3.
The transaction either ends with the loan and fee repaid or reverts entirely, in which case the tokens never left the pool. There is no state in which the loan is outstanding.
Exercise 23.4 ★★
A liquidator repays USD 50 000 of debt against ether at 2 500 with a 5% bonus. How much ether does it receive?
Solution
Solution of Exercise 23.4.
ether.
Exercise 23.5 ★★
A borrower’s health factor is 0.80 and the collateral’s threshold is 82.5% with a 10% bonus. Does liquidation improve its health factor?
Solution
Solution of Exercise 23.5.
No: , above the health factor of 0.80, so each liquidation lowers it further (Proposition 23.4); the position is heading for bad debt.
Exercise 23.6 ★★
Explain the looping trade on a liquid staking token and name two ways it loses money.
Solution
Solution of Exercise 23.6.
Supply the liquid staking token, borrow ether against it, stake the ether into more of the token, and repeat, earning the staking yield on several times the capital less the borrow rate on the debt. It loses if the borrow rate rises above the staking yield (utilisation spikes), or if the token trades below the ether behind it and the loops are liquidated.
Exercise 23.7 ★★★
Coding. With pump_attack, find the smallest pump at which the attack pays, with and without the tokens bought keeping a value of USD 1.
Solution
Solution of Exercise 23.7.
At a pump of 1.93 if the tokens bought become worthless, 1.72 if they keep USD 1: borrowing 60% of an inflated value and abandoning collateral worth the true value pays as soon as exceeds one plus the pump’s cost per dollar of collateral.
Exercise 23.8 ★★★
Find the flaw. “Our pool is safe: every loan is over-collateralised.”
Solution
Solution of Exercise 23.8.
Over-collateralised at the oracle’s price. If the price can be moved, or the collateral cannot be sold near it in a crash, or liquidators do not act in time, the collateral can be worth less than the debt: the protection is only as good as the oracle and the liquidity of the collateral.
23.9 Problem: The Oracle Pump
Problem 23.1
Weekend problem — borrowing a pool dry
A lending pool holds USD 50 million of stablecoins and accepts a thin token as collateral at a loan-to-value of 60%, priced by an oracle that reads a constant-product market holding USD 2 million and 2 million tokens (price USD 1). An attacker holds 5 million tokens.
Part I — The mechanics.
- What can the attacker borrow honestly?
- By what factor must the oracle’s price rise for the attacker to borrow the whole pool?
- What does pushing the market’s price up by that factor cost, and how many tokens does it buy?
- What is the attacker’s gain if the tokens bought become worthless? If they keep USD 1?
- Why does the gain fall for pumps beyond that factor?
Part II — The thresholds.
- What is the smallest pump that pays?
- How does the answer change if the source market holds USD 20 million?
- What if the loan-to-value is 30%?
- What borrow cap on this collateral would limit the attacker’s gain to zero at any pump?
- What would a 30-minute time-weighted oracle change?
Part III — The case.
- What did the CFTC allege happened on Mango Markets?
- What did the trial judge decide after the jury’s verdict, and on what kind of motion?
- Who bears the loss when a pool is borrowed dry?
- How does this attack differ from a flash-loan attack?
- What would a lending protocol’s governance do next?
Part IV — Judgement.
- Is the pool’s design at fault or the attacker’s conduct?
- Should a pool accept thin tokens as collateral at all?
- How should a supplier choose which pools to supply?
- State the named result: the pump that borrows the pool dry, and the attacker’s cost against the gain.
- In one sentence: what is an oracle to a lending pool?
Solution
Solution of Problem 23.1.
1. USD 3 million. 2. . 3. USD 6.16 million, buying of the market’s tokens, 1.51 million. 4. USD 38.84 million; USD 40.35 million if the 1.51 million tokens keep USD 1. 5. The pool is empty: further pumping only costs. 6. 1.93. 7. The attack never pays: pushing a USD 20 million market costs more than any borrowing it enables. 8. doubles to 33.3, but the attack still pays from a pump of 4.98 and can gain USD 35.4 million: halving the loan-to-value is not enough. 9. A cap of about USD 5.8 million on borrowing against this collateral: the gain (USD million) is then never positive. 10. The attacker would have to hold the pumped price for half an hour, multiplying the cost and the arbitrage losses while the price is out of line. 11. That Eisenberg pumped MNGO on the exchanges feeding the oracle, raising the reported price more than thirteenfold in 30 minutes, and used his inflated positions as collateral to withdraw over USD 110 million. 12. On a motion under Rule 29, which asks whether the evidence could sustain the verdict, the judge vacated the first two counts and entered a judgment of acquittal on the third (23 May 2025). 13. The suppliers of the pool, pro rata, unless the protocol has a reserve or a backstop. 14. It lasts longer than a transaction and needs the attacker’s own capital; a flash-loan attack borrows the capital and must complete in one transaction, so it can only exploit prices that move within it. 15. Freeze the collateral, lower its loan-to-value, cap borrowing against it, change the oracle, and vote on recoveries. 16. Both: the design made the attack cheap, and whether the conduct was unlawful is for courts. 17. Only with borrow caps sized to the cost of moving its oracle’s sources, or not at all. 18. By the collateral they accept and its caps, their oracles, their bad-debt history and reserves, and utilisation (the ability to withdraw). 19. Named result: a pump of 16.7 times borrows the pool dry; it costs USD 6.16 million in the source market (plus the USD 5 million of abandoned collateral) against USD 50 million borrowed, a gain of about USD 38.8 million. 20. The only thing it knows about the world, and so the thing an attacker buys.
23.10 Interview questions
Interview question 23.1 ★ trader
What is a health factor, and what happens when it falls below one?
Solution
Solution of Interview question 23.1.
Threshold-weighted collateral over debt. Below one, anyone may repay part of the debt (up to the close factor) and take collateral at a discount, the liquidation bonus.
What the interviewer is looking for: the ratio, the threshold, and permissionless liquidation.
Interview question 23.2 ★ developer
How does a flash loan work, and why can it only exist on a blockchain?
Solution
Solution of Interview question 23.2.
A loan that must be repaid within the transaction or the transaction reverts. It needs atomic execution of arbitrary code across contracts, which a blockchain provides and traditional settlement does not.
What the interviewer is looking for: atomicity as the collateral.
Interview question 23.3 ★★ researcher
Why do lending pools use a kinked rate curve rather than a linear one?
Solution
Solution of Interview question 23.3.
The pool has no maturity and must keep tokens available for withdrawals; a steep rate above the target utilisation forces repayment and attracts supply before the pool is fully lent, while a gentle slope below keeps borrowing cheap in normal times.
What the interviewer is looking for: liquidity for withdrawals.
Interview question 23.4 ★★ risk
How would you set the loan-to-value of a new collateral token?
Solution
Solution of Interview question 23.4.
From the collateral’s liquidity (depth of the markets the oracle reads and where liquidators sell), its volatility over the time liquidation takes, the cost to manipulate its oracle, and a borrow cap so that the maximum loss is bounded; revisit as markets change.
What the interviewer is looking for: liquidation horizon, depth and manipulation cost.
Interview question 23.5 ★★ trader, researcher
Why did an algorithmic stablecoin paying 20% collapse, and what would you have watched?
Solution
Solution of Interview question 23.5.
The yield was paid, not earned, and the peg depended on the floating token’s value exceeding the stablecoins outstanding; when demand turned, redemptions created floating tokens that nobody wanted. Watch the ratio of the floating token’s value to the stablecoin supply, the source of the yield, and redemption flows.
What the interviewer is looking for: reflexivity and the subsidy.
Interview question 23.6 ★★★ developer, risk
Design a liquidation bot that competes profitably without taking bad inventory risk.
Solution
Solution of Interview question 23.6.
Monitor health factors from the chain’s state and pending oracle updates; simulate each liquidation with the collateral’s sale path and gas; fund with a flash loan and sell in the same transaction so no inventory is carried; bid for position through bundles only up to the expected profit; and cap exposure to collateral that cannot be sold at once.
What the interviewer is looking for: atomic funding and disposal, and bidding discipline.