Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Integration & Porting Guide

This document outlines the steps required to port the frontend from the old architecture to the new smart contract system.

Goals & Scope

The primary goal is to reach a functional state suitable for audit. The frontend must support the following workflows:

  1. User Actions:
    • USDC Deposit
    • Collateral Deposit
    • Borrow USDC
    • Withdraw USDC
    • Withdraw Collateral
    • Repayment of USDC
  2. State Display:
    • Show current protocol state information.

Core Smart Contract Methods

To retrieve data, you will primarily interact with two view-only methods. It is essential to understand the data structures they return.

1. get_config

Returns ContractConfigView, which contains protocol configuration parameters.

#![allow(unused)]
fn main() {
pub struct ContractConfigView {
    pub owner_id: AccountId,
    pub liquidation_threshold: Decimal,
    pub borrow_threshold: Decimal,
    pub withdraw_threshold: Decimal,
    pub liquidation_penalty: Decimal,
    pub pyth_oracle_contract: AccountId,
    pub usdc_base_borrow_rate: Decimal,
    pub usdc_rate_multiplier: Decimal,
    pub insurance_allocation_rate: Decimal,
    pub liquidator_account: AccountId,
    pub intents_contract: AccountId,
    pub oracle_price_staleness_secs: u64,
    pub supported_collaterals: HashMap<CollateralContract, CollateralMetadata>,
    pub supported_usdc_token: Option<UsdcTokenView>,
    pub pyth_required_deposit: NearToken,
}
}

2. get_contract_state

Returns ContractState, which contains the dynamic state of the protocol (liquidity, shares, indexes, etc.).

#![allow(unused)]
fn main() {
pub struct ContractState {
    /// Protocol's cash-on-hand (available for withdrawal/borrowing).
    pub usdc_liquidity: Usdc,
    pub collateral_liquidity: IterableMap<CollateralContract, RawAmount>,
    /// Total lending shares for USDC.
    pub total_supplied_usdc_shares: LendingShare,
    /// Total borrow shares for USDC.
    pub total_borrowed_usdc_shares: BorrowShare,
    /// User data
    pub users: near_sdk::store::IterableMap<UserId, User>,
    /// Index to track interest accrued for USDC suppliers.
    /// User supply balance = `supplied_usdc_shares` * `usdc_supply_index`.
    pub usdc_supply_index: LendingIndex,
    /// Index to track interest accrued on USDC borrows.
    /// User borrow balance = `borrowed_usdc_shares` * `usdc_borrow_index`.
    pub usdc_borrow_index: BorrowIndex,
    /// Timestamp of the last interest accrual.
    pub last_interest_accrual_timestamp: Timestamp,
    /// Protocol's accumulated bad debt in USDC.
    pub bad_debt_usdc: Usdc,
    /// Protocol's insurance fund.
    pub insurance_fund: Usdc,
    /// Oracle Prices.
    pub prices: LookupMap<UsdPythIdentifier, PythPrice>,
    /// State of any ongoing liquidation.
    pub liquidation: Option<LiquidationInfo>,
    /// Tracks pending liquidations.
    pub pending_liquidations: Vector<UserId>,
    /// Unpaid fees to be paid to the liquidator.
    pub unpaid_liquidator_fee: Usdc,
    /// Unpaid surplus amounts to be transferred to users after liquidation.
    pub pending_surplus_transfers: LookupMap<UserId, Usdc>,
    /// The number of users registered with the contract.
    pub user_count: u64,
}
}

3. get_user(user_id: UserId)

Returns the User struct, containing specific data for a single user.

#![allow(unused)]
fn main() {
pub struct User {
    // Amounts of non-USDC collateral.
    pub collateral: HashMap<CollateralContract, RawAmount>,
    // User's position in the USDC market (supplier, borrower, or neither).
    pub usdc_position: UsdcPosition,
    // The current in-flight operation for this user, if any.
    pub in_flight_operation: Option<InFlightOperation>,
    /// Storage balance
    pub storage_balance: NearToken,
}

pub enum UsdcPosition {
    #[default]
    None,
    Supplied(LendingShare),
    Borrowed(BorrowShare),
}
}

