Section 18 of 18

Final Build
+100 Lynx

Complete Lending Protocol

Final Build

Submit your complete protocol and run the full test suite. Earn the "compound-v2-builder" badge on completion.

What You Built

You just wrote a complete lending protocol. Not a simplified tutorial version. The actual architecture that powered Compound V2, held over $10 billion in deposits, and was forked by Aave V2, Venus, Benqi, Cream, Iron Bank, and dozens of others. Every function you implemented has a direct counterpart in the deployed Compound V2 contracts on Ethereum mainnet.

Here is the full inheritance chain you built, from bottom to top:

ExponentialNoError (fixed-point math)
  -> CTokenStorage (state variables, events, interfaces)
    -> CTokenInterest (accrueInterest, exchangeRate, borrowBalance)
      -> CTokenMint (supply underlying, receive cTokens)
        -> CTokenRedeem (burn cTokens, withdraw underlying)
          -> CTokenBorrow (take out loans against collateral)
            -> CTokenRepay (return borrowed tokens, reduce debt)
              -> CTokenLiquidate (seize collateral from underwater positions)
                -> CErc20 (public entry points, ERC-20 transfers, initialization)

And the risk engine:

ExponentialNoError
  -> ComptrollerMarkets (market registry, enter/exit markets)
    -> ComptrollerLiquidity (cross-market solvency calculation)
      -> ComptrollerHooks (policy enforcement: mint/redeem/borrow/repay/liquidate/seize/transfer)

Compound V2 vs Uniswap V2: Architecture Comparison

ConceptCompound V2Uniswap V2
Share tokencToken (represents claim on pool + accrued interest)LP token (represents claim on reserves)
Value accrualExchange rate grows as borrowers pay interestReserve ratio changes as swaps pay fees
Share price formula(cash + totalBorrows - totalReserves) / totalSupplyreserve0 / totalSupply (for one side)
Depositmint() in CErc20mint() in Pair
Withdrawredeem() in CErc20burn() in Pair
Risk engineComptroller (cross-market solvency checks)None (each pair is independent)
Policy hooksmintAllowed, borrowAllowed, redeemAllowed, etc.None (Uniswap V4 adds hooks)
Interest modelJumpRateModel (kink-based, utilization-driven)No interest (fees are per-swap)
LiquidationliquidateBorrow + seize (8% incentive, 2.8% protocol)None (no lending, no debt)
Oracle dependencyRequired (Comptroller uses prices for solvency)Built-in TWAP (optional, not required for core)
Token transfer safetydoTransferIn with balance check (fee-on-transfer safe)_safeTransfer with low-level call (non-compliant safe)
Reentrancy guard_notEntered boolean in nonReentrant modifierunlocked variable in lock modifier

Key Concepts You Now Understand

Lazy interest accrual via borrowIndex: Instead of iterating over all borrowers every block, the protocol maintains a global accumulator. Each user's debt is computed on demand by comparing their snapshot to the current index. This is the same principle as Uniswap's cumulative price oracle.

Cross-market risk management: A user's ETH collateral in one market backs their USDC borrow in another. Only the Comptroller, with its global view, can make solvency determinations. This is fundamentally different from Uniswap, where each pair operates independently.

Hypothetical liquidity checks: Before every risky operation, the Comptroller simulates the outcome. "What if this user redeemed 100 cETH?" or "What if this user borrowed 500 more USDC?" If the hypothetical result shows shortfall, the operation is rejected.

The liquidation incentive loop: Underwater positions are liquidated by third parties competing for profit. The 8% incentive minus the 2.8% protocol cut creates a self-sustaining system where the protocol never needs to run its own liquidation infrastructure.

Fee-on-transfer safety: The before/after balance check in doTransferIn ensures the protocol accounts for actual received amounts, not requested amounts. This pattern appears in production Compound V2 and in Uniswap V2's Router.

What You Can Do Next

Shadow Arena: Test your understanding against real audit findings. The Shadow Arena presents historical vulnerabilities found in lending protocol audits. Try to identify the bugs before the timer runs out.

Advanced topics: Compound V2 has features we did not build in this module. Governance (COMP token distribution), flash loans (borrowing without collateral within a single transaction), and admin functions (setting reserve factors, adding new markets). Each of these extends the architecture you already understand.

Other protocols: With this foundation, you can read and understand any overcollateralized lending protocol. Aave V2 follows a nearly identical pattern with different naming conventions. Aave V3 adds efficiency modes and isolation modes on top of the same core.

Verify Your Understanding

In a liquidation, what percentage of the seized collateral goes to the protocol as reserves?

A small percentage. Think about protocol revenue from liquidations.

Your Complete Protocol

Solution.sol
Solidity
Loading editor...