BlockchainAppMaker

DeFi

Building a DeFi lending and borrowing platform: the mechanics that keep it solvent

A DeFi lending platform lets users deposit assets to earn interest and borrow other assets against over-collateralized positions, with automated liquidations keeping the system solvent. Its safety rests on three things: a sound interest rate model, reliable price oracles and liquidations that actually happen during a crash.

This page is a general build guide. If you specifically want to understand and adapt Aave's design, read the companion guide on building a protocol like Aave.

How the core loop works

  1. A lender deposits USDC into a market and receives an interest-bearing claim (a token whose balance or exchange rate grows).
  2. A borrower deposits ETH as collateral and borrows USDC up to a limit set by the collateral's loan-to-value ratio.
  3. Interest accrues continuously, set by how much of the pool is borrowed.
  4. If ETH falls and the position's debt grows too large relative to its collateral, anyone can liquidate it: repay part of the debt and receive collateral at a discount.

Everything else, from flash loans to isolation modes, is refinement of this loop.

Interest rate models

Rates are set by utilization U = borrows / (cash + borrows). Most protocols use a kinked curve: rates rise gently until an optimal utilization, then steeply, so that if the pool runs short of cash, borrowing becomes expensive enough to force repayments and attract deposits.

if U <= U_opt:
    borrowRate = base + slope1 * U / U_opt
else:
    borrowRate = base + slope1 + slope2 * (U - U_opt) / (1 - U_opt)

supplyRate = borrowRate * U * (1 - reserveFactor)

Example: with base 0%, slope1 4%, slope2 75% and U_opt 90%, a pool at 50% utilization charges borrowers about 2.2% and pays suppliers about 1.0% after a 10% reserve factor. At 95% utilization the borrow rate jumps to about 41.5%. That steep second slope is what protects withdrawals. Set it too gently and lenders can be locked out when everyone wants their cash back.

Some newer designs adjust the curve automatically over time based on how long utilization stays above target, rather than relying on governance to retune parameters.

Collateral, health factor and liquidation

Each collateral asset has two key parameters:

  • Loan-to-value (LTV): the maximum you can borrow against it when opening a position (e.g. 80%).
  • Liquidation threshold: the point at which the position becomes liquidatable (e.g. 83%). The gap between the two is the user's buffer.

The health factor summarizes a position:

healthFactor = Σ (collateral_i × price_i × liquidationThreshold_i) / totalDebtValue

Above 1 the position is safe; below 1 it can be liquidated. A liquidator repays some of the debt (a close factor often caps it at half per call, with exceptions for very unhealthy or tiny positions in some designs) and receives that value in collateral plus a bonus, for example 5%.

When liquidations fail

Liquidation only works if someone profits from doing it. It fails when:

  • the collateral cannot be sold without large slippage, so the bonus does not cover the loss;
  • the chain is congested and gas spikes make liquidation unprofitable for small positions;
  • the price moves faster than liquidators can act, leaving positions where debt exceeds collateral.

The result is bad debt: loans no collateral can cover. Lenders bear it unless a reserve or safety module absorbs it. Your risk framework must cap exposure to any asset by the liquidity available to liquidate it, using supply and borrow caps.

Oracles: the most dangerous dependency

Every borrow limit and liquidation depends on a price. Oracle failures have caused some of DeFi's largest losses, including manipulation of thinly traded collateral to borrow against inflated values.

Oracle typeStrengthWeaknessMitigation
Push-based aggregator (e.g. Chainlink)Aggregates many sources; widely usedUpdates on heartbeat or deviation, so can lagCheck staleness; bound deviations
Pull-based (e.g. Pyth, RedStone)Low latency, many assetsCaller supplies the update, so integration must verify freshnessEnforce maximum age and confidence intervals
On-chain TWAPNo external dependencyLags; manipulable on shallow pools over several blocksUse only deep pools; long windows
Spot pool priceSimpleManipulable within one transaction via flash loansDo not use for collateral valuation

On rollups, also check the sequencer uptime feed: when the sequencer is down, prices stall, and a grace period after it restarts prevents unfair liquidations. Pegged assets (stablecoins, liquid staking tokens) need explicit decisions about whether to price them at the peg or at market, since each choice fails differently during a de-peg.

Pooled versus isolated markets

DesignHow it worksProsCons
Pooled (shared risk)All assets in one system; any collateral backs any borrowCapital efficient, simple UXOne bad asset can create bad debt for everyone
Single-borrowable-assetEach market lends one asset against several collateralsContained risk, simpler accountingLiquidity fragmented across markets
Isolated pairsEach market is one collateral and one loan asset with its own oracle and parametersPermissionless market creation; risk fully separatedFragmented liquidity; curators or vaults needed to allocate capital

