Kirill Naumov
Kirill Naumov

@kinaumov

51 Tweets 12 reads Jun 10, 2022
Back to the Basics: Compound, Aave
Compound and Aave built the foundation for DeFi money markets so knowing the formulas behind them is crucial to evaluating new lending products. In this thread I’ll summarize exactly how they work. Try to follow the math, it’s interesting
1/46
While some people may be familiar with the general concepts of how these lending platforms work, few can explain the gigabrain formulas. It may get complex fairly quickly, so feel free to pause or skip parts of the thread.
Let’s get into it!
2/46
Originally, lending on Ethereum was facilitated via peer-to-peer marketplaces. However, matching user deposits with borrow requests was inefficient due to having to negotiate duration, collateral, and the interest rates. Because of that, p2p lending didn’t get much traction
3/46
In September 2018, @rleshner and @justHGH launched @compoundfinance, an algorithmic decentralized money market protocol. Compound allows users to lend and borrow from a pool, where the interest rate is based on the proportion of the pool reserves lent out.
4/46
Compound aggregates the supply of users and lends it out on demand. When users deposit into a pool, they receive a number of ERC-20 cTokens, which are a claim to a portion of the total pool. When the pool earns interest, the amount a user can claim with their cTokens grows
5/46
Users can borrow from the protocol using their cTokens as collateral. Assets have different collateral factors, which are regularly adjusted via governance. Check out the most recent proposal by @gauntletnetwork here
6/46
compound.finance
The total of a user’s underlying token balances, multiplied by the collateral factors, is their borrowing capacity. When a user borrows funds, they lock a portion of their cTokens so that they are unable to transfer them and/or redeem the collateral.
7/46
If a user’s outstanding borrowing exceeds their borrowing capacity due to volatility of asset prices, up to a fixed percentage of the outstanding borrowing may be repaid by another user in exchange for the first user’s cToken collateral (with a liquidation discount).
8/46
How does the protocol remain solvent if, let’s say, all of the deposited USDC is lent out to borrowers and someone wants to withdraw? It’s all in the interest rate model. Let’s get into the formulas.
9/46
First, an important concept to understand is utilization. Utilization (U) for each market (a) is the percentage of a given asset that is lent out with respect to the entire supply of the asset in the pool. The interest rates in the protocol revolve around utilization.
10/46
The interest rate on borrows is calculated as a function of Utilization, which is set via protocol governance. For most volatile markets, like ETH, the interest rate for borrowers is a linear function.
11/46
For assets which are most borrowed (stablecoins), the protocol uses a piecewise function with an optimal utilization rate, beyond which the interest rate grows faster. At high APY, users are incentivized to deposit more, ensuring there is always liquidity for withdrawals
12/46
Mathematically, the curve looks like this. The total borrow rate is composed of the rate at zero utilization (intercept) plus the one or two utilization slopes.
The interest rate offered to depositors is simply the borrow rate multiplied by the utilization. This makes the amount earned from borrowers equal to the amount paid to depositors. For simplicity, the formula I show here doesn’t include protocol fees.
14/46
Anyone can check Compound interest rates functions for different tokens by going to
compound.finance
15/46
Now to more complex stuff. How does the protocol track balances?
Each time a transaction occurs, the protocol records a new Interest Rate Index value for borrowers. Instead of refreshing the state every block (consumes too much gas), we can just timestamp specific values.
16/46
We can obtain a new index value multiplying the old one by the interest rate and the elapsed time. So, for example, we start with an index value of 1, then have 1 month of 12% APY, then 2 months of 6% APY and end up with
1 * (1 + 0.12 * 1/12) * (1 + 0.06 * 2/12) = 1.0201
17/46
When a transaction occurs (interest is fixed if nothing changes in the pool), the Interest Rate Index for the asset (a) is updated using the interest for the elapsed period, denominated by r * t
18/46
The total borrowing outstanding in a given asset (a) is updated to include interest accrued since the last index:
19/46
From this value, we can calculate total amount owed to depositors as
Borrows + Cash = Total Deposits
The formula gets slightly more complex if we account for fees that go to the reserve but that’s beyond the scope of this thread.
20/46
From the total amount owed to depositors, we can derive the amount of deposits (including accrued interest) of a given user as
User’s deposit = Total Deposits * user’s cTokens / Total cTokens
21/46
The amount a user (x) borrowed is stored in a data structure in the contract alongside the Interest Rate Index at that time. It’s updated each time the user borrows / repays. To calculate the current amount of asset (a) a user owes, one would use the following formula:
22/46
A Price Oracle maintains the exchange rate of every asset on the platform. These rates are used to determine borrowing capacity and collateral requirements of users, making sure they don’t borrow more than they are allowed to.
23/46
The Comptroller is the risk management smart contract of Compound. It determines how much collateral a given user is required to maintain, and whether they can be liquidated. For each user action, the Comptroller is asked to approve or deny the transaction.
24/46
Governance decisions on Compound are voted on by $COMP holders through the Governor smart contract. $COMP token-holders can delegate their voting rights to themselves, or an address of their choice. Shameless plug: delegate to @PennBlockchain :)
25/46
@AaveAave was founded as ETHLend in 2017 after raising $16.2 million in an ICO to build a decentralized peer-to-peer lending platform. It was rebranded to Aave in 2020, when they switched to a liquidity pool model. Their design is a little more complex than Compound’s.
26/46
The basics are the same: a user deposits funds, receives aTokens in return, and then can borrow funds by locking up their aTokens as collateral. However, there are a few important differences.
27/46
Primarily, aTokens aren’t the same as cTokens. Unlike cTokens, which represent a user’s share of the pool of deposits, aTokens are 1:1 to the amount deposited. Depositing 10 DAI returns you 10 aDAI. So, how does interest accrue?
28/46
This is the fun part. 1 + 1 no longer equals 2. Aave have altered the ERC-20 contract of aTokens in a way that the balance of aTokens grows without any incoming transactions.
29/46
Your balance of aTokens is composed of two elements: a super.balance (balance in the parent contract) and a Cumulated Liquidity Index, which works the same way as the Interest Index on Compound. The super.balance is fixed, but the Index grows with every Aave transaction.
30/46
Here is the implementation of balanceOf for reference.
Note: ray is a decimal number with 27 digits of precision. Aave stores its decimals in ray.
31/46
Transfer functions are implemented similarly. If you request a transfer, the amount you request is divided by the current index and transferred in the parent contract accounting system. Then the recipient’s balance is superTransferAmount * Index = transferAmount
32/46
Utilization and interest rate calculations are done the same way in Aave as in Compound, except all assets have a target utilization rate and a piecewise function.
33/46
As you may have noticed from the previous tweet, Aave has introduced stable borrow rates. Stable rates are higher than variable rates and use a Lending Rate Oracle. The stable rate uses the Market Lending Rate instead of a fixed intercept value.
34/46
Graphically, Aave money market interest rates for borrows on an individual asset look like this:
35/46
By using the variable and stable borrow rates, we can calculate the weighted average borrow rate for the pool and the liquidity provision rate, which is used to update the Index in aTokens by rate * time elapsed.
36/46
Another novel feature Aave introduced was Flash Loans. A flash loan allows technical users to borrow any amount from the reserve as long as they return it plus a fee within the same transaction. If the funds aren’t returned, the whole transaction is reverted.
37/46
More cool features… In v1, Aave supported the redirection of interest payments to another address. While this feature has been removed in v2, it can be added back via the governance process.
38/46
Aave is governed by $AAVE holders. Proposals are discussed on the Forum, then elevated to a Snapshot vote, and then voted for on-chain.
39/46
app.aave.com
The LendingPool contract is the main contract of the protocol, similar to the Comptroller for Compound. It holds the state of every asset deposited and handles basic logic.
40/46
With V3, Aave introduced several cool new features, including Portal, which allows approved bridges to burn aTokens on the source network while instantly minting them on the destination network, improving cross-chain capital efficiency.
41/46
The problem with algorithmic money markets is that they’re not permissionless. One can’t just add arbitrary assets to Compound or Aave as that puts the protocol in danger of insolvency. An attacker could infinitely inflate the price of the asset and borrow ALL liquidity.
42/46
@RariCapital aims to solve that problem. Rari allows for the permissionless creation of Compound-like money markets (Fuse pools) with arbitrary assets. Users accept the risks of the assets in the pool for higher yield rates and projects get to borrow against exotic assets.
43/46
@eulerfinance is a non-custodial semi-permissionless lending protocol. It allows the creation of borrow/lend markets for any token but limits the list of assets that can be used as collateral. They use complex oracle risk analysis strategies to whitelist collateral assets.
44/46
Money markets create the monetary foundation of DeFi and each new L1 chain needs their own. Since many new chains are EVM-compatible, most projects, instead of re-inventing the wheel, just fork Compound or Aave code.
45/46
I hope this thread gives a good in-depth overview of how DeFi money markets work, which would allow for analysis of the mechanics of newer projects on Ethereum and other chains. If you’ve learned something new, please consider giving me a follow @kinaumov
46/46
For a better reading experience, I have also posted this thread as a Medium article. Check it out here
@kinaumov/back-to-the-basics-compound-aave-436a1887ad94" target="_blank" rel="noopener" onclick="event.stopPropagation()">medium.com
This is the second thread in the Back to the Basics series. If you want to learn about the formulas behind Uniswap, Balancer, and Curve, check out my thread from last week.
Accounts you should follow to stay on top of Compound updates:
@compoundfinance, @rleshner, @justHGH, @gauntletnetwork, @getty_hill, @labsGFX, @adambavosa, @jaysonhobby, @jmflatow, @tylerether

Loading suggestions...