Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Architect a Lending and Borrowing Platform

A developer-focused guide to building a decentralized lending protocol. This tutorial covers core system design, including collateral management, risk parameters, liquidation mechanisms, and interest rate models.
Chainscore © 2026
introduction
CORE CONCEPTS

Introduction to Decentralized Lending Architecture

A technical overview of the fundamental components and smart contract patterns that power permissionless lending and borrowing protocols like Aave and Compound.

Decentralized lending protocols are non-custodial financial markets where users can supply crypto assets to earn yield and borrow assets against collateral. Unlike traditional finance, these platforms are governed by immutable smart contracts on blockchains like Ethereum. The core architecture revolves around pooled liquidity, where all supplied assets are aggregated into a single reserve, and over-collateralized loans, which mitigate default risk without requiring credit checks. This design enables 24/7, global access to capital markets.

The architecture is built on several key smart contracts. The LendingPool is the main entry point, handling deposits, withdrawals, borrows, and repayments. It interacts with a Price Oracle to fetch real-time asset values for calculating collateral health. Each supported asset has a corresponding aToken or cToken, which is an interest-bearing ERC-20 token minted to depositors, representing their share of the liquidity pool. Loan positions are managed by a Collateral Manager, which tracks each user's Loan-to-Value (LTV) ratio and triggers liquidations if the collateral value falls below a predefined threshold.

Interest rates are algorithmically determined by the Utilization Rate—the ratio of borrowed assets to supplied assets in a pool. A common model uses a kinked rate curve: rates rise slowly until utilization hits an optimal point (e.g., 80%), then increase sharply to incentivize repayments or more deposits. This is implemented in contracts using a piecewise linear or exponential function. For example, a simplified rate calculation in Solidity might update a borrow rate based on current pool utilization every block.

Liquidation is a critical safety mechanism. If a borrower's Health Factor falls below 1 (where Health Factor = (Collateral Value * Liquidation Threshold) / Borrowed Value), their position becomes eligible for liquidation. A liquidator can repay a portion of the unhealthy debt at a discount and receive a corresponding amount of the borrower's collateral, plus a liquidation bonus. This process, executed via a liquidate() function, ensures the protocol remains solvent even during volatile market conditions.

Advanced architectures incorporate features like flash loans, which are uncollateralized loans that must be borrowed and repaid within a single transaction. These are enabled by executing logic in a flash loan receiver contract that implements a specific callback function. Other considerations include risk parameters (reserve factors, liquidation thresholds) set by governance, interest rate strategies for each asset, and cross-chain deployments using layer-2 solutions or app-specific chains for scalability.

When architecting a lending platform, developers must prioritize security audits, formal verification of core math, and robust oracle design. The codebase is typically organized into modular contracts for upgradability via proxy patterns. Understanding this architecture is essential for building new protocols, contributing to existing ones like Aave V3, or simply interacting with them securely as a user or integrator.

prerequisites
ARCHITECTURE FOUNDATION

Prerequisites and Tech Stack

Building a secure and scalable lending and borrowing platform requires a deliberate selection of core technologies and a solid understanding of the underlying financial primitives.

The foundational layer of any lending platform is the smart contract framework. Solidity remains the dominant language for Ethereum and EVM-compatible chains like Arbitrum, Polygon, and Base. For developers, proficiency in Solidity, understanding the ERC-20 token standard, and familiarity with OpenZeppelin's secure contract libraries are non-negotiable. The development environment typically consists of Hardhat or Foundry for compiling, testing, and deploying contracts, alongside a node provider like Alchemy or Infura for blockchain interaction. A comprehensive test suite using frameworks like Waffle or the built-in tools in Foundry is critical for simulating liquidation scenarios, interest accrual, and edge cases.

The core architecture revolves around a few key smart contracts. The LendingPool contract acts as the central ledger, managing user deposits, borrow positions, and the calculation of accrued interest. Each supported asset requires a separate AToken (aToken) and DebtToken contract. The aToken is an interest-bearing token minted to depositors, representing their share of the liquidity pool, while the DebtToken represents a borrower's outstanding debt. An InterestRateStrategy contract dictates how borrow and supply rates are calculated based on pool utilization, often using a linear or kinked model. A Price Oracle, such as Chainlink, is essential for fetching real-time asset prices to determine collateral health and trigger liquidations.

