Q&A · Community Q&A

How to Build a DeFi Lending Protocol: Architecture, Rates, Oracles, Liquidations and Audits

Illustration of a lending pool connected to collateral, an oracle, a scale, and a security shield
On this page
Community question

Good day, I am a developer and have been wanting to build a lending protocol. Is it difficult to do this from scratch? How do I build this?

The short answer

You build a DeFi lending protocol by writing smart contracts that accept deposits into a pool, let borrowers draw from that pool against more valuable collateral, charge interest set by a formula, and let anyone liquidate loans that become unsafe. The lending logic itself is not the hard part. The hard part is everything that keeps depositors whole when markets crash: safe collateral choices, reliable price oracles, liquidations that still work under stress, bug-free accounting, audits, and careful operations after launch.

This page is a technical overview for developers. If you first want to understand the user side, read how DeFi lending protocols work and how lending works on Aave. For general tooling (Foundry, Hardhat, testnets, wallets and front ends), see our guide on how to make a dApp.

Step 1: choose an architecture

The first decision is how risk is shared between assets.

Design How it works Examples Trade-off
Shared multi-asset pool One pool per network; every listed asset can be collateral and borrowable Aave V3 Deep liquidity and flexible positions, but one bad collateral asset can create bad debt for the whole pool
Single-borrowable-asset markets Each market lends one base asset against a set of collateral assets Compound III (“Comet”) Simpler risk per market; liquidity is split across markets
Isolated pair markets Each market is one collateral asset and one loan asset with fixed parameters Morpho markets Risk is contained per market; curators or vaults allocate lender liquidity across markets
Hub-and-spoke Shared liquidity hubs extend capped credit lines to separate markets Aave V4 Aims to combine shared liquidity with isolated risk; more moving parts

Many newer protocols use isolated designs, because they limit the damage one listing can do. Our Aave vs Compound comparison explains the two best-known designs in more depth.

Step 2: the core contracts

Whatever the design, a lending protocol has the same building blocks:

  1. Deposit accounting. Suppliers receive a claim on the pool: a rebasing receipt token such as Aave’s aToken, or shares whose value rises over time (the ERC-4626 vault standard is a common pattern). Internally, protocols track a cumulative interest index and store each balance in “scaled” units, so interest accrues for everyone without looping over accounts.
  2. Borrow accounting. Debt is tracked the same way, with a borrow index that grows at the borrow rate.
  3. Interest-rate model. A separate contract that returns borrow and supply rates from utilization (see below).
  4. Collateral and risk configuration. For each asset: maximum loan-to-value, liquidation threshold, liquidation bonus, supply and borrow caps, and whether it can be borrowed at all.
  5. Oracle adapter. Normalizes prices from one or more feeds and rejects stale or invalid data.
  6. Liquidation engine. Lets third parties close unsafe positions.
  7. Admin layer. Governance, a timelock for parameter changes, and a guardian that can pause markets in an emergency.

Keep the core small and immutable where you can, and put parameters you expect to tune behind a timelock. Every upgrade path is also an attack path.

How the core contracts connect Supplier Deposits assets Pool accounting Deposit index Borrow index Borrower Draws a loan Assets Loan Collateral vault Secures the debt Posts Oracle adapter Validates prices Collateral rules Check loan safety Price Value Liquidation engine Repays unsafe debt If unsafe
The pool moves assets and tracks claims, while the oracle and collateral rules decide whether a loan remains safe. If it does not, the liquidation engine returns debt to the pool.

Step 3: design the interest-rate model

Almost every major protocol uses a “kinked” utilization curve. Utilization is borrowed ÷ supplied. Below an optimal utilization point, the borrow rate rises gently; above it, it rises steeply so that borrowers repay and new lenders arrive before the pool runs dry.

Aave V3’s documented formula is:

  • If U ≤ U_optimal: borrow rate = base + slope1 × (U ÷ U_optimal)
  • If U > U_optimal: borrow rate = base + slope1 + slope2 × (U − U_optimal) ÷ (1 − U_optimal)

Suppliers earn roughly borrow rate × utilization × (1 − reserve factor), where the reserve factor is the protocol’s cut. Compound III uses separate supply and borrow curves for its base asset, each with its own kink and slopes, and accrues interest per second. Morpho uses an adaptive curve that shifts over time toward a target utilization.

