Skip to content

Latest commit

 

History

History
344 lines (278 loc) · 18 KB

interface_quick_reference.md

File metadata and controls

344 lines (278 loc) · 18 KB

Contract Interface Quick Reference

Sync note: This file must stay in sync with stellar-lend/contracts/lending/src/lib.rs. After any pub fn change in that file, update the tables below and run bash docs/scripts/check_interface_sync.sh to verify.


1. Unit Scales & Precisions

Parameter Scale Description
Amounts raw i128 No automatic decimal shifting. Callers supply and receive raw integer amounts.
Health Factor 10^4 base 1.0 = 10000. Values < 10000 are eligible for liquidation. 100_000_000 is the sentinel for a debt-free position.
Basis Points (BPS) 10^4 1% = 100 BPS. Used for interest rates, fees, and risk thresholds.
Timestamps Seconds Unix epoch seconds from env.ledger().timestamp().

2. Implemented Function Reference

Initialization

Function Signature Auth Required Returns
initialize (admin: Address) — ()
get_admin () — Address
propose_admin (new_admin: Address) current admin ()
accept_admin () proposed admin ()
set_guardian (guardian: Address) admin ()
get_guardian () — Option<Address>

User Operations

Function Signature Auth Required Returns
deposit (user: Address, amount: i128) user Result<i128, LendingError> — new collateral balance
withdraw (user: Address, amount: i128) user Result<i128, LendingError> — new collateral balance
borrow (user: Address, amount: i128) user Result<i128, LendingError> — debt principal
repay (user: Address, amount: i128) user Result<i128, LendingError> — remaining debt principal
liquidate (liquidator: Address, borrower: Address, amount: i128) liquidator Result<i128, LendingError> — debt actually repaid
receive (token_asset: Address, from: Address, amount: i128, payload: Vec<Val>) from Result<(), LendingError> — pull-based deposit or repay dispatch

Flash Loans

Function Signature Auth Required Returns
flash_loan (initiator: Address, receiver: Address, asset: Address, amount: i128, params: Bytes) initiator ()
repay_flash_loan (payer: Address, asset: Address, amount: i128) payer ()

View Functions

Function Signature Returns
get_position (user: Address) PositionSummary { collateral: i128, debt: i128, health_factor: i128 }
get_debt_position (user: Address) DebtPosition { principal: i128, last_update: u64 }
get_min_borrow () i128
get_rate_smoothing_state () RateSmoothingState { schema_version: u32, current_rate_bps: i128, last_target_rate_bps: i128, last_update_ledger: u32 }
get_rate_model_diagnostics () RateModelDiagnostics { rate_model_active: bool, utilization_bps: i128, target_rate_bps: i128, applied_rate_bps: i128, last_update_ledger: u32, elapsed_ledgers: u32 }
get_health_factor (user: Address) i128
get_protocol_metrics () ProtocolMetrics { total_borrow: i128, total_supply: i128, utilization_bps: i128, ledger: u32 }
get_rate_model_diagnostics () RateModelDiagnostics { utilization_bps: i128, target_rate_bps: i128, applied_rate_bps: i128, last_update_ledger: u32 }

Upgrade Governance

Function Signature Auth Required Returns
upgrade_cancel (caller: Address, proposal_id: u64) admin Result<(), LendingError>
is_upgrade_proposal_cancelled (proposal_id: u64) — bool
get_upgrade_approval_binding (proposal_id: u64, approver: Address) — Option<BytesN<32>> — domain-separated approval binding
get_upgrade_proposal_signer_hash (proposal_id: u64) — Option<BytesN<32>> — approver-set fingerprint captured for the proposal
get_upgrade_approver_set_hash () — BytesN<32> — fingerprint of the current approver set

Oracle Price Controls