Security considerations must be integrated from the start. Use audited, upgradeable proxy patterns (like Transparent or UUPS proxies) to allow for future improvements, but ensure the initialization and admin functions are securely managed. Implement robust access control using OpenZeppelin's Ownable or role-based AccessControl. A critical component is the Health Factor calculation, which determines if a position is undercollateralized: Health Factor = (Collateral Value * Liquidation Threshold) / Borrowed Value. Positions with a health factor below 1.0 are eligible for liquidation. This logic must be gas-optimized and resistant to price manipulation.

For the front-end and backend, you'll need a stack to interact with these contracts. Use a library like ethers.js or viem to connect wallets (MetaMask, WalletConnect), query on-chain data, and send transactions. A subgraph on The Graph protocol is highly recommended for efficiently indexing complex events like deposits, borrows, and liquidations, which is far more efficient than direct RPC calls. For rate calculations off-chain, you'll need to replicate the contract's interest rate logic in JavaScript or another language, using the pool's reserveData (available liquidity, total debt, utilization rate).

Finally, consider the economic and risk parameters that are not code, but are crucial to the system's stability. These include: the Loan-to-Value (LTV) ratio (e.g., 75% for ETH), the liquidation threshold (e.g., 80%), the liquidation bonus (e.g., 5% for liquidators), and the reserve factor (a fee on interest sent to a treasury). These parameters are typically controlled by a decentralized governance contract. Thoroughly modeling different market scenarios (high volatility, flash crashes) with these parameters is a prerequisite before deploying to a mainnet.

core-architecture-overview
CORE SYSTEM ARCHITECTURE

How to Architect a Lending and Borrowing Platform

A technical guide to designing the core components of a decentralized lending protocol, covering smart contract structure, risk management, and economic incentives.

A lending and borrowing platform's architecture is defined by its core smart contracts. The primary contracts are the LendingPool, which manages deposits and loans, and the InterestRateModel, which calculates variable and stable rates. Assets are represented as aTokens (for lenders) and debtTokens (for borrowers), which are ERC-20 compliant and accrue interest in real-time. A critical design decision is whether to use a peer-to-pool model, like Aave and Compound, where liquidity is aggregated into shared reserves, or a peer-to-peer model. The peer-to-pool model dominates due to its superior capital efficiency and liquidity depth.

Risk parameters are the protocol's first line of defense and must be encoded on-chain. Each asset has configurable settings: the Loan-to-Value (LTV) ratio (e.g., 75% for ETH), the liquidation threshold (e.g., 80%), and a liquidation penalty (e.g., 5%). An oracle service, like Chainlink, feeds price data to a dedicated PriceOracle contract to determine collateral values and trigger liquidations. Health factors are calculated per user position: Health Factor = (Collateral Value * Liquidation Threshold) / Total Borrowed Value. A health factor below 1.0 makes the position eligible for liquidation.

The liquidation engine is a critical subsystem that must be robust and incentive-aligned. When a position becomes undercollateralized, liquidators can repay a portion of the debt in exchange for seized collateral, often at a discount. A common design is a fixed discount (e.g., 5%) or a Dutch auction mechanism. To prevent market manipulation, the protocol should use a decentralized oracle with multiple price feeds and circuit breakers. The liquidation logic must be gas-efficient and resistant to front-running, often implemented via a liquidationCall function that atomically swaps debt for collateral.

