Loan Smart Contract Structure
This document provides a detailed technical explanation of the Nebeus Lending Smart Contract, focusing on loan parameters, processes for issuing loans, handling collateral, managing repayments, and handling events like margin calls and liquidation. Additionally, it highlights how borrowers interact with the smart contract, including the address for collateral deposits and repayments, which are typically the same on the network.
Loan Parameters
The smart contract uses a structured approach to manage input and calculated values for loans. These parameters are divided into User Input and Backend Input.
1. User Input Parameters
These are the parameters provided by the borrower when creating a loan:
borrower
address
Wallet address of the borrower.
loanAmount
uint256
Amount of the loan in loan currency.
loanAmountCurrency
string
Currency of the loan (e.g., USD).
collateralAmountCurrency
string
Currency of the collateral (e.g., ETH).
term
uint256
Loan term in seconds (e.g., 30 days = 2592000).
2. Backend Input Parameters
These values are calculated or provided by the backend based on user input and real-time data:
collateralAmount
uint256
Amount of collateral required (in wei).
loanAmountRateUSD
uint256
USD value of the loan amount.
collateralAmountRateUSD
uint256
USD value of the collateral.
interestRate
uint256
Annualized interest rate (percentage).
originationFee
uint256
Fee for loan origination (percentage).
totalRepaymentAmount
uint256
Total amount to be repaid by the borrower.
startDate
uint256
Timestamp of loan start.
endDate
uint256
Timestamp of loan end.
LTV
uint256
Loan-to-Value ratio (percentage).
Loan Issuance Process
Step-by-Step Process
Loan Creation:
Borrower calls the
createLoanfunction with user input parameters.Backend calculates
collateralAmount,originationFee,totalRepaymentAmount, and other values.Borrower sends the
collateralAmountwith the transaction (msg.value).Show Address for Collateral and Loan Repayment:
The contract's deployed address (
address(this)) serves as the collateral deposit address and loan repayment address.Borrowers can view this address in the frontend or directly in the transaction metadata.
Validation:
collateralAmount > 0msg.value == collateralAmount
Collateral Locking:
The contract locks the collateral at its address (
collateralAddress).A new loan is created with the
LoanStatus.Newstatus.
Loan Activation:
Upon collateral receipt, the loan is activated (
LoanStatus.Active).Event:
LoanCreated.
Loan Parameters Calculations
Collateral Amount:
Origination Fee:
Net Loan Amount (After Fee):
Total Repayment Amount:
Dynamic Interest Rate Model
The Nebeus DeFi Lending Protocol employs a dynamic interest rate model to balance liquidity and optimize the use of capital within its lending pools. This system adjusts borrowing costs based on the Utilization Rate, ensuring efficient capital utilization, stable liquidity, and competitive returns.
Key Principles
Low Utilization (U ≤ Uₒₔₚₐ₁):
When the pool's utilization rate is low, interest rates increase slowly.
Encourages borrowing by maintaining low costs during high liquidity periods.
High Utilization (U > Uₒₔₚₐ₁):
As pool utilization exceeds the optimal level, interest rates rise sharply.
Motivates borrowers to repay loans and attracts additional liquidity into the pool.
Simplified Interest Rate Parameters
Optimal Utilization (Uₒₔₚₐ₁)
Target capital usage level where the interest rate slope changes.
Base Rate
Minimum interest rate when no funds are utilized.
Slope 1
Rate of interest increase below the optimal utilization level.
Slope 2
Steeper rate of interest increase above the optimal utilization level.
These parameters are tailored to reflect the volatility and liquidity of each asset, ensuring the protocol remains stable and competitive.
Interest Rate Formulas
Borrowing Interest Rate:
Supply Rate: The supply rate, representing the return earned by liquidity providers, is calculated as:
Stable vs. Variable Interest Rates
Variable Rates:
Adjust dynamically with pool utilization.
Suitable for borrowers seeking potentially lower rates while tolerating market fluctuations.
Supply Rate and Liquidity Pool Integration
The Nebeus Lending Smart Contract interacts with a Liquidity Pool contract to dynamically calculate the Supply Rate based on the pool’s liquidity utilization.
Liquidity Pool contract address can be the same as Lending contract address to optimize inter-contract payment costs.
Liquidity Utilization Rate
The Utilization Rate (U) determines how much of the liquidity pool's funds are currently loaned out. It is calculated as:
Total Borrowed Funds: Sum of all active loans in the pool.
Total Available Liquidity: Total funds deposited in the pool minus borrowed funds.
Supply Rate Calculation
The Supply Rate is the return earned by liquidity providers (depositors) in the pool. It is derived from the Borrowing Interest Rate and the Utilization Rate:
Utilization Rate: Proportion of funds loaned out from the pool.
Borrowing Interest Rate: Rate paid by borrowers, dynamically adjusted based on utilization.
Reserve Factor: A small percentage of interest payments reserved for the protocol's sustainability.
Supply Rate Parameters
Borrowing Interest Rate
Dynamic rate determined by utilization (see Interest Rate Model).
Reserve Factor
Example: 10% (i.e., 0.1), meaning 10% of interest payments go to the protocol.
Liquidity Pool Contract Address
Address of the pool managing the funds.
Liquidity Pool Smart Contract Address
The smart contract interacts with a dedicated Liquidity Pool contract to fetch the required values for supply rate calculations:
Liquidity Pool Contract:
Tracks deposits, withdrawals, and active loans.
Maintains the current available liquidity and borrowed funds.
Dynamic Supply Rate Workflow
Fetch Pool Data:
Retrieve
Total Borrowed FundsandTotal Available Liquidityfrom the Liquidity Pool contract:
Calculate Utilization Rate:
Calculate Supply Rate: Using the Borrowing Interest Rate, compute the supply rate:
Update Rates:
Rates are updated periodically (e.g., every 2 hours) or upon significant utilization changes.
Code Example: Supply Rate Integration
Collateral Handling
1. Sending Collateral
Borrower sends the calculated collateral amount (collateralAmount) during loan creation:
Input:
collateralAmountis passed asmsg.value(for ETH) or via ERC-20 transfer (for tokens).
Validation:
Collateral amount must match the backend-calculated value.
2. Adding Collateral
Borrower can add additional collateral to secure their loan:
Function:
Logic:
Updates the
collateralAmount.Recalculates the collateral-to-loan ratio (CLR).
Emits
CollateralAdded.
What is Collateral-to-Loan Ratio (CLR) - Risk Management?
CLR Formula
- How CLR Works
Healthy CLR:
When the CLR is high (e.g., above 150%), the loan is secure.
Borrowers do not need to add collateral.
Margin Call Threshold:
If the CLR falls below a predefined threshold (e.g., 115%), a margin call is issued.
Borrowers are required to add collateral to restore the CLR.
Liquidation Threshold:
If the CLR falls below the liquidation threshold (e.g., 110%), the loan is liquidated.
Collateral is redistributed to cover the loan.
Receiving Loan Amount
The loan amount sent to the borrower is net of the origination fee, and the transfer method depends on the requested loanAmountCurrency.
Flow:
The smart contract calculates the origination fee based on the loan amount and the predefined fee rate.
The net loan amount is calculated as:
The contract transfers the
netLoanAmountto the borrower based on the requestedloanAmountCurrency:Native Token (e.g., ETH): The loan is transferred directly to the borrower's wallet using
payable:ERC-20 Token (e.g., USDC, USDT): The loan is transferred using the ERC-20
transferfunction:
Code Example:
Repayment
Borrower repays the loan to retrieve their collateral:
Function:
Logic:
Validates repayment amount matches
totalRepaymentAmount.Collateral is returned to the borrower.
Flow:
Borrower sends repayment to the smart contract address.
Contract verifies the amount matches
totalRepaymentAmount.Collateral is unlocked and transferred back to the borrower.
Risk Managment
Obtaining Current Exchange Rates
The Nebeus Lending Smart Contract integrates with the CCData API to fetch real-time exchange rates. This ensures accurate calculations for the Collateral-to-Loan Ratio (CLR) and allows dynamic management of loan security. The API endpoint used is:
CCData API Endpoint
Purpose: Fetch the current USD value of the specified
loanAmountCurrencyandcollateralAmountCurrency.
Integration Process
API Request:
A backend service calls the
SingleSymbolPriceEndpointto fetch the current price of a specified symbol in USD.Example API Request:
API Response:
The API returns the current exchange rate in USD.
Example Response:
Storing Exchange Rates:
The backend updates the
loanAmountRateUSDandcollateralAmountRateUSDparameters in the smart contract.Example:
Recalculating CLR and Rate Updates
The Collateral-to-Loan Ratio (CLR) is recalculated periodically to ensure the loan's security status remains accurate. CLR is affected by exchange rate fluctuations, and regular updates are crucial for risk management.
CLR Formula
Recalculation Intervals
Rate Update Frequency: Exchange rates are updated at a fixed interval, e.g., every 2 hours.
CLR Update:
After each rate update, CLR is recalculated using the new rates for
collateralAmountCurrencyandloanAmountCurrency.
Workflow for Rate Updates and CLR Recalculation
Fetch Exchange Rates:
Use the CCData API to fetch the current exchange rates for the loan and collateral currencies in USD.
Update Exchange Rates:
The backend updates the smart contract with the latest rates:
Recalculate CLR:
Calculate the new CLR using the updated rates:
Trigger Margin Call or Liquidation:
If CLR falls below the Margin Call Rate, a margin call is issued.
If CLR falls below the Liquidation Threshold, the loan is liquidated.
Event: ExchangeRateUpdated
An event is emitted whenever exchange rates are updated and CLR is recalculated:
Code Example for Rate Updates and CLR Recalculation
Liquidation Threshold
What is the Liquidation Threshold?
The Liquidation Threshold is the minimum Collateral-to-Loan Ratio (CLR) required to keep a loan active. If the CLR drops below this threshold, the loan is considered under-collateralized, and the liquidation process is triggered to protect lenders from losses.
Liquidation Threshold Parameters
liquidationThreshold
uint256
The minimum CLR percentage before liquidation occurs. Default value: 110%.
Default Liquidation Threshold Value
Liquidation Threshold: 110%
This means the value of the collateral must be at least 110% of the loan value. For example:
If the loan value is $1,000, the collateral value must remain at or above $1,100.
If the collateral value drops below $1,100, the loan enters the liquidation process.
Liquidation Process
How Liquidation is Triggered
CLR Falls Below Liquidation Threshold:
The contract monitors CLR, recalculating it at regular intervals using updated exchange rates.
If
CLR < liquidationThreshold, the loan status is updated toLoanStatus.Liquidation.
Initiating Liquidation:
A liquidator or external entity repays the loan on behalf of the borrower.
The collateral is redistributed to the liquidator based on the loan's collateral-to-loan value ratio.
Liquidation Workflow
CLR Calculation:
Example:
Collateral Value: $1,050
Loan Value: $1,000
CLR =
(1050 / 1000) * 100 = 105%(Liquidation Triggered).
Collateral Distribution Rules:
If CLR < 110%, the liquidator receives the full collateral.
If CLR is between 110% and 130%, partial collateral is returned (adjusted by contract rules).
If CLR > 130%, additional collateral is provided to the liquidator as a bonus.
Liquidator Process:
The liquidator calls the
liquidateLoanfunction, repays the loan, and receives the collateral.Loan status is updated to
Completed.
Recalculating CLR and Rate Updates
The Collateral-to-Loan Ratio (CLR) is recalculated periodically to ensure the loan's security status remains accurate. CLR is affected by exchange rate fluctuations, and regular updates are crucial for risk management.
Recalculation Intervals
Rate Update Frequency: Exchange rates are updated at a fixed interval, e.g., every 2 hours.
CLR Update:
After each rate update, CLR is recalculated using the new rates for
collateralAmountCurrencyandloanAmountCurrency.
Workflow for Liquidation and CLR Recalculation
Fetch Exchange Rates:
Use the CCData API to fetch the current exchange rates for the loan and collateral currencies in USD.
Update Exchange Rates:
The backend updates the smart contract with the latest rates:
Recalculate CLR:
Calculate the new CLR using the updated rates:
Trigger Margin Call or Liquidation:
If CLR falls below the Margin Call Rate, a margin call is issued.
If CLR falls below the Liquidation Threshold, the loan is liquidated.
Code Example for Liquidation Process
Event: LoanLiquidated
An event is emitted whenever a loan is liquidated:
Returning Collateral
Upon successful repayment of the loan, the collateral is released back to the borrower. The smart contract ensures that the correct amount and currency of the collateral are returned by implementing strict validation and currency type checks.
Process for Returning Collateral
Repayment Validation:
Ensure the borrower has repaid the totalRepaymentAmount in the correct currency.
The repayment currency is checked against the
loanAmountCurrency.
Collateral Return Logic:
Check the
collateralAmountCurrencystored in the loan structure.Based on the
collateralAmountCurrency, the contract differentiates between native tokens (e.g., ETH) and ERC-20 tokens.
Return Collateral Based on Currency:
Native Token (e.g., ETH):
The
collateralAmountis returned using thetransferfunction:
ERC-20 Token (e.g., USDC, WBTC):
The collateral is returned using the
transferfunction of the respective ERC-20 token:
Update Loan Status:
Mark the loan as
Completedonce the collateral is successfully returned.
Additional Controls
To ensure correctness and security, the following controls are implemented:
Collateral Amount Check:
Validate that the
collateralAmountbeing returned matches the amount locked in the contract for the loan:
Collateral Currency Check:
Ensure that the
collateralAmountCurrencymatches the expected token type:
Repayment Confirmation:
Validate that the loan repayment matches the
totalRepaymentAmount:
Code Example for Returning Collateral
Event: CollateralReturned
The smart contract emits an event upon successful collateral return:
Parameters:
loanId: The unique ID of the loan.borrower: The address of the borrower.collateralAmount: The amount of collateral returned.collateralCurrency: The currency of the returned collateral.
Liquidation Process and Liquidators
When a loan enters the Liquidation status (i.e., LoanStatus.Liquidation), liquidators are allowed to repay the loan amount on behalf of the borrower. In return, the liquidators obtain the collateral associated with the loan, depending on the collateral-to-loan ratio (CLR) at the time of liquidation.
Liquidation Workflow
Loan Enters Liquidation Status:
When the CLR drops below the predefined
liquidationThreshold(e.g., 110%), the loan is marked asLoanStatus.Liquidation.An event
LoanLiquidationAvailableis emitted to notify liquidators:
Liquidator Interaction:
Liquidators can call the
liquidateLoanfunction to repay the loan and receive the collateral.The loan's CLR determines how much collateral the liquidator receives:
CLR < 110%: Liquidator receives the full collateral.
110% ≤ CLR ≤ 130%: Liquidator receives 95% of the collateral.
CLR > 130%: Liquidator receives 90% of the collateral, and the borrower retains the excess.
Collateral Distribution:
The smart contract redistributes the collateral based on the above conditions, ensuring fair compensation for the liquidator while protecting the borrower's rights.
API for Liquidators
The contract exposes the following API functions for liquidators to interact with loans in liquidation status:
1. Get Liquidation Details
Function:
getLoanLiquidationDetails(uint256 loanId)Description: Fetches liquidation details for a loan.
Input:
loanId: The unique ID of the loan.
Output:
loanAmount: Loan amount in the loan currency.collateralAmount: Total collateral amount locked.CLR: Current CLR of the loan.liquidationThreshold: CLR threshold for liquidation.status: Current loan status.
2. Liquidate Loan
Function:
liquidateLoan(uint256 loanId)Description: Allows liquidators to repay the loan and claim the collateral.
Access: External.
Input:
loanId: The unique ID of the loan.
Validation:
Loan must be in
LoanStatus.Liquidation.Liquidator must repay the full
totalRepaymentAmount.
Logic:
Calculates CLR:
Distributes collateral:
Transfers collateral:
Native Tokens (e.g., ETH):
ERC-20 Tokens:
Updates loan status:
Code Example for Liquidation API
Event: LoanLiquidated
An event is emitted when a loan is successfully liquidated:
Parameters:
loanId: The unique ID of the liquidated loan.liquidator: The address of the liquidator.clrAtLiquidation: The CLR at the time of liquidation.collateralSent: Amount of collateral sent to the liquidator.timestamp: Time of liquidation.
Workflow for Liquidators
Check Liquidation Status:
Use the
getLoanLiquidationDetailsAPI to identify loans eligible for liquidation.
Repay Loan:
Call the
liquidateLoanfunction, providing the repayment amount in the loan currency.
Receive Collateral:
The liquidator receives the collateral based on the loan's CLR at the time of liquidation.
Workflow Summary
Loan Creation:
Borrower specifies loan parameters and provides collateral.
Contract locks collateral and disburses the net loan amount.
Active Loan Monitoring:
Exchange rates are updated periodically.
CLR is recalculated to ensure the loan is secure.
Margin Call:
Triggered if CLR drops below the margin call rate.
Borrower is notified to add collateral.
Liquidation:
If CLR drops below the liquidation threshold, collateral is liquidated.
Repayment:
Borrower repays the loan amount plus interest.
Contract releases the collateral.
Last updated