Backend API Migration (Indexer & Querier)

This section maps old backend endpoints to the new logic using ContractState and ContractConfigView.

Summary Table

Old QueryEndpointNew Logic Summary
transactionsQuery/transactions/account/{accountId}Deferred to V2 (Indexer API).
indexerTotalBorrowedQuery/borrows/total_borrowedtotal_borrowed_usdc_shares * usdc_borrow_index
indexerTotalFeesQuery/fees/total/interest_and_penaltiesinsurance_fund + Liquidator Account Balance
indexerAccountsQuery/accountsuser_count
indexerProtocolLtvQuery/dashboard/ltvTotal Borrowed / Total Collateral Value
indexerTokenCollateralQuery/dashboard/token_collateralSum of all collateral values (USD).
indexerTotalStablecoinDepositedQuery/token_transfers/stablecoin/total_depositedusdc_liquidity
indexerTotalCollateralDepositedQuery/token_transfers/collateral/total_depositedSame as indexerTokenCollateralQuery.
querierUtilizationRatioQuery/utilization_ratioTotal Borrowed / Total Supplied
querierLendableQuery/lendableusdc_liquidity

Detailed Porting Guide

indexerTotalBorrowedQuery

Represents the total USDC lent out by the protocol.

  • Source: ContractState
  • Formula: total_borrowed_usdc_shares * usdc_borrow_index

indexerTotalFeesQuery

Represents total liquidator and insurance fees collected.

  • Source: ContractState (for insurance fund) & ContractConfigView (for liquidator account ID).
  • Formula: insurance_fund + (USDC balance of liquidator_account)

indexerAccountsQuery

Total number of registered users.

  • Source: ContractState
  • Formula: user_count

indexerProtocolLtvQuery

Protocol Loan-to-Value ratio.

  • Formula: Total Borrowed Value / Total Collateral Value
    • Total Borrowed Value: See indexerTotalBorrowedQuery.
    • Total Collateral Value:
      1. Get collateral_liquidity from ContractState.
      2. Fetch USD prices using Hermes.
      3. Normalize amounts based on token decimals.
      4. Sum: (Amount * USD Price) for all collateral types.

indexerTokenCollateralQuery & indexerTotalCollateralDepositedQuery

Total collateral present in the protocol (in USD).

  • Formula: Same calculation as Total Collateral Value in indexerProtocolLtvQuery.

indexerTotalStablecoinDepositedQuery

Total USDC present in the protocol.

  • Source: ContractState
  • Formula: usdc_liquidity

querierUtilizationRatioQuery

  • Source: ContractState
  • Formula: Total Borrowed / Total Supplied
    • Total Borrowed: total_borrowed_usdc_shares * usdc_borrow_index
    • Total Supplied: total_supplied_usdc_shares * usdc_supply_index

querierLendableQuery

Available USDC for lending.

  • Source: ContractState
  • Formula: usdc_liquidity

Contract View Query Migration

This section maps old smart contract view methods to the new logic.

Summary Table

