Back to Blog
How to Build Compound V2 From Scratch (18 Sections, Line by Line)
DeFiSolidityTutorialWeb3 Security

How to Build Compound V2 From Scratch (18 Sections, Line by Line)

13 min
Compound V2 is the most-forked lending protocol ever shipped. Understanding it from scratch is the prerequisite to launching anything in lending.

TL;DR — Quick Summary

  • Compound V2 is the canonical pooled-liquidity lending protocol. Rebuilt from scratch it is a collection of cToken contracts, a Comptroller that enforces cross-market risk policy, an Interest Rate Model, a price oracle, and liquidation logic.
  • Every DeFi lending protocol worth studying — Aave's early versions, Morpho, and dozens of chain-specific forks (Flux, Canto, Benqi, Cream, Hundred, many more) — traces back to Compound V2's architecture.
  • The Compound V2 module in Zealynx Academy is 18 sections, significantly deeper than the Uniswap V2 module. Expected completion time: 40-60 hours of focused work.
  • You will implement: cToken mint/redeem/borrow/repay flows, accrual-based interest math, the Comptroller's collateral factor enforcement, liquidation calculation and incentive, oracle integration, and the admin controls.
  • By the end, you can read any Compound V2 fork's diff and identify exactly what was changed — including the regressions that caused real exploits on live forks like Flux Finance and Canto v2.

Why Compound V2 Specifically

If you want to understand decentralized lending, you build Compound V2 once.
There are newer lending protocols — Aave V3 uses a different architecture (singleton with multiple assets), Morpho has peer-to-peer matching on top of pooled liquidity, Gearbox does credit accounts. Each has innovations worth studying.
But the design language of DeFi lending — cTokens, collateral factors, utilization-based interest rates, liquidation via direct incentive — originated with Compound V2 (2019) and remains the dominant pattern. Forks of V2 continue to ship on new chains. Auditors reviewing lending protocols spend most of their time on V2-family code. Founders launching lending protocols most often start with V2 as their base.
This is why the Zealynx Academy Compound V2 module is the Academy's second build module after Uniswap V2. Uniswap V2 teaches you AMM design. Compound V2 teaches you lending design.

Compound V2 Architecture

Four main contract categories make up the protocol:

cToken Contracts

One per supported asset. The cToken represents a user's share of a lending market. When you supply USDC to Compound, you mint cUSDC. Your cUSDC accumulates interest as the underlying USDC pool earns fees from borrowers. You can redeem cUSDC back for USDC plus interest.
There are two variants:
  • cErc20: for ERC-20 underlying assets (USDC, DAI, USDT, WBTC, etc.)
  • cEther: for native ETH
Both inherit from a common CToken base that defines the core mint/redeem/borrow/repay/liquidate logic.

Comptroller

A single contract that enforces cross-market policy. Each cToken refers back to the Comptroller for decisions like:
  • Can this user borrow this amount of this asset?
  • Can this user be liquidated?
  • How much collateral does this user have across all their markets?
The Comptroller holds collateral factors, close factors, and liquidation incentives as configurable parameters. Governance (originally COMP token holders) controls these.

InterestRateModel

One per cToken, or one shared across several cTokens. Given a utilization rate (borrow / supply ratio), it returns a borrow APR and a supply APR. The classic Compound V2 model is piecewise linear: low utilization = low rates, above the "kink" (typically 80% utilization) = steep rate increase.
This is the pricing mechanism that keeps the market liquid. If utilization gets too high, rates spike, attracting lenders and deterring new borrowers until utilization normalizes.

Price Oracle

Compound V2 originally used a simple price oracle that admin could update. Later deployments use Chainlink-based oracles. The oracle is consulted for collateral valuation and liquidation eligibility.

What You Build Across 18 Sections

The Compound V2 module maps to a deeper exploration than Uniswap V2. 18 sections, each with a test suite:

Sections 1-2: Introduction and Math Library

Contract overview. Implement the math library: exponential scaling for interest calculation, safe multiplication with precision preservation, the conversion between scaled and unscaled amounts.

Section 3: cToken Base Contract Scaffolding

Storage layout, state variables, events, access control. The foundation everything else builds on.

Section 4: Accrual-Based Interest Math

Compound's interest is not compounded per user action — it compounds per block. Every call to a cToken triggers accrueInterest() which fast-forwards interest from the last accrual block to the current block.
You implement:
  • blockNumber tracking
  • borrowRatePerBlock() and supplyRatePerBlock() queries against the InterestRateModel
  • The compound interest formula with proper precision
Common trap: getting the precision math wrong. Compound uses Exp and Double types for fixed-point arithmetic with 18 and 36 decimals respectively. Mixing these up causes systematic interest drift.

Sections 5-6: Mint and Redeem

Supply flow:
  1. User calls mint(amount) on cUSDC.
  2. cUSDC transfers USDC from user to itself.
  3. cUSDC mints new cUSDC tokens to user at the current exchange rate (cUSDC : USDC).
  4. Exchange rate grows over time as interest accrues.
