web3.path

PHASE 22 mechanism design · 18–28 hours

DeFi Protocol Engineering

The difference between an AMM demo and a protocol is explicit economics under adverse price movement, adversarial ordering, and imperfect liquidity.

Goal — model, implement, simulate, and falsify a small lending market and AMM integration before any public deployment.

1. Lending accounting

collateralValue = collateralAmount * collateralPrice / 10**collateralDecimals
debtValue       = debtAmount * debtPrice / 10**debtDecimals
healthFactor    = collateralValue * liquidationThreshold / debtValue

# liquidatable iff healthFactor < 1
# liquidatorRepayment ≤ debtValue * closeFactor
# collateralSeized includes a bounded liquidation bonus

Distinguish LTV (borrow limit), liquidation threshold (risk boundary), close factor (how much debt can be repaid at once), and liquidation bonus (incentive). State rounding direction for each conversion. Model bad debt: an oracle recovery is not guaranteed to make a position solvent.

2. Rate curves, vaults, and pools

SystemImplementation concernScenario to simulate
Money marketKinked utilization curve, reserve factor, accrual timestamps, capsUtilization moves from 80% to 100%; withdrawals queue or fail safely
ERC-4626 vaultshare/assets conversion, virtual shares/assets, strategy loss, feesFirst deposit, donation, loss, and decimal mismatch
Constant-product AMMfees, reserve update, slippage, deadline, min-outSandwich attempt and zero/near-zero liquidity
Concentrated liquidityticks/ranges, fee accrual, active managementPrice leaves range; LP becomes single-sided
Stable pooldepeg assumptions and invariant amplificationOne asset loses 30% of value

3. Integration policy

3b. Protocol economics & ve-tokenomics

Governance tokens, emissions schedules, and vote-escrow (ve) models change utilization and liquidity over time—not just smart-contract logic.

3c. Uniswap v4 hooks

v4 moves pool logic into hooks (before/after swap, liquidity change). Integrators must understand hook permissions and reentrancy surface—not just the v3 periphery.

4. Practical lab — isolated lending market

Deliverable
  1. Build a two-asset market with supplied collateral, borrowed asset, utilization-based interest, caps, partial liquidation, and a pause path.
  2. Make a Python/Rust simulation that replays random deposits, borrows, repayments, price shocks, and liquidations. Export equity, utilization, bad debt, and liquidation outcomes to CSV.
  3. Mirror the critical transitions in Solidity. Write handler invariants for solvency, accounting conservation, caps, and liquidation eligibility.
  4. Fork-test one real ERC-20 and a price feed. Test stale/depegged feeds and a 50% price move.
  5. Write a risk parameter sheet: why each threshold exists, allowed range, administrator, timelock, and emergency response.

5. Practical lab — safe AMM caller

Deliverable — do not build an exchange first. Build a router client that quotes, simulates, sends a slippage/deadline-bounded transaction, records the execution price, and rejects a manipulated/failing quote in a fork test. Add a private-submission policy only after documenting its trust and availability tradeoff.

Lab repo: labs/phase-22-lending/SimpleMarket solution + emissions simulation.

← Phase 21Phase 23: L2, Oracle & Cross-chain Systems →