Kinked utilization curve Utilization Borrow rate Optimalutilization Gentle slope Steep slope Below optimal Rates rise slowly as borrowing grows Above optimal Rates push repayment
The model makes borrowing progressively more expensive after the optimal-utilization kink, encouraging repayment and new supply before available liquidity runs out.

Things to get right: rate math in fixed-point units (ray or 1e18), rounding that always favors the protocol, and a high enough slope above the kink that withdrawals don’t get stuck for long. Our page on what determines interest rates on crypto lending platforms explains the economics behind these curves.

Step 4: oracles, the most dangerous dependency

Your protocol is only as safe as the prices it reads. If an attacker can move the price your contracts see, they can borrow far more than their collateral is worth.

Practical rules:

  • Use robust external feeds (Chainlink, Pyth, RedStone and similar) for liquid assets rather than spot prices from a single DEX pool, which flash loans can move within one transaction.
  • Check staleness and sanity. Reject prices older than the feed’s heartbeat, zero or negative answers, and wild jumps you can’t explain.
  • On layer-2 networks, check sequencer status. Chainlink publishes sequencer uptime feeds so you can pause liquidations or borrowing right after an outage.
  • Price derivatives carefully. Liquid staking tokens and wrapped assets are often priced from an exchange rate times the underlying price, with caps on how fast that rate can grow. A misconfigured cap can be as harmful as a manipulated feed: Aave’s March 2026 CAPO oracle error undervalued wstETH and triggered about $26 million of liquidations.
  • Don’t list thin assets as collateral. In the Mango Markets exploit of October 2022, an attacker pushed up the price of a thinly traded collateral token and borrowed against the inflated value.

Step 5: liquidations that work in a crash

When a position’s health factor falls below 1, someone has to repay the debt and seize collateral before the collateral is worth less than the loan. Design choices:

  • Who liquidates. Most protocols let anyone liquidate and pay a liquidation bonus (a discount on collateral) to attract competing bots.
  • How much at once. A close factor limits each liquidation. Aave V3 allows up to 50% of the debt to be repaid while the health factor is above 0.95, and up to 100% at 0.95 or below, or when the borrower’s balance of the specific collateral or debt asset being liquidated is worth less than $2,000 (a per-asset test, not the whole position).
  • Auction or fixed discount. Fixed discounts are simple; Dutch auctions (used by Sky, formerly MakerDAO) can find a fairer price in volatile markets. Compound III has the protocol “absorb” underwater accounts and sell the collateral at a discount from its reserves.
  • Bad debt. Decide in advance who absorbs losses when collateral is worth less than debt: protocol reserves, a staking backstop such as Aave’s Umbrella, or lenders pro rata.

Simulate liquidations under historical crashes and gas spikes, and set supply caps so no collateral position is larger than the market can absorb. For the borrower’s view, see forced liquidation.

Aave V3 close-factor path Health factor below 1? Position is not liquidated No Yes Health factor at or below 0.95? Up to 100% of debt repaid Yes No Specific asset balanceunder $2,000? Up to 100% of debt repaid Yes Up to 50% of debt repaid No
Once the health factor falls below 1, Aave V3 allows up to 100% repayment at 0.95 or below, or when the specific collateral or debt asset being liquidated is worth less than $2,000. Otherwise, the close factor is up to 50%.

Step 6: security, audits and testing

Lending protocols have lost hundreds of millions of dollars to bugs that sat outside the obvious lending path:

  • Euler Finance (March 2023): a missing health check in a donation function let an attacker drain roughly $197 million using a flash loan (estimates vary). After negotiations, the attacker returned all of the stolen funds by early April 2023, according to Euler’s own account.
  • Empty-market rounding attacks: several Compound V2 forks, including Hundred Finance (2023) and Sonne Finance (2024), were drained by manipulating the exchange rate of a newly listed, nearly empty market.

A realistic security process includes:

  1. Extensive tests: unit tests, fuzzing and invariant tests (for example “total debt never exceeds total collateral value at liquidation thresholds”), plus fork tests against mainnet state.
  2. Several independent audits by firms with lending experience, re-audited after every change. See our list of smart contract audit firms.
  3. Competitive audit contests and a public bug bounty sized relative to the value at risk.
  4. Formal verification of key invariants where budget allows.
  5. A staged launch: low supply caps, conservative collateral factors, and gradual increases as monitoring confirms behavior.
  6. Operational security: multisig or timelocked admin keys, hardware signers, and an incident-response plan.

Our page on smart contract vulnerabilities covers common bug classes such as reentrancy and access-control errors.

Step 7: fork or build from scratch?

