templar_common/market/
external.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use std::collections::HashMap;

use near_sdk::{near, AccountId, Promise, PromiseOrValue};

use crate::{
    accumulator::Accumulator,
    asset::{BorrowAsset, BorrowAssetAmount, CollateralAssetAmount},
    borrow::{BorrowPosition, BorrowStatus},
    number::Decimal,
    oracle::pyth::OracleResponse,
    snapshot::Snapshot,
    supply::SupplyPosition,
    withdrawal_queue::{WithdrawalQueueStatus, WithdrawalRequestStatus},
};

use super::{BorrowAssetMetrics, MarketConfiguration};

#[derive(Debug, Clone, Copy, Default)]
#[near(serializers = [json, borsh])]
pub enum HarvestYieldMode {
    #[default]
    Default,
    Compounding,
    SnapshotLimit(u32),
}

#[near_sdk::ext_contract(ext_market)]
pub trait MarketExternalInterface {
    // ========================
    // MARKET GENERAL FUNCTIONS
    // ========================

    /// Retrieve the market configuration.
    fn get_configuration(&self) -> MarketConfiguration;

    /// Retrieve the current snapshot (in progress; not yet finalized).
    fn get_current_snapshot(&self) -> Snapshot;

    /// Retrieve the count of finalized snapshots.
    fn get_finalized_snapshots_len(&self) -> u32;

    /// Retrieve a list of finalized snapshots.
    fn list_finalized_snapshots(&self, offset: Option<u32>, count: Option<u32>) -> Vec<&Snapshot>;

    /// Retrieve current contract metrics about borrow asset deposit,
    /// availability, usage, etc.
    fn get_borrow_asset_metrics(&self) -> BorrowAssetMetrics;

    // ==================
    // BORROW FUNCTIONS
    // ==================

    // *_on_transfer where msg = Collateralize
    // *_on_transfer where msg = Repay

    /// Retrieve a map of borrow positions.
    fn list_borrow_positions(
        &self,
        offset: Option<u32>,
        count: Option<u32>,
    ) -> HashMap<AccountId, BorrowPosition>;

    /// Retrieve a specific borrow position, with estimated fees.
    ///
    /// This function may report fees slightly inaccurately. This is because
    /// the function has to estimate what fees will be applied between the last
    /// finalized market snapshot and the (present) time when the function was
    /// called.
    fn get_borrow_position(&self, account_id: AccountId) -> Option<BorrowPosition>;

    /// Retrieves the status of a borrow position (healthy or in liquidation)
    /// given some asset prices.
    ///
    /// This is just a read-only function, so it does not validate the price
    /// data. It is intended to be called by liquidators so they can easily see
    /// whether a position is eligible for liquidation.
    fn get_borrow_status(
        &self,
        account_id: AccountId,
        oracle_response: OracleResponse,
    ) -> Option<BorrowStatus>;

    /// Transfers `amount` of borrow asset tokens to the caller, provided
    /// their borrow position will still be sufficiently collateralized.
    fn borrow(&mut self, amount: BorrowAssetAmount) -> Promise;

    /// Transfers `amount` of collateral asset tokens to the caller, provided
    /// their borrow position will still be sufficiently collateralized.
    fn withdraw_collateral(&mut self, amount: CollateralAssetAmount) -> Promise;

    /// Applies interest to the predecessor's borrow record.
    /// Not likely to be used in real life, since there it does not affect the
    /// final interest calculation, and rounds fractional interest UP.
    fn apply_interest(&mut self, account_id: Option<AccountId>, snapshot_limit: Option<u32>);

    // ================
    // SUPPLY FUNCTIONS
    // ================

    // *_on_transfer where msg = Supply

    /// Retrieves a set of supply positions.
    fn list_supply_positions(
        &self,
        offset: Option<u32>,
        count: Option<u32>,
    ) -> HashMap<AccountId, SupplyPosition>;

    /// Retrieves a supply position record, with estimated yield.
    fn get_supply_position(&self, account_id: AccountId) -> Option<SupplyPosition>;

    /// Enters a supply position into the withdrawal queue, requesting to
    /// withdraw `amount` borrow asset tokens.
    ///
    /// If the account is already in the queue, it will be moved to the back
    /// of the queue with the updated amount.
    fn create_supply_withdrawal_request(&mut self, amount: BorrowAssetAmount);

    /// Removes a supply position from the withdrawal queue.
    fn cancel_supply_withdrawal_request(&mut self);

    /// Attempts to fulfill the first withdrawal request in the queue.
    fn execute_next_supply_withdrawal_request(&mut self) -> PromiseOrValue<()>;

    /// Retrieves the status of a withdrawal request in the queue.
    fn get_supply_withdrawal_request_status(
        &self,
        account_id: AccountId,
    ) -> Option<WithdrawalRequestStatus>;

    /// Retrieves the status of the withdrawal queue.
    fn get_supply_withdrawal_queue_status(&self) -> WithdrawalQueueStatus;

    /// Claim any distributed yield to the supply record.
    /// If mode is set to [`HarvestYieldMode::Compounding`], the all of the
    /// yield (including any harvested in previous, non-compounding
    /// `harvest_yield` calls) will be deposited to the supply record, so it
    /// can be withdrawn and will contribute to future yield calculations.
    fn harvest_yield(
        &mut self,
        account_id: Option<AccountId>,
        mode: Option<HarvestYieldMode>,
    ) -> BorrowAssetAmount;

    /// This value is an *expected average over time*.
    /// Supply positions actually earn all of their yield the instant it is
    /// distributed.
    fn get_last_yield_rate(&self) -> Decimal;

    // =====================
    // LIQUIDATION FUNCTIONS
    // =====================

    // *_on_transfer where msg = Liquidate { account_id }

    // =================
    // YIELD FUNCTIONS
    // =================

    /// Retrieves the amount of yield earned by an account statically
    /// configured to earn yield (e.g. [`MarketConfiguration::yield_weights`]
    /// or [`MarketConfiguration::protocol_account_id`]).
    fn get_static_yield(&self, account_id: AccountId) -> Option<Accumulator<BorrowAsset>>;

    /// Accumulates yield for an account that earns static yield.
    fn accumulate_static_yield(
        &mut self,
        account_id: Option<AccountId>,
        snapshot_limit: Option<u32>,
    );

    /// Attempts to withdraw the amount of yield earned by an account
    /// statically configured to earn yield (e.g.
    /// [`MarketConfiguration::yield_weights`] or
    /// [`MarketConfiguration::protocol_account_id`]).
    ///
    /// Calls to this function should be preceded by calls to
    /// [`MarketExternalInterface::accumulate_static_yield`].
    fn withdraw_static_yield(&mut self, amount: Option<BorrowAssetAmount>) -> Promise;
}