1use std::collections::HashMap;
2
3use near_sdk::{env, near, require, AccountId, Promise, PromiseOrValue};
4use templar_common::{
5 accumulator::Accumulator,
6 asset::{BorrowAsset, BorrowAssetAmount, CollateralAssetAmount},
7 borrow::{BorrowPosition, BorrowStatus},
8 contract::list,
9 market::{BorrowAssetMetrics, HarvestYieldMode, MarketConfiguration, MarketExternalInterface},
10 oracle::pyth::OracleResponse,
11 self_ext,
12 snapshot::Snapshot,
13 supply::{SupplyPosition, WithdrawalAttempt},
14 withdrawal_queue::{
15 WithdrawalQueueExecutionResult, WithdrawalQueueStatus, WithdrawalRequestStatus,
16 },
17};
18use templar_primitives::Decimal;
19
20use crate::{Contract, ContractExt};
21
22#[near]
23impl MarketExternalInterface for Contract {
24 fn get_configuration(&self) -> MarketConfiguration {
25 self.configuration.clone()
26 }
27
28 fn get_current_snapshot(&self) -> Snapshot {
29 self.current_snapshot()
30 }
31
32 fn get_finalized_snapshots_len(&self) -> u32 {
33 self.finalized_snapshots.len()
34 }
35
36 fn get_borrow_asset_metrics(&self) -> BorrowAssetMetrics {
37 BorrowAssetMetrics {
38 available: self.get_borrow_asset_available_to_borrow(),
39 deposited_active: self.borrow_asset_deposited_active,
40 deposited_incoming: self
41 .borrow_asset_deposited_incoming
42 .iter()
43 .map(|incoming| (incoming.activate_at_snapshot_index, incoming.amount))
44 .collect(),
45 borrowed: self.borrowed(),
46 paid_to_fees: self.borrow_asset_paid_to_fees,
47 }
48 }
49
50 fn list_borrow_positions(
51 &self,
52 offset: Option<u32>,
53 count: Option<u32>,
54 ) -> HashMap<AccountId, BorrowPosition> {
55 list(self.iter_borrow_positions(), offset, count)
56 }
57
58 fn list_finalized_snapshots(&self, offset: Option<u32>, count: Option<u32>) -> Vec<&Snapshot> {
59 list(&self.finalized_snapshots, offset, count)
60 }
61
62 fn list_supply_positions(
63 &self,
64 offset: Option<u32>,
65 count: Option<u32>,
66 ) -> HashMap<AccountId, SupplyPosition> {
67 list(self.iter_supply_positions(), offset, count)
68 }
69
70 fn get_borrow_position(&self, account_id: AccountId) -> Option<BorrowPosition> {
71 let borrow_position = self.borrow_position_ref(account_id)?;
72 Some(borrow_position.inner().clone())
73 }
74
75 fn get_borrow_position_pending_interest(
76 &self,
77 account_id: AccountId,
78 snapshot_limit: Option<u32>,
79 ) -> Option<BorrowAssetAmount> {
80 let limit = snapshot_limit.unwrap_or(u32::MAX);
81 let position = self.borrow_position_ref(account_id)?;
82 Some(position.calculate_interest(limit).get_amount())
83 }
84
85 fn get_borrow_status(
86 &self,
87 account_id: AccountId,
88 oracle_response: OracleResponse,
89 ) -> Option<BorrowStatus> {
90 let borrow_position = self.borrow_position_ref(account_id)?;
91
92 let price_pair = self
93 .configuration
94 .price_oracle_configuration
95 .create_price_pair(&oracle_response)
96 .unwrap_or_else(|e| templar_common::panic_with_message(&e.to_string()));
97
98 Some(borrow_position.status(&price_pair, env::block_timestamp_ms()))
99 }
100
101 fn borrow(&mut self, amount: BorrowAssetAmount) -> Promise {
102 require!(!amount.is_zero(), "Borrow amount must be greater than zero");
103 let account_id = env::predecessor_account_id();
104 require!(
105 self.borrow_position_ref(account_id.clone()).is_some(),
106 "Borrow position does not exist",
107 );
108
109 self.configuration
110 .price_oracle_configuration
111 .retrieve_price_pair()
112 .then(
113 self_ext!(Self::GAS_BORROW_01_CONSUME_PRICE)
114 .borrow_01_consume_price(account_id, amount),
115 )
116 }
117
118 fn withdraw_collateral(&mut self, amount: CollateralAssetAmount) -> Promise {
119 let account_id = env::predecessor_account_id();
120
121 let snapshot = self.snapshot();
122 let Some(mut borrow_position) = self.borrow_position_guard(snapshot, account_id.clone())
123 else {
124 templar_common::panic_with_message(
125 "No borrower record. Please deposit collateral first.",
126 );
127 };
128
129 if borrow_position
130 .inner()
131 .get_total_borrow_asset_liability()
132 .is_zero()
133 {
134 let proof = borrow_position.accumulate_interest();
136 borrow_position.record_collateral_asset_withdrawal_initial(proof, amount);
137 drop(borrow_position);
138
139 self.configuration
140 .collateral_asset
141 .transfer(account_id.clone(), amount)
142 .then(
143 self_ext!(Self::GAS_WITHDRAW_COLLATERAL_02_FINALIZE)
144 .withdraw_collateral_02_finalize(account_id, amount),
145 )
146 } else {
147 drop(borrow_position);
148 self.configuration
150 .price_oracle_configuration
151 .retrieve_price_pair()
152 .then(
153 self_ext!(Self::GAS_WITHDRAW_COLLATERAL_01_CONSUME_PRICE)
154 .withdraw_collateral_01_consume_price(account_id, amount),
155 )
156 }
157 }
158
159 fn apply_interest(&mut self, account_id: Option<AccountId>, snapshot_limit: Option<u32>) {
160 let account_id = account_id.unwrap_or_else(env::predecessor_account_id);
161 let snapshot = self.snapshot();
162 if let Some(mut borrow_position) = self.borrow_position_guard(snapshot, account_id) {
163 borrow_position.accumulate_interest_partial(snapshot_limit.unwrap_or(u32::MAX));
164 }
165 }
166
167 fn get_supply_position(&self, account_id: AccountId) -> Option<SupplyPosition> {
168 let position = self.supply_position_ref(account_id)?;
169 Some(position.inner().clone())
170 }
171
172 fn get_supply_position_pending_yield(
173 &self,
174 account_id: AccountId,
175 snapshot_limit: Option<u32>,
176 ) -> Option<BorrowAssetAmount> {
177 let limit = snapshot_limit.unwrap_or(u32::MAX);
178 let position = self.supply_position_ref(account_id)?;
179 Some(position.calculate_yield(limit).get_amount())
180 }
181
182 fn create_supply_withdrawal_request(&mut self, amount: BorrowAssetAmount) {
185 require!(
186 !amount.is_zero(),
187 "Amount to withdraw must be greater than zero",
188 );
189 let predecessor = env::predecessor_account_id();
190 let Some(supply_position) = self
191 .supply_position_ref(predecessor.clone())
192 .filter(|supply_position| !supply_position.total_deposit().is_zero())
193 else {
194 templar_common::panic_with_message("Supply position does not exist");
195 };
196
197 require!(
201 supply_position.total_deposit() >= amount,
202 "Attempt to withdraw more than current deposit",
203 );
204 require!(
205 self.configuration.supply_withdrawal_range.contains(amount),
206 "Withdrawal amount is outside of allowable range",
207 );
208
209 self.withdrawal_queue.remove(&predecessor);
210 self.withdrawal_queue.insert_or_update(&predecessor, amount);
211 }
212
213 fn cancel_supply_withdrawal_request(&mut self) {
214 self.withdrawal_queue.remove(&env::predecessor_account_id());
215 }
216
217 fn execute_next_supply_withdrawal_request(
218 &mut self,
219 batch_limit: Option<u32>,
220 ) -> PromiseOrValue<WithdrawalQueueExecutionResult> {
221 let batch_limit = batch_limit.unwrap_or(1);
222 let mut batch = Vec::with_capacity(batch_limit.min(self.withdrawal_queue.len()) as usize);
223 let snapshot_proof = self.snapshot();
224 let block_timestamp_ms = env::block_timestamp_ms();
225 let queue_len_start = self.withdrawal_queue.len();
226 let mut depth_cleared = BorrowAssetAmount::zero();
227 let mut visited = 0u32;
228
229 while let Some((account_id, requested_amount)) = self.withdrawal_queue.peek() {
230 if visited >= batch_limit {
233 break;
234 }
235 visited += 1;
236
237 let withdrawal_attempt = {
238 let Some(mut position_guard) =
239 self.supply_position_guard(snapshot_proof, account_id.clone())
240 else {
241 self.withdrawal_queue.pop();
244 depth_cleared += requested_amount;
245 continue;
246 };
247 let accumulation_proof = position_guard.accumulate_yield();
248 position_guard.record_withdrawal_initial(
249 accumulation_proof,
250 requested_amount,
251 block_timestamp_ms,
252 )
253 };
254
255 match withdrawal_attempt {
256 WithdrawalAttempt::EmptyPosition => {
257 self.withdrawal_queue.pop();
258 depth_cleared += requested_amount;
259 }
260 WithdrawalAttempt::NoLiquidity => {
261 break;
262 }
263 WithdrawalAttempt::Full(withdrawal) => {
264 batch.push(withdrawal);
265 self.withdrawal_queue.pop();
266 depth_cleared += requested_amount;
267 }
268 WithdrawalAttempt::Partial {
269 withdrawal,
270 remaining,
271 } => {
272 batch.push(withdrawal);
273 self.withdrawal_queue.mut_head(|a| *a = remaining);
274 depth_cleared += requested_amount - remaining;
275 break;
276 }
277 }
278 }
279
280 let result = WithdrawalQueueExecutionResult {
281 depth: depth_cleared,
282 length: queue_len_start - self.withdrawal_queue.len(),
283 };
284
285 let Some(transfers) = batch
286 .iter()
287 .map(|resolution| {
288 self.configuration
289 .borrow_asset
290 .transfer(resolution.account_id.clone(), resolution.amount_to_account)
291 })
292 .reduce(|a, b| a.and(b))
293 else {
294 return PromiseOrValue::Value(result);
295 };
296
297 PromiseOrValue::Promise(
298 transfers.then(
299 self_ext!(
300 Self::gas_execute_next_supply_withdrawal_request_01_finalize(batch.len())
301 )
302 .execute_next_supply_withdrawal_request_01_finalize(batch, result),
303 ),
304 )
305 }
306
307 fn get_supply_withdrawal_request_status(
308 &self,
309 account_id: AccountId,
310 ) -> Option<WithdrawalRequestStatus> {
311 self.withdrawal_queue.get_request_status(&account_id)
312 }
313
314 fn get_supply_withdrawal_queue_status(&self) -> WithdrawalQueueStatus {
315 self.withdrawal_queue.get_status()
316 }
317
318 fn harvest_yield(
319 &mut self,
320 account_id: Option<AccountId>,
321 mode: Option<HarvestYieldMode>,
322 ) -> BorrowAssetAmount {
323 let mode = mode.unwrap_or_default();
324 let predecessor = env::predecessor_account_id();
325 let account_id = account_id.unwrap_or_else(|| predecessor.clone());
326
327 let snapshot = self.snapshot();
328 let Some(mut supply_position) = self.supply_position_guard(snapshot, account_id) else {
329 return BorrowAssetAmount::zero();
330 };
331
332 match mode {
333 HarvestYieldMode::SnapshotLimit(limit) => {
334 supply_position.accumulate_yield_partial(limit);
335 }
336 HarvestYieldMode::Default => {
337 supply_position.accumulate_yield();
338 }
339 }
340
341 BorrowAssetAmount::zero()
342 }
343
344 fn get_last_yield_rate(&self) -> Decimal {
345 self.configuration
346 .supply_yield_rate_from_interest(&self.current_snapshot())
347 }
348
349 fn get_static_yield(&self, account_id: AccountId) -> Option<Accumulator<BorrowAsset>> {
350 self.static_yield.get(&account_id)
351 }
352
353 fn accumulate_static_yield(
354 &mut self,
355 account_id: Option<AccountId>,
356 snapshot_limit: Option<u32>,
357 ) {
358 self.market
359 .accumulate_static_yield(
360 &account_id.unwrap_or_else(env::predecessor_account_id),
361 snapshot_limit.unwrap_or(u32::MAX),
362 )
363 .unwrap_or_else(|_| {
364 templar_common::panic_with_message("This account does not earn static yield")
365 });
366 }
367
368 fn withdraw_static_yield(&mut self, amount: Option<BorrowAssetAmount>) -> Promise {
369 let predecessor = env::predecessor_account_id();
370 let Some(mut yield_record) = self.static_yield.get(&predecessor) else {
371 templar_common::panic_with_message("Yield record does not exist");
372 };
373
374 let available = yield_record.get_total();
375 let amount = amount.unwrap_or(available);
376 require!(
377 amount <= available,
378 "Attempt to withdraw more than accumulated static yield",
379 );
380
381 yield_record.remove(amount);
382
383 self.static_yield.insert(&predecessor, &yield_record);
384 self.borrow_asset_balance = self.borrow_asset_balance.unwrap_sub(
385 amount,
386 "Invariant violation: static yield withdrawal exceeds market borrow asset balance",
387 );
388
389 self.configuration
390 .borrow_asset
391 .transfer(predecessor.clone(), amount)
392 .then(
393 self_ext!(Self::GAS_WITHDRAW_STATIC_YIELD_01_FINALIZE)
394 .withdraw_static_yield_01_finalize(predecessor, amount),
395 )
396 }
397}