Forking an established codebase gets you years of review, but it is not a shortcut to safety. Forks often change parameters, oracles or token lists without understanding why the original made its choices, and attackers know the original’s weak spots well. Check the license first, since visible source code is not always licensed for commercial reuse, then treat the fork as a new system that needs its own audits.

Step 8: regulation and compliance

Lending protocols sit in uncertain legal territory, and rules change, so take legal advice for your jurisdiction before launch.

  • European Union: the Markets in Crypto-Assets Regulation (MiCA) licenses crypto-asset service providers. Its recital 22 says that where crypto-asset services are “provided in a fully decentralised manner without any intermediary, they should not fall within the scope of this Regulation”, while activities partly performed in a decentralised manner can still be covered. Whether your project qualifies depends on who controls the contracts, front end and upgrades. Separately, MiCA’s recital 94 says the regulation “should not address the lending and borrowing of crypto-assets” and should not prejudice applicable national law; ESMA restated this in a June 2026 Q&A, and in its 24 September 2026 response to the Commission’s MiCA review consultation the European Banking Authority recommended a cost-benefit analysis of adding intermediated crypto-asset borrowing and lending to MiCA’s list of services, so this may change.
  • United States: there is no single DeFi lending license. Depending on the facts, securities laws (the SEC treated BlockFi’s interest accounts as securities), commodities rules, state money-transmission laws and sanctions screening can apply, especially to the company running the front end.
  • Everywhere: decide whether your interface will block sanctioned addresses or certain regions, and how token distribution and governance affect your legal exposure.

Risks for builders and users

Launching a lending protocol puts other people’s money at risk. Beyond code bugs, the main risks are bad debt from poor collateral choices, oracle failures, liquidity crunches when utilization hits 100%, governance capture, and front-end hijacks. Our overview of DeFi lending risks covers them from the user side. Being transparent with users about these risks is part of building responsibly.

For more on lending protocols in general, browse the Lending & Borrowing hub.

Frequently asked questions

Is it hard to build a DeFi lending protocol?

A toy version is a weekend project for an experienced Solidity developer. A production protocol is hard: the difficult parts are pricing collateral safely, making liquidations work in a crash, avoiding rounding and accounting bugs, and operating the system securely after launch.

Should I fork Aave or Compound instead of writing from scratch?

Forking battle-tested code saves time and inherits years of review, but you also inherit its known attack surface, and forks have been drained by bugs the original teams had mitigated with careful market configuration. Check the code's license, keep upstream security fixes, and get the fork audited as a new system.

What programming language do I need?

On Ethereum and EVM chains, Solidity is standard, with Foundry or Hardhat for testing. On Solana, programs are usually written in Rust, often with the Anchor framework. The language matters less than testing discipline and security review.

How do lending protocols make money?

Usually through a reserve factor, a share of the interest borrowers pay that goes to the protocol treasury instead of suppliers. Some also take a cut of liquidation bonuses or charge flash-loan fees.

Do I need a license to launch a lending protocol?

It depends on your jurisdiction and how the service is run. In the EU, MiCA's recitals say crypto-asset services provided in a fully decentralised manner without any intermediary should not fall within its scope, and that it should not address the lending and borrowing of crypto-assets, which remains subject to applicable national law. In the US, securities, commodities, money-transmission and sanctions laws can apply depending on the facts. Get legal advice before launch.

Sources

  1. Euler Labs: War & Peace, behind the scenes of Euler's $240M exploit recovery
  2. Aave governance forum: [Direct to AIP] wstETH CAPO Oracle Incident User Reimbursement
  3. Aave V3 source code (aave-dao/aave-v3-origin): LiquidationLogic.sol
  4. Aave documentation: Interest rate strategy (DefaultReserveInterestRateStrategyV2)
  5. Compound III documentation: Interest rates
  6. Compound III documentation: Liquidation
  7. Aave Help Center: Liquidations and health factor
  8. Chainlink documentation: Data Feeds
  9. Regulation (EU) 2023/1114 on markets in crypto-assets (MiCA), recitals 22 and 94, EUR-Lex
  10. EBA: Response to the EC targeted consultation on the review of MiCA (24 September 2026)
  11. ESMA Q&A 2883: MiCA and crypto-asset lending and borrowing
  12. Cointelegraph: Euler Finance attack, how it happened and what can be learned

Educational content, not financial advice. DeFi carries risk, including total loss of funds.

↑↓ to navigate ↵ to open Esc to close