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:

Parameter
Type
Description

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:

Parameter
Type
Description

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

  1. Loan Creation:

    • Borrower calls the createLoan function with user input parameters.

    • Backend calculates collateralAmount, originationFee, totalRepaymentAmount, and other values.

    • Borrower sends the collateralAmount with 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 > 0

    • msg.value == collateralAmount

  2. Collateral Locking:

    • The contract locks the collateral at its address (collateralAddress).

    • A new loan is created with the LoanStatus.New status.

  3. 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

  1. 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.

  2. 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

Parameter
Description

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

  1. Borrowing Interest Rate:

  2. Supply Rate: The supply rate, representing the return earned by liquidity providers, is calculated as:


Stable vs. Variable Interest Rates

  1. Variable Rates:

    • Adjust dynamically with pool utilization.

    • Suitable for borrowers seeking potentially lower rates while tolerating market fluctuations.

  2. Stable Rates:

    • Locked in at the time of borrowing for predictability.

    • Typically higher than variable rates to account for market stability.

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 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

Parameter
Description

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

  1. Fetch Pool Data:

    • Retrieve Total Borrowed Funds and Total Available Liquidity from the Liquidity Pool contract:

  2. Calculate Utilization Rate:

  3. Calculate Supply Rate: Using the Borrowing Interest Rate, compute the supply rate:

  4. 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:

    • collateralAmount is passed as msg.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.


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:

  1. The smart contract calculates the origination fee based on the loan amount and the predefined fee rate.

  2. The net loan amount is calculated as:

  3. The contract transfers the netLoanAmount to the borrower based on the requested loanAmountCurrency:

    • 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 transfer function:

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:

  1. Borrower sends repayment to the smart contract address.

  2. Contract verifies the amount matches totalRepaymentAmount.

  3. 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

Integration Process

  1. API Request:

    • A backend service calls the SingleSymbolPriceEndpoint to fetch the current price of a specified symbol in USD.

    • Example API Request:

  2. API Response:

    • The API returns the current exchange rate in USD.

    • Example Response:

  3. Storing Exchange Rates:

    • The backend updates the loanAmountRateUSD and collateralAmountRateUSD parameters 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 collateralAmountCurrency and loanAmountCurrency.


Workflow for Rate Updates and CLR Recalculation

  1. Fetch Exchange Rates:

    • Use the CCData API to fetch the current exchange rates for the loan and collateral currencies in USD.

  2. Update Exchange Rates:

    • The backend updates the smart contract with the latest rates:

  3. Recalculate CLR:

    • Calculate the new CLR using the updated rates:

  4. 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

Parameter
Type
Description

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

  1. 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 to LoanStatus.Liquidation.

  2. 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

  1. CLR Calculation:

    Example:

    • Collateral Value: $1,050

    • Loan Value: $1,000

    • CLR = (1050 / 1000) * 100 = 105% (Liquidation Triggered).

  2. 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.

  3. Liquidator Process:

    • The liquidator calls the liquidateLoan function, 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 collateralAmountCurrency and loanAmountCurrency.


Workflow for Liquidation and CLR Recalculation

  1. Fetch Exchange Rates:

    • Use the CCData API to fetch the current exchange rates for the loan and collateral currencies in USD.

  2. Update Exchange Rates:

    • The backend updates the smart contract with the latest rates:

  3. Recalculate CLR:

    • Calculate the new CLR using the updated rates:

  4. 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

  1. Repayment Validation:

    • Ensure the borrower has repaid the totalRepaymentAmount in the correct currency.

    • The repayment currency is checked against the loanAmountCurrency.

  2. Collateral Return Logic:

    • Check the collateralAmountCurrency stored in the loan structure.

    • Based on the collateralAmountCurrency, the contract differentiates between native tokens (e.g., ETH) and ERC-20 tokens.

  3. Return Collateral Based on Currency:

    • Native Token (e.g., ETH):

      • The collateralAmount is returned using the transfer function:

    • ERC-20 Token (e.g., USDC, WBTC):

      • The collateral is returned using the transfer function of the respective ERC-20 token:

  4. Update Loan Status:

    • Mark the loan as Completed once the collateral is successfully returned.

Additional Controls

To ensure correctness and security, the following controls are implemented:

  1. Collateral Amount Check:

    • Validate that the collateralAmount being returned matches the amount locked in the contract for the loan:

  2. Collateral Currency Check:

    • Ensure that the collateralAmountCurrency matches the expected token type:

  3. 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

  1. Loan Enters Liquidation Status:

    • When the CLR drops below the predefined liquidationThreshold (e.g., 110%), the loan is marked as LoanStatus.Liquidation.

    • An event LoanLiquidationAvailable is emitted to notify liquidators:

  2. Liquidator Interaction:

    • Liquidators can call the liquidateLoan function 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.

  3. 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

  1. Check Liquidation Status:

    • Use the getLoanLiquidationDetails API to identify loans eligible for liquidation.

  2. Repay Loan:

    • Call the liquidateLoan function, providing the repayment amount in the loan currency.

  3. Receive Collateral:

    • The liquidator receives the collateral based on the loan's CLR at the time of liquidation.


Workflow Summary

  1. Loan Creation:

    • Borrower specifies loan parameters and provides collateral.

    • Contract locks collateral and disburses the net loan amount.

  2. Active Loan Monitoring:

    • Exchange rates are updated periodically.

    • CLR is recalculated to ensure the loan is secure.

  3. Margin Call:

    • Triggered if CLR drops below the margin call rate.

    • Borrower is notified to add collateral.

  4. Liquidation:

    • If CLR drops below the liquidation threshold, collateral is liquidated.

  5. Repayment:

    • Borrower repays the loan amount plus interest.

    • Contract releases the collateral.

Last updated