Defi Lending Protocol Architecture

Comprehensive guide for defi lending protocol architecture covering essential concepts, practical examples, and production best practices.

Defi Lending Protocol Architecture is the blueprint for how decentralized protocols enable users to deposit collateral, borrow assets, and manage risk across multiple lending markets. It matters when capital efficiency, interest rate dynamics, and collateral health must be maintained under unpredictable market conditions, with minimal latency and maximum reliability.

Core Operations

Deposit Collateral

To deposit collateral, a user sends a transaction to a lending pool contract with the asset and amount. The protocol must update the user’s balance, adjust pool-wide metrics, and emit an event for downstream systems.

function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

The transaction includes:

On success, the protocol emits:

{
  "name": "Deposit",
  "transactionHash": "0x...",
  "args": {
    "reserve": "0x1234...",
    "user": "0x5678...",
    "onBehalfOf": "0x5678...",
    "amount": "1000000000000000000",
    "referralCode": 1234
  }
}

Failure occurs if:

The protocol uses a two-phase approach:

  1. Token transfer: IERC20(asset).transferFrom(msg.sender, address(this), amount)
  2. Internal accounting: update user’s depositBalance, totalDeposited, and userState

A common failure mode is stale balances due to delayed sync between the depositBalance and totalDeposited values. This happens when multiple deposits are processed concurrently without proper locking, leading to over- or under-accounting.

Borrow Funds

Borrowing is triggered by a borrow call with the selected reserve, desired amount, and interest rate mode.

function borrow(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf, uint16 referralCode) external;

Key parameters:

The protocol:

  1. Validates that the asset is active and has liquidity
  2. Checks that the user has sufficient collateral in the system
  3. Updates the user’s borrowBalance, totalBorrowed, and userState
  4. Transfers amount of asset to onBehalfOf
  5. Emits Borrow event
{
  "name": "Borrow",
  "transactionHash": "0x...",
  "args": {
    "reserve": "0x1234...",
    "user": "0x5678...",
    "onBehalfOf": "0x5678...",
    "amount": "500000000000000000",
    "interestRateMode": 2,
    "referralCode": 1234
  }
}

Common failure modes:

A subtle failure occurs when interestRateMode is set to 1 (variable) but the user’s previous borrow was stable, and the protocol fails to properly update the lastInterestIndex for the reserve. This leads to inconsistent interest accruals.

Repay Loan

Repayment is done via repay with the asset, amount, and optional onBehalfOf.

function repay(address asset, uint256 amount, address onBehalfOf, uint256 interestRateMode) external;

The protocol:

  1. Transfers amount of asset from msg.sender to the lending pool
  2. Updates totalBorrowed and userState.borrowBalance
  3. Updates lastUpdated and interestIndex for the reserve
  4. Emits Repay event
{
  "name": "Repay",
  "transactionHash": "0x...",
  "args": {
    "reserve": "0x1234...",
    "user": "0x5678...",
    "onBehalfOf": "0x5678...",
    "amount": "750000000000000000",
    "interestRateMode": 1
  }
}

Critical edge cases:

A silent failure arises when the repayment is processed but the interestIndex is not updated. This causes future interest calculations to be based on stale values, leading to underpayment of interest over time.

Risk Management

Health Factor Calculation

The health factor determines whether a user is at risk of liquidation. It is computed as:

healthFactor = (totalCollateralValue * 1000) / totalBorrowedValue

Where:

The protocol checks health factor before every operation:

Liquidation is triggered when health factor falls below 1.0. The protocol emits LiquidationCall event:

{
  "name": "LiquidationCall",
  "transactionHash": "0x...",
  "args": {
    "reserve": "0x1234...",
    "borrower": "0x5678...",
    "liquidator": "0x9abc...",
    "debtToCover": "2000000000000000000",
    "collateralAmount": "1500000000000000000",
    "liquidationRatio": "1100"
  }
}

Liquidation Process

Liquidation is a multi-step process:

  1. A liquidator calls liquidate with borrower, collateralAsset, debtAsset, and maxDebtToCover
  2. The protocol:

