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.
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:
asset: ERC20 token addressamount: wei amount of the assetonBehalfOf: address receiving the deposit (may differ from sender)referralCode: optional 16-bit code for referral trackingOn success, the protocol emits:
{
"name": "Deposit",
"transactionHash": "0x...",
"args": {
"reserve": "0x1234...",
"user": "0x5678...",
"onBehalfOf": "0x5678...",
"amount": "1000000000000000000",
"referralCode": 1234
}
}
Failure occurs if:
asset is not a registered reserveamount is zeroonBehalfOf is nullmsg.value does not match amount for native assets (e.g., ETH)The protocol uses a two-phase approach:
IERC20(asset).transferFrom(msg.sender, address(this), amount)depositBalance, totalDeposited, and userStateA 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.
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:
asset: the token to borrowamount: amount in weiinterestRateMode: 1 for variable, 2 for stableonBehalfOf: borrower addressreferralCode: optionalThe protocol:
borrowBalance, totalBorrowed, and userStateamount of asset to onBehalfOfBorrow 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.
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:
amount of asset from msg.sender to the lending pooltotalBorrowed and userState.borrowBalancelastUpdated and interestIndex for the reserveRepay event{
"name": "Repay",
"transactionHash": "0x...",
"args": {
"reserve": "0x1234...",
"user": "0x5678...",
"onBehalfOf": "0x5678...",
"amount": "750000000000000000",
"interestRateMode": 1
}
}
Critical edge cases:
amount < userState.borrowBalance, only part of the loan is repaidinterestRateMode is 1, the repayment is applied to the variable rate pool, but the protocol may fail to update the variableBorrowIndex correctlyassetB but the loan is in assetA. The protocol must convert the repayment amount using the current exchange rateA 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.
The health factor determines whether a user is at risk of liquidation. It is computed as:
healthFactor = (totalCollateralValue * 1000) / totalBorrowedValue
Where:
totalCollateralValue = sum over all assets: balance * price * (1 - liquidationBonus)totalBorrowedValue = sum over all borrowed assets: borrowBalance * priceThe protocol checks health factor before every operation:
deposit: if health factor < 1.0, user is undercollateralizedborrow: if health factor < 1.0 after borrowing, the user is at riskwithdraw: if health factor drops below 1.0, the user may be liquidatedLiquidation 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 is a multi-step process:
liquidate with borrower, collateralAsset, debtAsset, and maxDebtToCoverdebtToCover as the minimum between maxDebtToCover and userState.borrowBalance[debtAsset]debtToCover from msg.sender to the poolcollateralAmount from the pool to liquidatortotalBorrowed, userState, and reserve stateLiquidationCall and LiquidationCompleteThe 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:
collateralAmount is less than required, the liquidator must cover the shortfallmaxDebtToCover is too large, the protocol may repay more than necessary, leaving excess funds in the systemPrice 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:
depositborrowrepayliquidateupdateInterestFailure occurs when:
getAssetPrice returns 0asset is not in the oracle mappingThe 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.
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:
baseVariableRate: rate at 0% utilizationvariableRateSlope1: rate increase per 100% utilization up to kinkvariableRateSlope2: rate increase per 100% utilization above kinkkink: utilization rate at which slope changesFor utilization u:
u <= kink: rate = baseVariableRate + (u * variableRateSlope1)u > kink: rate = baseVariableRate + (kink * variableRateSlope1) + ((u - kink) * variableRateSlope2)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:
newInterestIndex = oldInterestIndex + (elapsedTime * currentRate)reserve.interestIndex = newInterestIndexIf elapsedTime is computed as block.timestamp - reserve.lastUpdated, but block.timestamp is not synchronized with the lastUpdated timestamp, interest accruals become inaccurate.
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:
The protocol is deployed as a set of contracts, each with a config storage layout. The configuration includes:
reserves: list of registered assetsreservesConfig: mapping from asset address to ReserveConfigurationliquidationThreshold: default LTV for all reservesliquidationBonus: default bonus for liquidationprotocolFee: fee taken from every deposit and borrowflashLoanPremium: premium for flash loansExample 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.
The protocol is monitored via:
eth_getBalance on the lending pool contracteth_getStorageAt to read interestIndex and totalBorrowedeth_call to execute getAssetPrice and getReserveDataA failure is detected when:
getReserveData(reserve).totalBorrowed is zero but totalDeposited is non-zerogetAssetPrice(asset) returns 0getReserveData(reserve).interestIndex is stale (difference > 1 hour)getReserveData(reserve).utilizationRate is inconsistent with totalBorrowed / totalDepositedAlerts 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.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy