Lending and borrowing on-chain
Suggest an editA lending protocol lets users supply an ERC-20 token to a shared pool to earn yield, and lets others borrow from the same pool by posting collateral worth more than they borrow. The core shape has been stable since Compound v1 in 2018, a pool per asset, interest set by utilization, collateral priced by oracle, liquidations triggered when a position's collateral falls below a safety threshold.
The collateral is all the protocol can take
A contract cannot check who a borrower is and cannot take them to court. If a borrower does not repay, all the protocol can take is what the borrower locked in the contract beforehand. So the collateral has to be worth more than the debt at every moment. An oracle prices the collateral, and liquidation closes a position before the collateral stops covering the debt. The interest rate has a separate job, keeping part of the pool available for suppliers who want to withdraw.
People still take such a loan, because the borrower gets USDC to spend without selling the ETH. When they repay, the ETH comes back, along with whatever it gained in price.
A supplier deposits asset X into the protocol's pool for X. In return they get a receipt token, typically called aToken on Aave or cToken on Compound. The receipt represents their share of the pool plus all interest accrued since they deposited.
This is the ERC-4626 vault pattern with one specific yield source. When a borrower repays, their interest payment goes into the pool, and every supplier's receipt-token-to-asset conversion rate grows accordingly.
A supplier can redeem their receipt tokens for the underlying asset at any time, as long as there is enough liquidity in the pool. If borrowers have taken out 95% of the pool's assets, a supplier who wants to withdraw 10% of the pool cannot, until either some of those borrowers repay or new supply arrives. This constraint is the central piece of the interest rate model.
Borrowers post collateral and owe a growing debt
A borrower deposits collateral, then takes out a loan against it. The collateral is typically a different asset from the loan, for example deposit ETH as collateral and borrow USDC against it. Posting collateral and borrowing happen in the same contract, and the protocol tracks each user's collateral and debt positions in a single account.
The amount that can be borrowed is bounded by the Loan-to-Value ratio, abbreviated LTV. For ETH on Aave, the LTV might be 80%. With 1 ETH deposited as collateral while ETH trades at $3,000, a borrower can take out up to $2,400 worth of USDC.
The borrow position pays interest, and the interest compounds the debt itself. A borrower who took out 2,400 USDC today owes 2,400 USDC plus accrued interest at any later time.
The protocol cannot add that interest by looping over every borrower, because the gas would grow with the number of positions. It keeps one shared number per asset, a borrow index that grows with the interest rate. Each position stores its debt together with the index value at its last update, and the current debt is the stored debt multiplied by the growth of the index since then. The supply side works the same way, with the receipt token's conversion rate as the shared number. This is the running total from the TWAP lesson, applied to interest.
A minimal version in Solidity, where ratePerSecond is the borrow rate per second and both it and borrowIndex are scaled by 1e18, so 1e18 stands for 1.0:
uint256 public borrowIndex = 1e18;
uint256 public lastAccrual = block.timestamp;
mapping(address => uint256) public debtAtLastUpdate;
mapping(address => uint256) public indexAtLastUpdate;
function accrueInterest() public {
borrowIndex += borrowIndex * ratePerSecond * (block.timestamp - lastAccrual) / 1e18;
lastAccrual = block.timestamp;
}
function debtOf(address user) public view returns (uint256) {
if (indexAtLastUpdate[user] == 0) return 0;
return debtAtLastUpdate[user] * borrowIndex / indexAtLastUpdate[user];
}The contract calls accrueInterest at the start of every borrow and repayment, then stores the position's new debt together with the current borrowIndex. Say Alice borrows 1,000 USDC when the index is 1.0, and Bob borrows 1,000 USDC after interest has raised it to 1.1. When the index reaches 1.21, debtOf gives 1,000 × 1.21 / 1.0 = 1,210 for Alice and 1,000 × 1.21 / 1.1 = 1,100 for Bob, though neither position was written in between.
A position has a health factor that measures distance from liquidation:
health = (collateral_value × liquidation_threshold) / debt_valueWhen health >= 1, the position is safe. When health < 1, the position is liquidatable. Anyone can step in to repay part of the borrower's debt in exchange for a share of the collateral at a discount. A position with several collateral assets adds them up, each weighted by its own liquidation threshold.
The liquidation threshold sits slightly above the LTV. For ETH, the LTV might be 80% and the liquidation threshold 85%. That gap is the safety buffer. A user who borrows the maximum allowed cannot be liquidated immediately. The collateral value would have to fall by about 6% before they hit the liquidation threshold.
The rate rises with utilization so that suppliers can withdraw
The pool's interest rate is a function of utilization. Utilization is the fraction of the pool currently borrowed:
U = totalBorrows / totalSupplyAt U=0, no one is borrowing. Suppliers can withdraw anything they want, and rates are low because there is no demand for borrows. At U=1, everything is borrowed and no supplier can withdraw. Rates spike because the protocol needs to either attract more supply or push some borrowers to repay.
The dominant model since Compound v1 is the kink model. From U=0 up to a kink point typically at U=80%, the rate grows linearly from a low base rate to an optimal rate of around 4%. From U=80% up to U=100%, the rate grows much more steeply, hitting 100% or higher at full utilization. The kink point is where the model considers utilization healthy. Above it, the model penalizes borrowing aggressively and rewards new supply.
The curve only creates an incentive. During DeFi panic moments, large suppliers withdrawing at once can drive a healthy pool to 100% utilization within minutes. The suppliers who remain earn high paper yields they cannot realize until borrowers repay or new supply arrives.
Borrowers pay interest only on the borrowed part of the pool, and that interest is spread over the whole pool after the protocol takes its cut. So the supply rate is:
supplyRate = borrowRate × utilization × (1 − reserveFactor)The reserve factor, typically between 10% and 25%, is the protocol's cut. It builds a treasury that can cover bad debt or pay out to governance. If borrowRate is 5%, utilization is 80%, and reserveFactor is 10%, the supply rate is:
5% × 0.80 × 0.9 = 3.6%Liquidation has to start while the collateral still covers the bonus
When a position's health factor drops below 1, anyone can liquidate it. The liquidator transfers an amount of the debt asset into the protocol, and the protocol transfers a corresponding amount of the borrower's collateral, at a discounted price, to the liquidator.
The discount is the liquidation bonus. For ETH on Aave it sits around 5% to 10%, and for more volatile assets the bonus is higher. The size of the bonus reflects the risk the liquidator takes by holding the seized collateral until they can sell it on the open market.
Take Bob, who deposited 1 ETH at $3,000 and borrowed the maximum, 2,400 USDC. Interest has grown his debt to 2,500 USDC, so his health is (3,000 × 0.85) / 2,500 = 1.02. ETH falls 2% to $2,940, and his health becomes (2,940 × 0.85) / 2,500 = 0.9996. A liquidator repays 1,250 USDC of the debt and receives 1,250 × 1.05 = $1,312.50 worth of ETH, a bonus of $62.50. Bob is left with $1,627 of ETH against 1,250 USDC of debt, and a health of 1.11.
The bonus is one reason the threshold is 85% and not 99%, and the time a liquidation takes is another. With a 5% bonus a liquidator takes $1.05 of collateral for every $1 of debt, so liquidation can clear a position only while the collateral is worth at least 105% of the debt. With a threshold of 85%, liquidation starts when the collateral is worth about 118% of the debt, so the collateral can lose about 11% more before liquidation stops covering the debt. That room has to cover the price move between the moment the position becomes liquidatable and the moment a liquidator's transaction lands, and the distance between the oracle price and the market price, which for a Chainlink feed can be up to its deviation threshold. With a threshold of 99%, liquidation would start at 101%, which is less than a liquidator has to be paid.
Most protocols cap each individual liquidation at 50% of the position's debt. This is the close factor. It limits what the borrower loses to the bonus: for Bob, repaying half was enough to restore his health and cost him $62.50, and repaying everything would have cost him twice that. The 50% close-factor cap is typically enough to push the health factor back above 1, but it may not be in extreme market conditions. If the price keeps falling after one liquidation, another liquidator can step in for the next 50%, and so on.
If the collateral falls below the debt before anyone liquidates, no liquidator will touch the position, since repaying the debt would cost more than the collateral received. The protocol either absorbs this bad debt from its reserve, or distributes it across suppliers, reducing everyone's balance proportionally. Major bad-debt events have hit Inverse Finance in April 2022, Mango Markets on Solana in October 2022, and Euler V1 in March 2023.
A wrong price breaks the protocol in both directions
Every collateral and debt asset needs a price oracle. The protocol reads oracle prices to compute collateral value when a borrower opens a position, to compute the health factor of every open position, and to determine how much collateral the liquidator receives for a given amount of debt repaid.
Oracle reports a price too high. Borrowers take out more debt than their collateral is worth. When the price corrects downward, those positions are underwater, with debt larger than collateral, and the protocol absorbs the loss as bad debt. The flash loans lesson walked through this attack on a lending protocol that read the spot price of a single AMM pool, which is why most production lending protocols use Chainlink price feeds.
Oracle reports a price too low. Healthy positions are marked as liquidatable. Liquidators rush in and seize collateral from positions that, by true market prices, should never have been liquidated. The borrower loses collateral they should not have lost.
Some protocols use multiple oracles for the same asset and cross-check. If two sources diverge by more than a threshold, the protocol pauses operations on that asset until the divergence resolves. This costs availability but prevents bad debt during oracle outages.
The pool-per-asset design described above is the original Compound V2 / Aave V2 shape. Any listed asset can back a loan from any pool, so when one collateral asset fails, the bad debt lands on suppliers who never chose to lend against it. Later designs answer this in different ways.
Isolated lending markets separate the assets. In Morpho Blue each market pairs one collateral asset with one borrow asset: ETH/USDC, wBTC/USDC, stETH/ETH, each its own market. A bug or oracle problem in one market does not affect others. The tradeoff is fragmented liquidity, since suppliers must choose specific markets rather than the protocol allocating their deposit across all opportunities.
Curated vaults are built on top of isolated markets to give the allocation back. In Morpho Vaults, suppliers deposit into a vault, and a curator allocates the vault's deposits across multiple isolated markets, rebalancing as rates change and pulling out of markets that show signs of risk. The supplier deposits once and now depends on the curator, which can be an EOA, a multisig, or a smart contract executing rules.
Shared pools with per-asset limits keep one pool and restrict each asset. In Aave V3 each asset has its own LTV and liquidation threshold, plus per-asset borrow caps and supply caps. Isolation mode lets the protocol mark certain risky assets as collateral that can only back stablecoin borrows, never other volatile assets. This contains tail risk without splitting into separate markets.
Two risks that the parameters do not remove
Liquidation cascades. In stressed markets, a price drop liquidates the first set of positions. Liquidators seize collateral and sell it on the open market to lock in their profit. Those sales push the price further down, and more positions become liquidatable. The cycle continues until the market stabilizes or the protocol runs out of liquidatable collateral. This pattern hit several lending protocols during the May 2022 Terra/Luna collapse, the March 2023 USDC depeg, and the August 2024 yen carry trade unwinds.
Bridge or wrapped-asset risk. Many lending markets accept wrapped versions of cross-chain assets, like wBTC on Ethereum or USDC.e on L2s. The wrapper is only as safe as the bridge. If the bridge gets exploited, the wrapped asset depegs from the underlying, and any lending market holding it as collateral has bad debt overnight.
Before you list an asset as collateral, or supply to a market that accepts it, compare three numbers: how far its price can move before a liquidation lands, the liquidation bonus, and the room between the liquidation threshold and 100%. If the first two do not fit into the third, the loss goes to the reserve and then to the suppliers.