Aave and the original Compound are pooled, Compound III uses a single borrowable asset per market, and designs such as Morpho's isolated markets push risk decisions to market creators and vault curators. Pick based on how many long-tail assets you want to support: the more exotic the collateral, the stronger the case for isolation.

Choosing chains for a lending market

A lending market can only be as safe as the chain's liquidity and oracle coverage allow. Before deploying anywhere, check:

  • Collateral liquidity on that chain. Liquidators need to sell seized collateral locally. A bridged asset with deep liquidity on Ethereum but a thin pool on your target rollup must get conservative parameters there.
  • Oracle coverage. Are there reputable feeds for each asset on this chain, with sensible heartbeat and deviation settings?
  • Sequencer and finality behavior. Rollups such as Arbitrum and Base have centralized sequencers that can go down; your liquidation logic needs a grace period. Chains with faster or slower finality affect how quickly oracles and liquidators react.
  • Native versus bridged assets. A bridged token carries bridge risk; if the bridge is exploited, the collateral can become worthless instantly. Prefer native issuance where it exists.
  • Gas costs. Cheap gas makes small positions viable and liquidations profitable at small sizes, which is good, but also makes spam and dust positions cheap.

Deploying the same contracts on Ethereum, Arbitrum, Base, Polygon PoS or BNB Smart Chain is straightforward because they are EVM-compatible. Solana requires a separate implementation in Rust with different account and oracle models. Each deployment should be treated as its own market with its own parameters, never a copy-paste of the mainnet configuration.

Security issues specific to lending

  • Empty-market exchange-rate attacks. Forks of Compound v2 have been drained when a new market launched with zero supply, letting an attacker manipulate the exchange rate through donations and rounding. Seed new markets and round against users.
  • Reentrancy via token hooks. Tokens with transfer callbacks (ERC-777 style) have been used to re-enter lending contracts mid-borrow. Follow checks-effects-interactions and guard every external entry point.
  • Donation and accounting logic. Euler Finance lost about $197 million in March 2023 through a flaw in a donation function that let an attacker create an undercollateralized position and self-liquidate profitably. The funds were later returned, but the lesson stands: every function that changes balances must preserve solvency checks.
  • Flash loans. Offering flash loans is useful but expands the attack surface. Ensure no state can be read mid-flash-loan in an inconsistent condition.

The audit guide explains how to scope review for a protocol like this.

Build process

  1. Decide market structure (pooled or isolated) and the initial asset list. Start small: two or three liquid assets.
  2. Write a risk framework: how LTV, liquidation thresholds, bonuses and caps are derived from each asset's volatility and on-chain liquidity.
  3. Implement or fork the core. Forking an audited protocol is usually wiser than writing one; respect the license.
  4. Build the liquidation bot and publish liquidation docs so third parties compete to liquidate.
  5. Simulate stress: historical crashes, oracle delays, gas spikes, de-pegs.
  6. Audit, bug bounty, guarded launch with caps, then raise limits gradually.

Cost and timeline

A reasoned estimate: deploying a fork of an established lending protocol with new parameters, a front end and a liquidation bot takes a team of three to five engineers roughly two to four months, plus audits and risk work. A novel lending design takes considerably longer and needs economic review in addition to code audits. Ongoing costs include oracle fees on some networks, keeper infrastructure, risk monitoring and governance. For collateral that is itself an NFT, see the NFT lending guide; for the broader picture, the DeFi development overview.

General information only, not legal or financial advice. Operating a lending front end or interest-bearing product may be regulated depending on your structure and jurisdiction.

Frequently asked questions

Why are DeFi loans over-collateralized?

Because the protocol cannot identify borrowers or pursue them for repayment. The only enforcement is selling collateral, so collateral must exceed the debt with enough margin to survive price moves before liquidation.

What is a flash loan?

An uncollateralized loan that must be borrowed and repaid within a single transaction. If repayment fails, the whole transaction reverts. Flash loans are used for arbitrage, liquidations and collateral swaps, and also to fund attacks on contracts with manipulable prices.

Who liquidates positions?

Anyone. In practice, specialized bots monitor health factors and compete to liquidate, earning the liquidation bonus. Protocols should run their own backup bots too.

Can a lending protocol lose lenders' money?

Yes, through bad debt from failed liquidations, oracle errors, smart contract exploits or a collateral asset collapsing. Reserves and safety modules can absorb some losses but rarely all.

How are interest rates set?

Algorithmically, from utilization. Parameters such as the optimal utilization and slopes are set by governance or risk managers, and some newer models adapt automatically.

Can I support long-tail tokens as collateral?

Only with tight caps or isolated markets. Thinly traded tokens are easy to manipulate and hard to liquidate, which is exactly how many lending exploits have started.