web3.path

PHASE 18 protocol systems · 18–28 hours

Protocol, L2, Oracle & ZK Engineering

A protocol is not a Solidity class hierarchy. It is asset accounting, market assumptions, external dependencies, and operations under adversarial inputs.

Goal — build and test a small lending/bridge-adjacent system with real safety controls, then explain the L2, oracle, and proof-system assumptions it depends on.

1. DeFi mechanics you must model

MechanismRequired modelFailure test
LendingLTV, liquidation threshold, health factor, close factor, liquidation bonus, kinked utilization-rate curvePrice gap, stale oracle, bad debt, partial liquidation
AMM swapReserves, fees, slippage, minAmountOut, deadline, price impact and routingSandwich/revert on adverse price; zero-liquidity boundary
VaultERC-4626 conversions, share rounding, fees, donation resistance, strategy lossFirst depositor, donation, loss, decimals mismatch
Stable/curve poolStableSwap or weighted invariant, depeg scenario, oracle-free vs oracle-assisted priceOne asset depegs; withdrawal queue/invariant remains safe

Read and fork-test real interfaces rather than reimplementing a popular protocol from memory. Include Aave v3 isolation/e-mode and Uniswap periphery/router behavior in the investigation; an integration has more assumptions than its happy-path ABI call.

2. Oracle policy, not just an oracle call

function checkedPrice() internal view returns (uint256) {
    (, int256 answer,, uint256 updatedAt,) = feed.latestRoundData();
    if (answer <= 0 || updatedAt == 0 || block.timestamp - updatedAt > MAX_AGE) {
        revert InvalidOraclePrice();
    }
    // Normalize feed decimals before combining with token decimals.
    return uint256(answer);
}

3. L2 and cross-chain assumptions

A sidechain is not a rollup: Polygon PoS and an L2 have different trust and exit assumptions. For each target chain, document finality, reorg depth, sequencer failure/censorship behavior, data availability, precompile differences, native gas token, fee model, and canonical bridge. Learn the chain's message interfaces (for example OP Stack cross-domain messaging) rather than treating every EVM RPC as interchangeable.

Message ruleWhy
Authenticate transport and remote senderChecking only a local endpoint permits forged payloads.
Persist message ID/nonce and consumed statePrevents replay and gives an auditable recovery path.
Rate-limit mint/release and cap supplyContains key compromise or implementation bugs.
Define ordering and retry semanticsMessages can delay, fail, arrive out of order, or be duplicated.
Monitor the full state machine“Sent” is not “delivered” and “delivered” is not necessarily “executed”.
Rule — do not write a production bridge. Use canonical bridges or a protocol with a documented trust model unless bridge security is the explicit product competency.

4. MEV and transaction policy

5. ZK: circuit correctness is security

Learn the pipeline (circuit → witness → proof → verifier) and then add the production concerns that introductory examples omit: constrain every intended relationship, test malicious witnesses, version circuit/proving/verifying-key artifacts, pin verifier keys, decide upgrade governance, and measure proving CPU/GPU/memory and queue latency.

6. Practical lab — guarded lending market

Deliverable
  1. Implement a collateralized borrowing prototype: deposit collateral, borrow a capped asset, repay, and partially liquidate. State formulas for health factor, liquidation threshold, close factor, and rounding direction in NatSpec.
  2. Use a mock Chainlink feed with stale, zero/negative, decimal-mismatch, and price-gap tests. Add an L2 sequencer-up check if deploying to an L2.
  3. Build Foundry handler invariants: debt/accounting conservation, no healthy account is liquidated, no borrower exceeds its cap, and liquidation improves health factor where mathematically possible.
  4. Fork-test token/oracle interactions; run a simulation of a 30–60% collateral drop and capture the resulting bad-debt behavior.
  5. Deploy to an L2 testnet. Make the UI submit slippage/deadline-bounded operations and expose pending, confirmed, reorged, and failed states.

7. Extension lab — proof-gated claim

Deliverable — build a Merkle-membership or preimage claim circuit; add a deliberately underconstrained version and a failing exploit test; then version the final circuit artifacts, verifier key, verifier contract address, and public-input schema in the repository. Continue in Phase 24 lab (labs/phase-24-zk/).
Track note — Phase 18 surveys protocol systems. For DeFi depth, prefer Phase 22 after this phase (see tracks).
← Phase 17Phase 19: Bitcoin Engineering →