Old QueryOld MethodNew Logic Summary
spBalanceOfCollateralQuerybalance_of_collateralUser.collateral (converted to USD).
spBalanceOfBorrowQuerybalance_of_borrowUser.usdc_position (Borrowed) * usdc_borrow_index.
spGetUserUnlentQueryget_user_unlentUser.usdc_position (Supplied) * usdc_supply_index.
spGetUserLentQueryget_user_lentDeprecated. (All deposits are now fully lent/supplied).
spGetBorrowThresholdQueryget_borrow_thresholdContractConfigView.borrow_threshold.
spGetWithdrawThresholdQueryget_withdraw_thresholdContractConfigView.withdraw_threshold.
spGetLiquidationThresholdQueryget_liquidation_thresholdContractConfigView.liquidation_threshold.
spGetLiquidationWarningThresholdQueryget_liquidation_warning_thresholdDeprecated. Hardcode in frontend.
spGetMaximumWithdrawableQueryget_maximum_withdrawableClient-side calculation (Collateral - Borrowed/Threshold).
spGetCollateralValueQueryget_collateral_valueUser.collateral * Prices.
spCalculateLtvQuerycalculate_ltvUser Borrowed Value / User Collateral Value.
spGetAccumulatedInterestQueryget_accumulated_interestDeferred to V2 Indexer.
spGetAnnualPercentageRateQueryget_annual_percentage_rateContractConfigView.usdc_base_borrow_rate.
spGetAnnualPercentageYieldQueryget_annual_percentage_yieldNot Applicable.
spGetMinimumBorrowableQueryget_smaller_operations_amountHardcode in frontend.
spGetMaximumBorrowableAmountQuerycomposedBorrowing Power - Current Borrow Value.
spBalanceOfAllMainCollateralsQuerycomposedAggregate User.collateral values.
spIsAccountAtRiskQueryis_account_at_riskClient-side check: Current LTV > Hardcoded Limit.
spGetAccountPendingLiquidationNotificationsQueryDeprecated.

Detailed Integration Guide

spBalanceOfCollateralQuery

Represents the collateral deposited by a User.

  • Source: User struct (collateral field).
  • Logic: Iterate through the map. Use Hermes API to convert amounts to USD if total value is needed.

spBalanceOfBorrowQuery

Represents the amount borrowed by a User (including accrued interest).

  • Source: User struct (usdc_position) & ContractState (usdc_borrow_index).
  • Formula:
    • If usdc_position is Borrowed(shares): shares * usdc_borrow_index.

spGetUserUnlentQuery

Represents the total USDC supplied by the lender that can be withdrawn.

  • Source: User struct (usdc_position) & ContractState (usdc_supply_index).
  • Formula:
    • If usdc_position is Supplied(shares): shares * usdc_supply_index.

spGetBorrowThresholdQuery, spGetWithdrawThresholdQuery, spGetLiquidationThresholdQuery

  • Source: ContractConfigView fields:
    • borrow_threshold
    • withdraw_threshold
    • liquidation_threshold

spGetMaximumWithdrawableQuery

Maximum amount (USDC) that can be withdrawn. Do note that this is an approximation of the maximum appoint since the current price fluctuating and interest also gets accumulated as seconds pass.

  • Logic (USDC):
    1. Fetch Pyth/Hermes data.
    2. Perform client-side interest accrual (refer to Liquidator bot implementation for logic).
    3. Calculate total supplied balance (like spGetUserUnlentQuery).
  • Logic (Collateral - returned in USDC value):
    1. Fetch Pyth/Hermes data.
    2. Perform client-side interest accrual.
    3. Compute Total Borrow Value of user.
    4. Compute Total Collateral Value of user.
    5. Formula: Total Collateral Value - (Total Borrow Value / withdraw_threshold)

spGetMaximumBorrowableAmountQuery

Maximum additional amount that can be borrowed.

  • Formula: Borrowing Power - Current Borrow Value
    • Borrowing Power: Total Collateral Value * borrow_threshold
    • Current Borrow Value: User Borrow Shares * Borrow Index

spGetAnnualPercentageRateQuery

Borrow rate at zero utilization.

  • Source: ContractConfigView.usdc_base_borrow_rate

User Actions (Transactions)

These are the write operations performed by the user.

Deposit

  1. USDC: Use ft_transfer_call on the USDC token contract, passing the protocol contract as the receiver.
  2. Collateral: Use ft_transfer_call on the specific collateral token contract.

Withdraw

  1. USDC: Call withdraw_usdc on the protocol contract.
  2. Collateral: Call withdraw_collateral on the protocol contract.

Borrow USDC

Call borrow_usdc on the protocol contract.

Repay USDC

Send USDC using ft_transfer_call on the USDC token contract to the protocol contract. The contract will automatically interpret this as a repayment.