Section 5 of 18
CToken: Exchange Rate and Interest Accrual
Key takeaway: Compound V2 accrues interest in O(1) per market via a global
borrowIndexplus a per-account snapshot of the index when the user borrowed. To compute a borrower's current debt, the protocol reads their snapshot, reads the current index, and divides; no iteration over borrowers is ever needed. This is what lets Compound V2 scale to hundreds of thousands of borrowers without gas-griefing on every accrual call. The snapshot pattern repeats in any protocol that needs fair interest distribution at scale.
What You Are Building
This section adds the two most fundamental functions in the CToken: exchangeRateStoredInternal() and accrueInterest(). Every other operation in the protocol (mint, redeem, borrow, repay, liquidate) depends on these being correct. They are the heartbeat of the lending market.
You will also build borrowBalanceStoredInternal(), which uses the BorrowSnapshot pattern to compute a borrower's current debt, and getAccountSnapshot(), which the Comptroller uses for liquidity calculations.
Your Code
Requirements
Sign up free — keep reading + earn 15 Lynx
Zealynx Academy is free. Track your progress, earn Lynx, and climb the leaderboard.
Sign up free to continueAlready have an account? Log in