The liquidationRatio is a protocol-wide parameter that determines how much collateral is required to cover one unit of debt. A ratio of 1100 means 1.1 units of collateral are needed to cover 1 unit of debt.

Critical failure modes:

System Integration

Price Oracles

Price oracles feed real-time asset prices to the protocol. The protocol uses a getAssetPrice(address asset) function that returns a uint256 price in 18 decimals (e.g., 1 ETH = 1,000,000,000,000,000,000 wei).

The oracle is queried on every operation:

Failure occurs when:

The protocol uses a time-weighted average price (TWAP) over a 24-hour window. The TWAP is computed as:

TWAP = sum( price[i] * duration[i] ) / sum( duration[i] )

Where duration[i] is the time interval between price[i-1] and price[i].

A common failure is oracle drift — the oracle reports a price that is higher than the actual on-chain price, leading to overvaluation of collateral and false health factors.

Interest Rate Models

The protocol supports two interest rate models:

The variable rate is computed using a kink-based model:

function calculateInterestRate(address reserve, uint256 utilizationRate) external view returns (uint256 rate);

The model uses:

For utilization u:

A common failure is interest rate lag — the rate is updated infrequently, leading to inconsistent interest accruals. The protocol uses a lastUpdated timestamp and interestIndex to track interest accruals.

When a user deposits or borrows, the protocol:

  1. Computes newInterestIndex = oldInterestIndex + (elapsedTime * currentRate)
  2. Updates reserve.interestIndex = newInterestIndex

If elapsedTime is computed as block.timestamp - reserve.lastUpdated, but block.timestamp is not synchronized with the lastUpdated timestamp, interest accruals become inaccurate.

Event Processing and Indexing

The protocol emits events for every operation. These are consumed by downstream systems using eth_getLogs with filters.

Example query:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "eth_getLogs",
  "params": [
    {
      "fromBlock": "0x123456",
      "toBlock": "0x123457",
      "address": "0x1234567890123456789012345678901234567890",
      "topics": [
        "0x65b2817b80f338b0f3781c135f0517e293c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5"
      ]
    }
  ]
}

The topics array contains the event signature (e.g., Deposit event hash). The fromBlock and toBlock define the range of blocks to scan.

Common failure modes:

Configuration and Deployment

The protocol is deployed as a set of contracts, each with a config storage layout. The configuration includes:

Example configuration:

{
  "reserves": [
    "0x1234567890123456789012345678901234567890",
    "0x2345678901234567890123456789012345678901"
  ],
  "reservesConfig": {
    "0x1234567890123456789012345678901234567890": {
      "baseLTV": 7000,
      "liquidationThreshold": 8000,
      "liquidationBonus": 1050,
      "reserveFactor": 1000,
      "borrowingEnabled": true,
      "stableBorrowingEnabled": true,
      "interestRateModel": "variable"
    },
    "0x2345678901234567890123456789012345678901": {
      "baseLTV": 6500,
      "liquidationThreshold": 7500,
      "liquidationBonus": 1025,
      "reserveFactor": 1250,
      "borrowingEnabled": true,
      "stableBorrowingEnabled": false,
      "interestRateModel": "stable"
    }
  },
  "protocolFee": 250,
  "flashLoanPremium": 10000
}

Deployment is orchestrated using hardhat:

npx hardhat deploy --network mainnet --tags lending

The --tags flag selects which contracts to deploy. The deploy script uses deployments directory with deployments/mainnet/ for the mainnet deployment.

A common failure is mismatched configuration: the reservesConfig in the contract does not match the config object in the deployment script. This leads to incorrect LTVs, liquidation thresholds, and interest rate models.

Monitoring and Failure Detection

The protocol is monitored via:

A failure is detected when:

Alerts are triggered when:

The protocol logs errors using emit LogError(string message, bytes data) with data encoding the error context.

A silent failure occurs when the protocol updates interestIndex but fails to update lastUpdated. This causes interest accruals to be based on incorrect timestamps, leading to interest that is either too high or too low.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.