T4 · DeFi Engineer
Move beyond implementing a mechanism to explaining when it loses money and who absorbs the losses.
For financial engineering.
“T4” here means this track. Linked “Chapter T22” means a course chapter; Chapter T4 covers RPC.
Who This Track Serves
Your AMM passes numerical tests but has never faced a 40% one-block decline. Slippage, fees, deposits, and withdrawals work; you do not know how to test extremes.
You know protocol names but not their risk structures. Lending liquidates, perpetuals charge funding, AMMs have impermanent loss—but who bears risk and who pays remains unclear.
You write formulas but cannot justify parameters. Collateral ratios of 75% or 80%, liquidation bonuses of 5% or 8%, and utilization kinks of 80% or 90% are copied from other protocols.
Testing assumes normal markets. Stable prices, sufficient liquidity, and timely liquidators all fail together during incidents.
The dividing line: deliver an explanation of bad-debt conditions and who absorbs them, plus its implementation.
Prerequisites
Part A explains why; Part B implements how. T19's joint dependencies on Chapter 14 and T12 reflect this.
- Chapters 14–15
- Chapters 16–18
- Chapter T9
- Chapter T12
- Chapter T19
- Chapter T20
- Chapter T21
- Chapter T22
- Chapter T23
| Required reading | Graph rationale |
|---|---|
| Chapter 14 · DEXs | T19 prerequisite: implement a market rather than bare mathematics |
| Chapter 15 · Liquidity | Recoverable money underpins every risk discussion |
| Chapter 16 and Chapter 18 | T22/T23 prerequisites: credit becomes liquidation, leverage creates feedback |
| Chapter T9 · ERC Standards | T19 prerequisite; tokens may violate standard assumptions |
| Chapter T12 · Testing & Deployment | T19 prerequisite; financial tests need mainnet forks rather than fictional markets |
| Chapter T19 and Chapter T20 | Constant-product code; separate quoting, routing, and execution |
| Chapter T21 · Oracle | T22 prerequisite; prices precede liquidation |
| Chapter T22 and Chapter T23 | Liquidation and risk engines underpin the deliverable |
Chapter T24 · MEV is strongly recommended: ordering markets reprice every liquidation reward and quote update.
What You Will Learn
- AMM
- CLMM
- Order Book
- Lending
- Perp
- Oracle
- Risk Engine
Seven topics form three groups and a final integrating layer.
1. Trading Venues: How Prices Form
These are different solutions under different constraints rather than successive technology generations. Choose for an asset pair and chain cost structure, explaining tradeoffs.
| Structure | Price formation | Maker risk | Suitable conditions |
|---|---|---|---|
| Constant product | Passive reserve ratio | Inventory shifts from price changes | Long-tail assets without active makers |
| Concentrated liquidity | Reserve ratio within ranges | Inventory shifts and no fees outside range | Correlated pairs prioritizing capital efficiency |
| Order book | Active quotes | Stale quotes being taken | Cheap matching with professional makers |
Concentrated-liquidity implementation requires ranges, ticks, crossing state, and range-based fee accounting. Translating floating-point intuition into precise fixed-point integers is harder than the mathematics.
2. Credit and Leverage: Who Bears Risk?
Lending safety rests on liquidation speed rather than elegant interest models. Implement:
- Health definitions and update timing: interactions or external triggers.
- Bonuses high enough for liquidators without excessive user losses, varying with gas and depth.
- Bad-debt allocation: insurance, proportional LP losses, or socialization.
- Perpetual margin modes, funding convergence, mark versus index prices, and automatic deleveraging.
Liquidation cascades conclude this group: sales lower prices and trigger more liquidations. Reproduce the loop and measure insurance consumption.
3. Oracles: Why Trust the Price?
Oracles are common single dependencies. Define checkable trust conditions: updates, deviation limits, heartbeat timeouts, and stale-data fallbacks.
Calculate manipulation costs and extractable protocol value yourself. Compare both to assess safety.
4. Risk Engines: A System That Refuses
A risk engine is a responsibility: prevent execution from entering unacceptable states. It controls limits, margin, concentration, price validity, and refusals of otherwise valid transactions.
This separates the deliverable from a working demo.
Final Deliverable
A trading or lending protocol with a risk engine.
The Capstone Project covers a full system. This focuses on protocol behavior under extreme markets. Without a risk engine, it is incomplete.
Others can run it. Install dependencies and run all tests, including forks, with one command each. State fork chain, height, and rationale, usually real liquidity.
Include a locally runnable extreme-market script showing crash behavior.
The risk engine refuses and records refusals. Cover stale prices, excessive deviation, per-action limits, concentration, and inadequate health.
Construct and test each state with distinguishable reasons. An engine that always accepts provides no protection.
Perform a complete extreme-market drill. Model a severe one-block drop; record liquidatable positions, timely liquidations, and bad debt.
Explain who bears that debt and in which order. Otherwise part of the protocol is undesigned.
Calculate oracle attack costs. Specify pricing, capital requirements, required duration, and extractable value.
If profitable, change pricing or explicitly document exclusion and loss bearers. Acknowledged limits are professional; ignored limits are not.
Justify parameters. Explain collateral ratios, bonuses, rate kinks, and funding coefficients through volatility, depth, and liquidation-delay assumptions.
References are allowed, but explain why their assumptions hold here.
Complete a testnet cycle first, then use small bounded mainnet funds. Testnet delivery with complete parameter arguments is acceptable.
Assess Your Readiness
Within one transaction, buy heavily to raise the pool price, borrow against inflated collateral, then unwind.
One block and one transaction prevent price recovery; instantaneous checks pass. Flash loans reduce principal requirements to near zero beyond fees.
Use time-weighting, independent sources, or cross-block constraints. Time-weighting has a cost: lag delays liquidation in fast markets.
Liquidator costs include gas and ordering premiums; rewards must exceed them.
Depth determines slippage when selling collateral and required buffers.
Volatility during execution delay determines the remaining safety margin.
Excess rewards increase user losses and encourage manufacturing liquidation conditions. The answer is a range. Bonus: explain adaptation to gas and markets through timelocked parameter updates.
It pressures prices toward spot. When perpetuals trade above spot, longs pay shorts, making long exposure more expensive. This is economic pressure rather than force.
One-sided markets can sustain premiums despite funding when expected gains are larger. Liquidity exhaustion breaks arbitrage when spot borrowing or depth is unavailable; funding then merely transfers money.
Margin, liquidation thresholds, and automatic deleveraging protect extremes; funding handles ordinary convergence.
Fixed-point precision and rounding direction.
Ticks discretize exponential prices; liquidity, accrued fees, and crossing transitions rely on integers. One-unit errors accumulate into exploitable money across millions of trades.
Follow Chapter T28: round in the protocol's favor. Fuzz invariants such as assets covering all claims rather than reviewing divisions manually.
Check:
- Concentration risk: can an oversized position still be liquidated normally?
- Can the deposit disappear at once, and what dependent functions fail?
- Do limits address participant share or only single actions?
Per-action limits overlook accumulated risk.
Common Mistakes
“Correct Numerical Tests Mean Correct Mechanisms”
Unit tests verify chosen inputs. Incidents arise from combined states: prices, liquidity, and absent liquidators.
Use stateful invariants and extreme scenarios. Numerical tests are a floor.
“Mature Protocol Parameters Are Safe Here”
Parameters encode volatility, gas, liquidator ecosystems, and depth. These change across environments.
Document assumptions and test their failure. Timelocked adjustability matters more than one perfect initial choice.
“No Explicit Oracle Means No Oracle Risk”
Any referenced price, including your reserve ratio or another protocol's quote, is an oracle with a manipulation cost.
Calculate price origin and attack cost using Chapter T21.
“Correct Liquidation Code Guarantees Liquidation”
External participants must act. Code only guarantees success if they arrive; high gas, ordering competition, and tied-up capital coincide during stress.
Design incentives for liquidators and simulate delays of N blocks against insurance capacity.
Next Steps
- Reread with your protocol: Chapter T21, Chapter T22, Chapter T24.
- Apply Chapter T29 · Protocol Security's attack-cost table after choosing parameters.
- Combine Track T5 · Security Engineer for verified risk controls, Track T1 · EVM Engineer for implementation depth, and Track T3 · Onchain Data Engineer for evidence-based parameters.
- Cross into Track N1 · Crypto Research & Investment: you distinguish designed numbers from market outcomes.
- Build a complete product through the Capstone Project.