Interest rate models algorithmically balance supply and demand. A common model is a jump-rate model (used by Compound) or a linear model (like Aave's stable borrowing). For example, a model might have a base utilizationRate (U). The borrow rate (R) could be defined as: if U < U_optimal: R = R_0 + U * R_slope1; if U >= U_optimal: R = R_0 + U_optimal*R_slope1 + (U-U_optimal)*R_slope2. Parameters like U_optimal, R_0, R_slope1, and R_slope2 are governance-upgradable. Supply rate is derived from the borrow rate, minus a reserve factor that accrues to the protocol treasury.

Governance and upgradeability are final architectural pillars. Control over critical parameters (risk settings, oracle addresses, reserve factors) is typically vested in a decentralized autonomous organization (DAO) via a governance token like AAVE or COMP. To manage smart contract risk, protocols use proxy patterns (e.g., Transparent or UUPS Proxies) that separate logic from storage, allowing for bug fixes and improvements. However, the upgrade mechanism itself must be permissioned and include timelocks to give users notice. A robust architecture also includes emergency pause mechanisms and asset listing/bridging modules for multi-chain deployment.

key-components
ARCHITECTURE

Key Protocol Components

Building a secure lending platform requires integrating several core smart contract modules. This guide covers the essential components and their interactions.

collateral-and-ltv
ARCHITECTURAL GUIDE

Collateral Management and Loan-to-Value Ratios

A technical guide to designing the core risk parameters for a decentralized lending protocol, focusing on collateral valuation and LTV mechanics.

The Loan-to-Value (LTV) ratio is the primary risk parameter in any lending protocol. It defines the maximum amount a user can borrow against their deposited collateral. For example, with an LTV of 75% on ETH, a user depositing $10,000 worth of ETH can borrow up to $7,500 of another asset. This ratio acts as a buffer against price volatility. If the value of the collateral falls, the protocol has a safety margin before the loan becomes undercollateralized. Protocols like Aave and Compound set LTVs per asset based on its liquidity, volatility, and oracle reliability.

Effective collateral management requires a robust system for tracking user positions in real-time. The Health Factor is the standard metric for this, calculated as (Collateral Value * Liquidation Threshold) / Total Borrowed Value. A health factor below 1.0 indicates the position is eligible for liquidation. This calculation must be performed on-chain, often using price feeds from decentralized oracles like Chainlink. The architecture must efficiently update this factor for a user on every interaction—deposit, withdraw, borrow, or repay—to ensure the protocol's solvency is never at risk.

Setting LTV and liquidation parameters is a continuous risk assessment process. A volatile asset like a memecoin may have an LTV of 25-40%, while a stable, blue-chip asset like WETH or WBTC might support 75-80%. The Liquidation Threshold is typically set a few percentage points above the LTV to create a buffer zone. For instance, an asset with a 75% LTV might have an 80% liquidation threshold. This means borrowing up to 75% is allowed, but if the collateral value drops such that the borrowed amount exceeds 80% of its value, the position becomes liquidatable to protect the protocol.

Smart contract architecture must enforce these rules gas-efficiently. A typical borrow() function will check: 1) The asset's isActive flag, 2) The requested amount does not exceed the user's borrowing power based on LTV, and 3) The resulting health factor remains above 1.0. Here's a simplified logic check in Solidity:

solidity
require(asset.isActive, "Asset not active");
require(amount <= getUserBorrowingPower(user), "Exceeds borrowing power");
require(calculateHealthFactor(user, amount) > 1e18, "Health factor too low");

Failed checks revert the transaction, keeping the system safe.

Advanced protocols implement features like isolation modes and collateral caps for further risk management. Isolation mode, used by Aave V3, restricts which assets can be used as collateral for borrowing specific, high-risk assets. This contains risk contagion. Collateral caps limit the total protocol-wide exposure to a single asset, preventing over-concentration. When architecting your platform, you must decide whether to implement a global risk framework for all assets or allow governance to set granular, asset-specific parameters for LTV, liquidation threshold, and caps.

Ultimately, a lending protocol's security and capital efficiency are a direct function of its collateral management design. Regular stress testing of LTV ratios against historical price volatility data is essential. The architecture should allow protocol governance to adjust parameters in response to market conditions without requiring upgrades. By prioritizing precise collateral valuation, conservative LTV settings, and real-time health monitoring, you build a foundation that can scale securely.

MODEL ARCHITECTURE

Interest Rate Model Comparison

Comparison of common interest rate models used in DeFi lending protocols, detailing their core mechanisms and trade-offs.

Model FeatureLinear (Aave V2)Kinked (Compound V2)Dynamic (Euler Finance)

Core Mechanism

Utilization-based piecewise linear function

Two-slope model with a kink at optimal utilization

Exponential function based on market volatility

Interest Rate Predictability

Capital Efficiency at Low Utilization

Low

High

High

Borrow Rate Cap

No hard cap

No hard cap

Theoretically uncapped, practically limited by function

Optimal Utilization Target

Variable per asset (e.g., 80-90%)

Fixed kink point (e.g., 80-90%)

Dynamic, adjusts based on market conditions

Implementation Complexity

Low

Medium

High

Primary Use Case

General-purpose lending with stable assets

Protecting liquidity during high demand