Function Signature Auth Required Returns
set_oracle_pubkey (pubkey: BytesN<32>) admin ()
get_oracle_pubkey () — Option<BytesN<32>>
set_price (caller: Address, asset: Address, price: i128, timestamp: u64, signature: BytesN<64>) caller must be admin or the configured price relayer Result<(), LendingError>
get_price_record (asset: Address) — Option<PriceRecord>
set_price_relayer (relayer: Address) admin Result<(), LendingError>
get_price_relayer () — Option<Address>
set_oracle_max_age (asset: Address, secs: u64) admin Result<(), LendingError> — bounds 60..=86_400
get_oracle_max_age (asset: Address) — Option<u64>
set_move_window_secs (secs: u64) admin Result<(), LendingError> — bounds 1..=86_400
get_move_window_secs () — u64
set_max_move_bps (max_move_bps: i128) admin Result<(), LendingError>
get_max_move_bps () — Option<i128>
set_price_bounds (asset: Address, min_price: i128, max_price: i128, force: bool) admin Result<(), LendingError> — rejects bounds excluding the current price unless force
get_price_bounds (asset: Address) — (Option<i128>, Option<i128>)

Admin & Risk Controls

Function Signature Auth Required Returns
set_min_borrow (min_borrow: i128) admin Result<(), LendingError>
set_debt_ceiling (ceiling: i128) admin Result<(), LendingError>
set_flash_fee (fee_bps: i128) admin Result<(), LendingError>
set_emergency_state (new_state: EmergencyState) admin; guardian may set Shutdown ()
set_pause (pause_type: PauseType, paused: bool, ttl_ledgers: u32) admin or guardian Result<(), LendingError>
get_pause_state (pause_type: PauseType) — bool
set_asset_params (admin: Address, asset: Address, ltv_bps: i128, liquidation_threshold_bps: i128, debt_ceiling: i128, borrow_cap: i128, supply_cap: i128) admin Result<(), LendingError>
get_asset_params (asset: Address) — Option<AssetParams>
set_close_factor_bps (close_factor_bps: i128) admin Result<(), LendingError>
get_close_factor_bps () — i128
set_liquidation_incentive_bps (incentive_bps: i128) admin Result<(), LendingError>
get_liquidation_incentive_bps () — i128
set_liquidation_threshold_bps (threshold_bps: i128) admin Result<(), LendingError>
upgrade_cancel (caller: Address, proposal_id: u64) admin Result<(), LendingError>
is_upgrade_proposal_cancelled (proposal_id: u64) — bool
get_upgrade_approval_binding (proposal_id: u64, approver: Address) — Option<BytesN<32>>
get_upgrade_approver_set_hash () — BytesN<32>
get_upgrade_proposal_signer_hash (proposal_id: u64) — Option<BytesN<32>>

Config Store

Function Signature Auth Required Returns
config_set (key: Symbol, value: Bytes) admin Result<(), LendingError>
config_get (key: Symbol) — Option<Bytes>
config_backup (name: Symbol) admin Result<(), LendingError>
config_restore (name: Symbol) admin Result<(), LendingError>

Governance Audit

Function Signature Auth Required Returns
get_governance_audit_count () — u64
get_governance_audit_entries (limit: u64) — Vec<AuditLogEntry>
get_upgrade_approval_binding (approver: Address, sequence: u32) — Option<BytesN<32>>
get_upgrade_approver_set_hash () — Option<BytesN<32>>
get_upgrade_proposal_signer_hash (proposal: Bytes) — Option<BytesN<32>>
is_upgrade_proposal_cancelled (proposal_hash: BytesN<32>) — bool
upgrade_cancel (proposal_hash: BytesN<32>) admin ()

Upgrade Governance

