DeFi Protocol Engineering
The difference between an AMM demo and a protocol is explicit economics under adverse price movement, adversarial ordering, and imperfect liquidity.
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
| System | Implementation concern | Scenario to simulate |
|---|---|---|
| Money market | Kinked utilization curve, reserve factor, accrual timestamps, caps | Utilization moves from 80% to 100%; withdrawals queue or fail safely |
| ERC-4626 vault | share/assets conversion, virtual shares/assets, strategy loss, fees | First deposit, donation, loss, and decimal mismatch |
| Constant-product AMM | fees, reserve update, slippage, deadline, min-out | Sandwich attempt and zero/near-zero liquidity |
| Concentrated liquidity | ticks/ranges, fee accrual, active management | Price leaves range; LP becomes single-sided |
| Stable pool | depeg assumptions and invariant amplification | One asset loses 30% of value |
3. Integration policy
- Prefer maintained protocol interfaces/periphery over copying a protocol core.
- Fork-test against pinned real contracts. Document addresses, code hash/version, and the exact fork block.
- Every user-facing swap has
amountOutMinimum, deadline, and displayed price impact; every borrow/lend path has caps and clear oracle policy. - Model governance, emissions, and incentive programs as variable external conditions—not guaranteed yield.
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.
- Run
labs/phase-22-lending/scripts/emissions_sim.py— export CSV of weekly emission vs locked weight. - Document who can change emissions, timelock delay, and emergency pause.
- Simulate mercenary liquidity: users deposit for rewards, exit when emissions drop.
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.
- Read Uniswap v4 hook examples; identify which callbacks are untrusted.
- Fork-test against v4 pool manager on your target testnet when deployed; pin address in lab README.
- Default policy: treat hook contracts as full reentrancy + oracle manipulation surface.
4. Practical lab — isolated lending market
- Build a two-asset market with supplied collateral, borrowed asset, utilization-based interest, caps, partial liquidation, and a pause path.
- 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.
- Mirror the critical transitions in Solidity. Write handler invariants for solvency, accounting conservation, caps, and liquidation eligibility.
- Fork-test one real ERC-20 and a price feed. Test stale/depegged feeds and a 50% price move.
- Write a risk parameter sheet: why each threshold exists, allowed range, administrator, timelock, and emergency response.
5. Practical lab — safe AMM caller
Lab repo: labs/phase-22-lending/ — SimpleMarket solution + emissions simulation.