Risk-adjusted rates for volatile assets

Example Borrow APR at 50% Util

~5%

~3%

Varies by volatility oracle

liquidation-engine
CORE MECHANICS

Designing the Liquidation Engine

A liquidation engine is the critical risk management component of any lending protocol, automatically closing undercollateralized positions to protect the system's solvency.

A liquidation engine continuously monitors the health of all open borrow positions, measured by the health factor or collateralization ratio. This metric compares the value of a user's deposited collateral to their borrowed value. When market volatility causes the collateral value to drop or the borrowed asset value to rise, this ratio can fall below a predefined liquidation threshold (e.g., 110%). At this point, the position is considered undercollateralized and becomes eligible for liquidation. The primary goal is to repay the bad debt before the protocol itself becomes insolvent, ensuring lenders can always withdraw their funds.

The engine's architecture must decide who can trigger a liquidation and what incentives they receive. Most modern protocols use a permissionless, incentivized model where any external actor (a "liquidator") can call the liquidation function. They are rewarded with a liquidation bonus—a discount on the seized collateral—which compensates them for their gas costs and effort. For example, a 10% bonus means a liquidator repaying $100 of debt can claim $110 worth of the borrower's collateral. This design creates a robust, decentralized network of actors constantly watching for profitable opportunities, ensuring swift execution.

Implementing the logic requires precise, secure smart contract functions. A typical liquidate(address borrower, uint256 debtToRepay, address collateralAsset) function will: 1) Verify the borrower's health factor is below the threshold, 2) Calculate the exact amount of collateral to seize based on oracle prices and the bonus, 3) Transfer the debt repayment from the liquidator to the protocol (burning the borrower's debt tokens), and 4) Transfer the discounted collateral to the liquidator. It's critical that price feeds come from decentralized oracles like Chainlink to prevent manipulation during this sensitive process.

Key design considerations include the liquidation close factor and health factor buffer. A close factor limits how much of a position can be liquidated in a single transaction (e.g., 50%), preventing overly punitive liquidations from a single price dip. A health factor buffer is the gap between the liquidation threshold and the point of actual insolvency (100% collateralization). This buffer must account for price feed latency and transaction confirmation times; a buffer that is too small risks bad debt accumulating if liquidations cannot be processed fast enough during a crash.

Advanced systems implement features like soft liquidations or auction mechanisms to improve user experience and capital efficiency. Instead of an immediate, fixed-discount seizure, a soft liquidation might gradually swap a portion of the borrower's collateral for the debt asset via a DEX, potentially leaving them with a still-open but healthier position. Other protocols use a Dutch auction for the collateral, starting at a small discount that increases over time until a liquidator claims it. These methods can reduce the penalty for borrowers and improve the recovery rate for the system during volatile but non-catastrophic events.

oracle-integration
ARCHITECTING LENDING PLATFORMS

Price Oracle Integration and Security

A secure, reliable price oracle is the backbone of any DeFi lending protocol, determining collateral values, loan health, and liquidation triggers.

A price oracle is an external data feed that provides smart contracts with real-world asset prices. In a lending platform, this data is critical for calculating the loan-to-value (LTV) ratio, which determines borrowing limits and collateral requirements. An incorrect price can lead to undercollateralized loans or unnecessary, unfair liquidations. Therefore, oracle selection and integration are foundational security decisions, not mere implementation details. The primary challenge is sourcing tamper-proof, manipulation-resistant price data from off-chain markets into the deterministic on-chain environment.

Architects typically choose between decentralized oracle networks (DONs) like Chainlink, which aggregate data from multiple independent nodes, and custom oracle designs that may rely on a committee of signers. For most production platforms, a DON is recommended for its security and maintenance benefits. Integration involves the lending contract calling a function on an oracle contract (e.g., AggregatorV3Interface for Chainlink) to fetch the latest price. The key security parameters to configure are the heartbeat (how often the price updates) and deviation threshold (the price change that triggers an update), which balance data freshness with gas costs.

A robust architecture implements defense-in-depth. This starts with using multiple price sources to avoid a single point of failure. For major assets, pull data from at least two independent oracles (e.g., Chainlink and a custom fallback). The contract logic should include a circuit breaker that pauses borrowing or liquidations if price data becomes stale or deviates abnormally. Furthermore, implement a time-weighted average price (TWAP) for highly volatile assets or use the oracle's built-in min/max price bound checks to reject clearly invalid data before it impacts the system's state.