Function Signature Auth Required Returns
upgrade_init (caller: Address, current_wasm_hash: BytesN<32>, required_approvals: u32) admin Result<(), LendingError>
upgrade_propose (caller: Address, new_wasm_hash: BytesN<32>, new_version: u32) admin Result<u64, LendingError> — proposal ID
upgrade_approve (caller: Address, proposal_id: u64) approver Result<u32, LendingError> — approval count
upgrade_cancel (caller: Address, proposal_id: u64) admin Result<(), LendingError>
upgrade_execute (caller: Address, proposal_id: u64) approver Result<(), LendingError>
upgrade_set_required_approvals (caller: Address, required_approvals: u32) admin Result<(), LendingError>
upgrade_add_approver (caller: Address, approver: Address) admin Result<(), LendingError>
upgrade_remove_approver (caller: Address, approver: Address) admin Result<(), LendingError>
upgrade_status (proposal_id: u64) — Result<UpgradeStatus, LendingError>
current_version () — Result<u32, LendingError>
current_wasm_hash () — Result<BytesN<32>, LendingError>
get_required_approvals () — Result<u32, LendingError>
get_upgrade_approvers () — Result<Vec<Address>, LendingError>
get_proposal_approvals (proposal_id: u64) — Result<Vec<Address>, LendingError>
is_upgrade_proposal_cancelled (proposal_id: u64) — bool
get_upgrade_approval_binding (proposal_id: u64, approver: Address) — Option<BytesN<32>> — WASM hash the approver committed to
get_upgrade_approver_set_hash () — BytesN<32> — fingerprint of the live approver set
get_upgrade_proposal_signer_hash (proposal_id: u64) — Option<BytesN<32>> — approver-set fingerprint at proposal creation
get_min_upgrade_delay_ledgers () — u32 — minimum timelock delay in ledgers

Upgrade Governance

Function Signature Auth Required Returns
upgrade_cancel (caller: Address, proposal_id: u64) admin Result<(), LendingError> — cancel a pending proposal
is_upgrade_proposal_cancelled (proposal_id: u64) — bool — proposal is in the Cancelled terminal state
get_upgrade_approval_binding (proposal_id: u64, approver: Address) — Option<BytesN<32>> — stored domain-separated approval binding hash
get_upgrade_proposal_signer_hash (proposal_id: u64) — Option<BytesN<32>> — approver-set fingerprint captured at proposal creation
get_upgrade_approver_set_hash () — BytesN<32> — fingerprint of the live upgrade approver set

Cross-Asset User Operations

Function Signature Auth Required Returns
deposit_collateral_asset (user: Address, asset: Address, amount: i128) user Result<i128, LendingError> — new collateral balance
borrow_asset (user: Address, asset: Address, amount: i128) user Result<i128, LendingError> — debt principal
repay_asset (user: Address, asset: Address, amount: i128) user Result<i128, LendingError> — remaining debt principal
withdraw_asset (user: Address, asset: Address, amount: i128) user Result<i128, LendingError> — new collateral balance

Cross-Asset View Functions

Function Signature Returns
get_cross_position_summary (user: Address) CrossPositionSummary { total_collateral_usd: i128, total_debt_usd: i128, health_factor: i128 }
get_cross_health_factor (user: Address) i128
get_collateral_asset_balance (user: Address, asset: Address) i128
get_debt_asset_position (user: Address, asset: Address) DebtPosition

3. Return Types

PositionSummary

pub struct PositionSummary {
    pub collateral: i128,    // Raw collateral balance
    pub debt: i128,          // Effective debt (principal + accrued interest)
    pub health_factor: i128, // (collateral * 8000) / debt; 100_000_000 if debt == 0
}

DebtPosition

pub struct DebtPosition {
    pub principal: i128,    // Borrowed principal (before interest)
    pub last_update: u64,   // Timestamp of last interest calculation
}

AssetParams

pub struct AssetParams {
    pub ltv_bps: i128,                  // Loan-to-value in basis points
    pub liquidation_threshold_bps: i128, // Liquidation threshold in basis points
    pub debt_ceiling: i128,             // Total system-wide debt cap for this asset
}

CrossPositionSummary

pub struct CrossPositionSummary {
    pub total_collateral_usd: i128, // Σ(collateral_i × price_i) / PRICE_DIVISOR
    pub total_debt_usd: i128,       // Σ(debt_j × price_j) / PRICE_DIVISOR
    pub health_factor: i128,        // Aggregate HF (≥10000 = healthy)
}

PriceRecord

pub struct PriceRecord {
    pub price: i128,
    pub timestamp: u64,
}

ProtocolMetrics

pub struct ProtocolMetrics {
    pub total_borrow: i128,
    pub total_supply: i128,
    pub utilization_bps: i128,
    pub ledger: u32,
}

RateSmoothingState

