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:
- User Actions:
- USDC Deposit
- Collateral Deposit
- Borrow USDC
- Withdraw USDC
- Withdraw Collateral
- Repayment of USDC
- 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 Query | Endpoint | New Logic Summary |
|---|---|---|
transactionsQuery | /transactions/account/{accountId} | Deferred to V2 (Indexer API). |
indexerTotalBorrowedQuery | /borrows/total_borrowed | total_borrowed_usdc_shares * usdc_borrow_index |
indexerTotalFeesQuery | /fees/total/interest_and_penalties | insurance_fund + Liquidator Account Balance |
indexerAccountsQuery | /accounts | user_count |
indexerProtocolLtvQuery | /dashboard/ltv | Total Borrowed / Total Collateral Value |
indexerTokenCollateralQuery | /dashboard/token_collateral | Sum of all collateral values (USD). |
indexerTotalStablecoinDepositedQuery | /token_transfers/stablecoin/total_deposited | usdc_liquidity |
indexerTotalCollateralDepositedQuery | /token_transfers/collateral/total_deposited | Same as indexerTokenCollateralQuery. |
querierUtilizationRatioQuery | /utilization_ratio | Total Borrowed / Total Supplied |
querierLendableQuery | /lendable | usdc_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:
- Get
collateral_liquidityfromContractState. - Fetch USD prices using Hermes.
- Normalize amounts based on token decimals.
- Sum:
(Amount * USD Price)for all collateral types.
- Get
- Total Borrowed Value: See
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
- Total Borrowed:
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 Query | Old Method | New Logic Summary |
|---|---|---|
spBalanceOfCollateralQuery | balance_of_collateral | User.collateral (converted to USD). |
spBalanceOfBorrowQuery | balance_of_borrow | User.usdc_position (Borrowed) * usdc_borrow_index. |
spGetUserUnlentQuery | get_user_unlent | User.usdc_position (Supplied) * usdc_supply_index. |
spGetUserLentQuery | get_user_lent | Deprecated. (All deposits are now fully lent/supplied). |
spGetBorrowThresholdQuery | get_borrow_threshold | ContractConfigView.borrow_threshold. |
spGetWithdrawThresholdQuery | get_withdraw_threshold | ContractConfigView.withdraw_threshold. |
spGetLiquidationThresholdQuery | get_liquidation_threshold | ContractConfigView.liquidation_threshold. |
spGetLiquidationWarningThresholdQuery | get_liquidation_warning_threshold | Deprecated. Hardcode in frontend. |
spGetMaximumWithdrawableQuery | get_maximum_withdrawable | Client-side calculation (Collateral - Borrowed/Threshold). |
spGetCollateralValueQuery | get_collateral_value | User.collateral * Prices. |
spCalculateLtvQuery | calculate_ltv | User Borrowed Value / User Collateral Value. |
spGetAccumulatedInterestQuery | get_accumulated_interest | Deferred to V2 Indexer. |
spGetAnnualPercentageRateQuery | get_annual_percentage_rate | ContractConfigView.usdc_base_borrow_rate. |
spGetAnnualPercentageYieldQuery | get_annual_percentage_yield | Not Applicable. |
spGetMinimumBorrowableQuery | get_smaller_operations_amount | Hardcode in frontend. |
spGetMaximumBorrowableAmountQuery | composed | Borrowing Power - Current Borrow Value. |
spBalanceOfAllMainCollateralsQuery | composed | Aggregate User.collateral values. |
spIsAccountAtRiskQuery | is_account_at_risk | Client-side check: Current LTV > Hardcoded Limit. |
spGetAccountPendingLiquidationNotificationsQuery | … | Deprecated. |
Detailed Integration Guide
spBalanceOfCollateralQuery
Represents the collateral deposited by a User.
- Source:
Userstruct (collateralfield). - 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:
Userstruct (usdc_position) &ContractState(usdc_borrow_index). - Formula:
- If
usdc_positionisBorrowed(shares):shares * usdc_borrow_index.
- If
spGetUserUnlentQuery
Represents the total USDC supplied by the lender that can be withdrawn.
- Source:
Userstruct (usdc_position) &ContractState(usdc_supply_index). - Formula:
- If
usdc_positionisSupplied(shares):shares * usdc_supply_index.
- If
spGetBorrowThresholdQuery, spGetWithdrawThresholdQuery, spGetLiquidationThresholdQuery
- Source:
ContractConfigViewfields:borrow_thresholdwithdraw_thresholdliquidation_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):
- Fetch Pyth/Hermes data.
- Perform client-side interest accrual (refer to Liquidator bot implementation for logic).
- Calculate total supplied balance (like
spGetUserUnlentQuery).
- Logic (Collateral - returned in USDC value):
- Fetch Pyth/Hermes data.
- Perform client-side interest accrual.
- Compute
Total Borrow Valueof user. - Compute
Total Collateral Valueof user. - Formula:
Total Collateral Value - (Total Borrow Value / withdraw_threshold)
spGetMaximumBorrowableAmountQuery
Maximum additional amount that can be borrowed.
- Formula:
Borrowing Power - Current Borrow ValueBorrowing Power:Total Collateral Value * borrow_thresholdCurrent 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
- USDC: Use
ft_transfer_callon the USDC token contract, passing the protocol contract as the receiver. - Collateral: Use
ft_transfer_callon the specific collateral token contract.
Withdraw
- USDC: Call
withdraw_usdcon the protocol contract. - Collateral: Call
withdraw_collateralon 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.