The most common attack vector is oracle manipulation, where an attacker artificially inflates or deflates an asset's price on a DEX to exploit the lending protocol's valuation. Mitigations include using TWAP oracles (like Uniswap V3's) that average prices over a period (e.g., 30 minutes), making short-term manipulation prohibitively expensive. For long-tail assets, a circuit breaker with multi-sig governance can allow for manual intervention. Always sanitize inputs: check for zero, negative, or extremely old timestamps (answeredInRound) in the returned price data to prevent using corrupted values.

Here is a basic example of a secure price fetch using Chainlink, incorporating staleness and validity checks:

solidity
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract OracleConsumer {
    AggregatorV3Interface internal priceFeed;
    uint256 public constant MAX_STALE_TIME = 2 hours;

    constructor(address _oracle) {
        priceFeed = AggregatorV3Interface(_oracle);
    }

    function getSecurePrice() public view returns (uint256) {
        ( , int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
        // Security Checks
        require(price > 0, "Invalid price");
        require(block.timestamp - updatedAt <= MAX_STALE_TIME, "Stale price");
        // Convert to uint256 (Chainlink returns 8 decimals for USD pairs)
        return uint256(price);
    }
}

Finally, continuous monitoring and governance are essential. Set up alerts for oracle heartbeat failures or deviation threshold breaches. Have a clear, tested emergency shutdown procedure that the protocol's governance can execute if an oracle is compromised. Document all oracle dependencies and their risk profiles. By treating the oracle not as a simple data feed but as a critical security subsystem, you architect a lending platform that is resilient to market manipulation and data corruption, protecting both the protocol's solvency and its users' funds.

LENDING & BORROWING ARCHITECTURE

Frequently Asked Questions

Common technical questions and solutions for developers building on-chain lending platforms.

Lending platforms use two primary risk models for collateral. Isolated pools (used by Euler, Solend) treat each asset pair as a separate, non-interacting market. A user borrowing USDC against ETH cannot use that ETH as collateral elsewhere. This model limits contagion risk but reduces capital efficiency.

Shared pools (used by Aave, Compound) aggregate all supplied assets into a single, cross-collateralized pool. A user's deposited ETH can simultaneously secure loans for multiple other assets. This increases capital efficiency but creates systemic risk where a single asset's depeg can threaten the entire protocol's solvency. The choice depends on your protocol's risk tolerance and target user sophistication.

conclusion-next-steps
ARCHITECTURE REVIEW

Conclusion and Next Steps

This guide has outlined the core components of a decentralized lending and borrowing platform, from the smart contract architecture to the economic mechanisms that ensure its stability. The next steps involve rigorous testing, security auditing, and planning for long-term governance.

Building a robust lending platform requires integrating the components we've discussed: the core LendingPool logic, price oracles for asset valuation, interest rate models, and liquidation engines. Each contract must be thoroughly unit-tested using frameworks like Foundry or Hardhat, with simulations covering edge cases like extreme market volatility, oracle failure, and flash loan attacks. A common next step is to deploy these contracts to a testnet (like Sepolia or Goerli) and develop a basic front-end interface to interact with the protocol, allowing for real-world testing of deposits, borrows, and liquidations.

Before any mainnet deployment, a comprehensive security audit is non-negotiable. Engage multiple reputable auditing firms to review the entire codebase, focusing on the calculateHealthFactor function, liquidation incentives, and oracle integration points. Consider implementing a bug bounty program on platforms like Immunefi to crowdsource security reviews. Simultaneously, you must design and deploy the protocol's governance system, which typically involves a GovernanceToken and a TimelockController contract (like OpenZeppelin's) to allow token holders to vote on parameter updates, new asset listings, and treasury management.

For ongoing development, monitor key protocol health metrics: Total Value Locked (TVL), utilization rates, and the ratio of bad debt. Plan for upgrades using proxy patterns (e.g., Transparent or UUPS proxies) to allow for future improvements without migrating user positions. Finally, engage with the developer community by publishing clear documentation, SDKs, and subgraph for data indexing. The architecture is a foundation; its long-term success depends on vigilant maintenance, transparent governance, and continuous adaptation to the evolving DeFi landscape.