pub struct RateSmoothingState {
    pub schema_version: u32,
    pub current_rate_bps: i128,
    pub last_target_rate_bps: i128,
    pub last_update_ledger: u32,
}

EmergencyState

pub enum EmergencyState {
    Normal,    // All operations permitted
    Shutdown,  // All operations blocked
    Recovery,  // Only repay and withdraw permitted
}

4. Error Codes

Code Variant Meaning Suggested UI Message
1001 LendingError::InvalidAmount Amount must be positive "Please enter a valid amount."
1002 LendingError::Overflow Calculation exceeded storage limits "Result too large. Try a smaller amount."
1003 LendingError::Unauthorized Caller lacks permission "You are not authorized for this action."
1008 LendingError::BelowMinimumBorrow Borrow amount below protocol minimum "Amount is below the minimum borrow. Please increase your amount."
1009 LendingError::NotInitialized Contract not yet initialized "Contract is not ready. Contact the administrator."
1010 LendingError::AlreadyInitialized initialize called twice "Contract already initialized."
1011 LendingError::PositionHealthy Liquidation rejected — position is healthy "This position cannot be liquidated."
2001 LendingError::DebtCeilingExceeded Borrow would exceed global debt ceiling "Protocol debt limit reached. Try a smaller amount."
2002 LendingError::DepositCapExceeded Deposit would exceed total cap "Deposit cap reached. Try a smaller amount."
2005 LendingError::InvalidFeeBps Flash loan fee out of range "Fee must be between 0 and 10%."
2007 LendingError::InsufficientCollateral Collateral too low "Insufficient collateral for this action."
5001 LendingError::InvalidOracleSignature Bad oracle signature "Oracle signature verification failed."
5002 LendingError::StaleOracleTimestamp Oracle update too old "Oracle price is outdated."
5003 LendingError::OraclePubkeyNotSet Oracle key missing "System error: Oracle key not configured."
3001 LendingError::AssetNotConfigured Asset not registered via set_asset_params "Asset is not configured. Contact the administrator."
3002 LendingError::PriceFeedNotFound Oracle price missing for asset "Price data not available for this asset."
3003 LendingError::HealthFactorTooLow Operation would drop HF below 1.0 "Insufficient collateral for this action."

5. Emergency State Permissions

State Deposit Borrow Repay Withdraw Liquidate
Normal ✅ ✅ ✅ ✅ ✅
Shutdown ❌ ❌ ❌ ❌ ❌
Recovery ❌ ❌ ✅ ✅ ❌

6. Events Emitted

Event Topic Payload Emitted When
EmergencyStateChanged (old_state: EmergencyState, new_state: EmergencyState) set_emergency_state completes
PauseStateChanged (operation: PauseType, old_state: PauseState, new_state: PauseState) set_pause completes
AssetParamsSet (asset: Address, ltv_bps: i128, liquidation_threshold_bps: i128, debt_ceiling: i128) set_asset_params completes
CrossDeposit (user: Address, asset: Address, amount: i128) deposit_collateral_asset completes
CrossBorrow (user: Address, asset: Address, amount: i128) borrow_asset completes
CrossRepay (user: Address, asset: Address, amount: i128) repay_asset completes
CrossWithdraw (user: Address, asset: Address, amount: i128) withdraw_asset completes

Additional events for deposit, borrow, repay, liquidate, and flash_loan are planned but not yet emitted by the current implementation.


7. 🔮 Planned — Not Yet Implemented

The following functions are not present in src/lib.rs and should not be called. They are documented here for roadmap visibility.

Feature Tracking
get_emergency_state() Planned public view (state visible via events today)
set_oracle(admin, oracle) Planned external oracle contract adapter
get_max_liquidatable_amount(user) Planned convenience helper
data_* functions Planned persistent data-store management

8. Integration Checklist

  • Use raw i128 for all amounts — no automatic decimal conversion.
  • Call get_position(user) before allowing further borrows; check health_factor >= 10000.
  • Ensure wallet connector handles user.require_auth() for all user-facing calls.
  • Confirm EmergencyState::Normal before presenting deposit / borrow UI to users.
  • Flash loan receivers must implement an on_flash_loan(initiator, asset, amount, fee, params) endpoint.