Redeem is the reverse.
Common trap: the exchange rate must be computed before the state changes of the mint. If you compute it after, new minters receive bonus cUSDC at the old rate while the contract holds new USDC.

Sections 7-8: Borrow and Repay

Borrow flow:
  1. User calls borrow(amount) on cDAI (assumes they've already supplied collateral).
  2. cDAI asks the Comptroller: "can this user borrow this much?"
  3. Comptroller checks collateral factor across all markets.
  4. If allowed, cDAI increases user's borrow balance and transfers DAI out.
Repay is the reverse.
Common trap: the borrow balance stored is in "principal" units that must be scaled by the current borrow index. Forgetting the scaling means stale borrow balances that can be exploited.

Sections 9-11: The Comptroller

Section 9: core Comptroller scaffolding — market registry, user entered markets. Section 10: liquidity calculations — iterating all markets a user is in, computing total collateral value, total borrow value. Section 11: liquidation eligibility — is this user's collateral value less than their borrow value?
Common trap: reentrancy across cToken calls when iterating markets. The Comptroller reads multiple cToken states; if a malicious cToken is added that can call back into the Comptroller during read, cross-contract reentrancy attacks become possible.

Sections 12-13: Liquidation

When a user becomes undercollateralized, anyone can liquidate them:
  1. Liquidator calls liquidateBorrow(borrower, repayAmount, collateral cToken).
  2. Liquidator repays repayAmount of borrower's debt on one market.
  3. In exchange, liquidator receives collateral from a different market at a discount (the liquidation incentive, typically 5-8% below market price).
  4. Close factor limits how much of a single position can be liquidated in one transaction (typically 50%).
Common trap: the math for converting "amount of borrowed asset repaid" to "amount of collateral seized" must use oracle prices for both, apply the liquidation incentive, and round carefully. Rounding in favor of the liquidator loses protocol value; rounding against makes liquidations unprofitable and undermines the system.

Section 14: Oracle Integration

The cToken queries the oracle for collateral valuation. In real Compound V2, the oracle is pluggable — admin sets an IComptroller.oracle interface. Implementing this correctly means accepting that the oracle is a trusted input. Bad oracle → bad liquidations → protocol insolvency.

Section 15: Admin and Governance

Admin functions: setting the interest rate model, adding new markets, adjusting collateral factors, pausing specific actions. In production, these are gated by the Comptroller's admin, usually a timelock backing governance.

Section 16: Events and Accounting Sanity

Every state change emits events for off-chain indexing. You verify that events are consistent with state — no silent state changes.

Section 17: Cross-Market Scenarios

Multiple users in multiple markets, borrowing across them, some liquidatable, some not. You test that the Comptroller handles all the interactions correctly.

Section 18: Final Build + Test Suite

The complete protocol. Full test suite runs end-to-end. You do not finish until all tests pass.

Build the protocols. Find the bugs.

Free, hands-on Web3 academy. Build Uniswap V2 / Compound V2 / Yearn V2 from scratch. Audit real protocols in Shadow Arena.

No spam. Unsubscribe anytime.


What Distinguishes Forks

The interesting part of Compound V2: the original is clean. Most of the exploited bugs in Compound V2 forks are in the modifications. Specific patterns:
Custom interest rate models. Canto v2 introduced a custom rate model with edge cases not present in Compound's original. Several of Canto v2's documented Shadow Arena findings trace to this.
KYC / compliance checks. Flux Finance added KYC gating. The KYC check itself was sometimes bypassable, or had unexpected interaction with liquidation logic.
Oracle switches. Some forks swapped Chainlink for a custom oracle. Custom oracles have unique bugs not present in the vetted versions.
Collateral factor changes via governance. Setting collateral factors too permissively (e.g., 90% on volatile assets) means protocols become insolvent after small price moves.
New asset additions. Fee-on-transfer tokens, rebasing tokens, and tokens with unusual transfer semantics break assumptions Compound V2 made about standard ERC-20 behavior.
When you have built Compound V2 from scratch, you see the fork's diff instantly. "They changed the rate model here" or "they added a pause modifier but forgot to include it on the borrow path" — these become obvious observations rather than deep-scan work.

Why This Matters for Forks You Might Ship

If you are planning to fork Compound V2 to launch a lending protocol, the build module is the prerequisite to doing it safely.
Specific things you will understand afterward:
  • When is an interest rate model change safe vs dangerous. You will have implemented the default model and seen how it interacts with borrow/supply dynamics. Custom models that diverge need careful analysis.
  • Collateral factor calibration. You will understand the math connecting collateral factor, price volatility, and solvency. Setting it too high leads to insolvency after moderate price drops.
  • Liquidation incentive economics. You will understand how the incentive needs to be high enough to attract liquidators even during gas spikes, but low enough to not punish borrowers excessively.
  • Oracle dependencies. You will have felt how deeply the protocol trusts its oracle. Custom oracles are dangerous because the protocol's safety depends on them entirely.
  • Admin access risks. You will have built the admin functions and seen what they can do. You will think hard about timelock delays and multisig controls.
This is what enables an informed fork vs a naive one. The Academy is structured around producing the former.

Then: The Shadow Arena

After the Compound V2 build, enter the Shadow Arena. Two targets are live in the lending category:
  • Flux Finance — Compound V2 fork with KYC/sanctions checks. Beginner-level, 2-day window, 6 documented bugs. The bugs cluster around the KYC modifications.
  • Canto v2 — Compound V2 fork with algorithmic stablecoin (cNote) and custom interest rate model. Intermediate-level, 4-day window, 10 documented bugs. Described by its audit report as "almost a syllabus for what goes wrong when you fork Compound V2."
By the time you have done both, you have seen real fork-specific bugs. When you come to ship your own fork, you ship with the pattern recognition to avoid those classes.

How to Start

Open academy.zealynx.io/modules/compound-v2. The module is ~18 sections. Plan for 40-60 hours of focused work over 2-4 weeks.
Prerequisites:
  • Uniswap V2 module completed (or equivalent AMM knowledge). Compound V2 builds on patterns you first see in Uniswap V2.
  • Basic Solidity fluency — functions, mappings, events, modifiers, inheritance.
  • Basic understanding of ERC-20 tokens.
Recommended pace: one or two sections per session, with time between sessions to let concepts consolidate.

Supporting Infrastructure Work

Zealynx Academy is part of the Giveth Ethereum Security QF round backed by TheDAO Security Fund's 500 ETH matching pool. The round runs April 21 – May 12, 2026. Every unique donor unlocks meaningfully more matching than large donors. If the expansion of Web3 lending education matters to you — through the Compound V2 build module or the broader platform — a $5 donation compounds. Details here.

Conclusion

Compound V2 is the canonical lending design. Understanding it from scratch is the prerequisite to launching anything in the lending category safely. The 18 sections in Zealynx Academy's module are structured to produce that understanding the fastest way I know how: guided scaffolding, function-by-function builds, and test suites that verify correctness at every step.
By the end, you can read any Compound V2 fork's diff and know exactly what to worry about. That is what a builder about to ship a lending protocol needs.
Start the Compound V2 module: academy.zealynx.io/modules/compound-v2

FAQ

1. How long does the Compound V2 module take?
40-60 hours of focused work, typically spread across 2-4 weeks. Significantly longer than Uniswap V2 because the protocol is more complex.
2. Should I do Uniswap V2 before Compound V2?
Yes, strongly recommended. Uniswap V2 introduces patterns (scaffolded builds, test-driven verification, the Zealynx Academy workflow) that transfer directly. It is also a simpler protocol, which makes it a better first experience with the build-from-scratch methodology.
3. Is Compound V2 still relevant if I want to build on newer protocols?
Yes. Compound V2's design vocabulary is the foundation for understanding Aave, Morpho, Gearbox, and many others. Even if you never ship a V2 fork, the patterns you learn transfer. Forks of V2 remain the most common lending protocol pattern in 2026.
4. What's the difference between Compound V2 and V3?
Compound V3 is a major architectural redesign. Each V3 market has one borrowable asset and a set of collateral-only assets — fundamentally different from V2's symmetric cToken-per-market design. V3 also uses different math and a different oracle approach. V2 remains the widely-forked version; V3 is Compound Labs' own current deployment.
5. Can I skip sections I already know?
The module is designed as a sequence because later sections depend on earlier ones. However, you can move quickly through sections you find straightforward. The test suite gates progression, so you cannot skip without demonstrating that your implementation works.
6. What if I want to fork Compound V3 instead?
Build V2 first to understand the lending fundamentals, then study V3 separately. A V3 module may come to the Academy in the future. For now, the jump from V2 understanding to V3 analysis is manageable with the V2 foundation in place.

Glossary

TermDefinition
Compound (V2)Compound Finance V2, the canonical pooled-liquidity lending protocol, launched in 2019. Most-forked lending contract in DeFi history.
cTokenA token representing a user's share of a Compound V2 lending market. Supplying USDC mints cUSDC; cUSDC grows in value as the pool earns interest.
Interest Rate ModelThe contract that computes borrow and supply rates from market utilization. Typically piecewise linear with a kink at ~80% utilization.
Collateral FactorThe percentage of a collateral asset's value that can be borrowed against. Set per market by governance. Higher values increase capital efficiency but also insolvency risk.
Shadow AuditA training exercise where you audit a past security contest on a known-graded protocol fork, scored against the actual contest findings.

Build the protocols. Find the bugs.

Free, hands-on Web3 academy. Build Uniswap V2 / Compound V2 / Yearn V2 from scratch. Audit real protocols in Shadow Arena.

No spam. Unsubscribe anytime.