1use near_sdk::{env, near, require, serde_json, AccountId, Gas, Promise, PromiseResult};
2use templar_common::{
3 asset::{
4 BorrowAsset, BorrowAssetAmount, CollateralAsset, CollateralAssetAmount, FungibleAsset,
5 ReturnStyle,
6 },
7 borrow::InitialBorrow,
8 market::{LiquidateMsg, Withdrawal},
9 oracle::pyth::OracleResponse,
10 price::PricePair,
11 self_ext,
12 withdrawal_queue::WithdrawalQueueExecutionResult,
13};
14
15use crate::{Contract, ContractExt};
16
17impl Contract {
19 pub fn retrieve_price_pair(&self) -> Promise {
20 self.configuration
21 .price_oracle_configuration
22 .retrieve_price_pair()
23 }
24
25 pub fn price_pair(&self, oracle_response: OracleResponse) -> PricePair {
26 self.configuration
27 .price_oracle_configuration
28 .create_price_pair(&oracle_response)
29 .unwrap_or_else(|e| templar_common::panic_with_message(&e.to_string()))
30 }
31
32 pub fn execute_supply(&mut self, account_id: AccountId, amount: BorrowAssetAmount) {
33 if self.supply_position_ref(account_id.clone()).is_none() {
34 self.charge_for_storage(
35 &account_id,
36 self.storage_usage_supply_position + self.storage_usage_snapshot * 2,
37 );
38 }
39
40 let snapshot = self.snapshot();
41 let mut supply_position = self.get_or_create_supply_position_guard(snapshot, account_id);
42 let proof = supply_position.accumulate_yield();
43 supply_position.record_deposit(proof, amount, env::block_timestamp_ms());
44 require!(
45 supply_position.is_within_allowable_range(),
46 "New supply position is outside of allowable range",
47 );
48 }
49
50 pub fn execute_collateralize(
51 &mut self,
52 account_id: AccountId,
53 amount: CollateralAssetAmount,
54 price_pair: &PricePair,
55 ) {
56 if self.borrow_position_ref(account_id.clone()).is_none() {
64 self.charge_for_storage(
65 &account_id,
66 self.storage_usage_borrow_position + self.storage_usage_snapshot * 2,
67 );
68 }
69
70 let snapshot = self.snapshot();
71 let mut borrow_position = self.get_or_create_borrow_position_guard(snapshot, account_id);
72 let proof = borrow_position.accumulate_interest();
73 borrow_position.record_collateral_asset_deposit(proof, amount);
74 require!(
75 !borrow_position
76 .status(price_pair, env::block_timestamp_ms())
77 .is_liquidation(),
78 "Position is eligible for liquidation after collateralization",
79 );
80 }
81
82 pub fn execute_repay(
84 &mut self,
85 account_id: AccountId,
86 amount: BorrowAssetAmount,
87 price_pair: &PricePair,
88 ) -> BorrowAssetAmount {
89 let snapshot = self.snapshot();
90 let Some(mut borrow_position) = self.borrow_position_guard(snapshot, account_id) else {
91 return amount;
93 };
94 let proof = borrow_position.accumulate_interest();
95 require!(
96 !borrow_position
97 .status(price_pair, env::block_timestamp_ms())
98 .is_liquidation(),
99 "Cannot repay when eligible for liquidation",
100 );
101 borrow_position.record_repay(proof, amount)
103 }
104}
105
106#[near]
108impl Contract {
109 pub const GAS_BORROW_01_CONSUME_PRICE: Gas = Gas::from_tgas(6)
111 .saturating_add(FungibleAsset::<BorrowAsset>::GAS_FT_TRANSFER)
112 .saturating_add(Self::GAS_BORROW_02_FINALIZE);
113
114 #[private]
115 pub fn borrow_01_consume_price(
116 &mut self,
117 account_id: AccountId,
118 amount: BorrowAssetAmount,
119 #[callback_unwrap] oracle_response: OracleResponse,
120 ) -> Promise {
121 let price_pair = self.price_pair(oracle_response);
122 let snapshot = self.snapshot();
123
124 let Some(mut borrow_position) = self.borrow_position_guard(snapshot, account_id.clone())
125 else {
126 templar_common::panic_with_message(
127 "No borrower record. Please deposit collateral first.",
128 );
129 };
130
131 let interest = borrow_position.accumulate_interest();
132
133 let initial_borrow = borrow_position
134 .record_borrow_initial(
135 snapshot,
136 interest,
137 amount,
138 &price_pair,
139 env::block_timestamp_ms(),
140 )
141 .unwrap_or_else(|e| templar_common::panic_with_message(&e.to_string()));
142
143 drop(borrow_position);
144
145 self.configuration
146 .borrow_asset
147 .transfer(account_id.clone(), amount)
148 .then(
149 self_ext!(Self::GAS_BORROW_02_FINALIZE)
150 .borrow_02_finalize(account_id, initial_borrow),
151 )
152 }
153
154 pub const GAS_BORROW_02_FINALIZE: Gas = Gas::from_tgas(6);
156
157 #[private]
158 pub fn borrow_02_finalize(&mut self, account_id: AccountId, initial_borrow: InitialBorrow) {
159 let snapshot = self.snapshot();
160 let Some(mut borrow_position) = self.borrow_position_guard(snapshot, account_id) else {
161 templar_common::panic_with_message(
162 "Invariant violation: borrow position does not exist after transfer.",
163 );
164 };
165
166 let proof = borrow_position.accumulate_interest();
167 #[allow(deprecated)]
168 let success = matches!(env::promise_result(0), PromiseResult::Successful(_));
169 borrow_position.record_borrow_final(
170 snapshot,
171 proof,
172 &initial_borrow,
173 success,
174 env::block_timestamp_ms(),
175 );
176 }
177
178 const GAS_FINALIZE_WITHDRAWAL_BASE: Gas = Gas::from_tgas(6);
179 const GAS_FINALIZE_WITHDRAWAL_PER_RESOLUTION: Gas = Gas::from_tgas(3);
180
181 pub(crate) fn gas_execute_next_supply_withdrawal_request_01_finalize(
184 resolutions: usize,
185 ) -> Gas {
186 Self::GAS_FINALIZE_WITHDRAWAL_BASE.saturating_add(
187 Self::GAS_FINALIZE_WITHDRAWAL_PER_RESOLUTION
188 .saturating_mul(u64::try_from(resolutions).unwrap_or(u64::MAX)),
189 )
190 }
191
192 #[private]
193 pub fn execute_next_supply_withdrawal_request_01_finalize(
194 &mut self,
195 resolutions: Vec<Withdrawal>,
196 result: WithdrawalQueueExecutionResult,
197 ) -> WithdrawalQueueExecutionResult {
198 let snapshot = self.snapshot();
199
200 for (i, resolution) in resolutions.iter().enumerate() {
201 #[allow(deprecated)]
202 let succeeded = matches!(env::promise_result(i as u64), PromiseResult::Successful(_));
203
204 if let Some(mut position) =
205 self.supply_position_guard(snapshot, resolution.account_id.clone())
206 {
207 position.record_withdrawal_final(resolution, succeeded);
208 }
209
210 if succeeded && self.cleanup_supply_position(&resolution.account_id) {
211 self.refund_for_storage(&resolution.account_id, self.storage_usage_supply_position);
212 }
213 }
214
215 result
216 }
217
218 pub const GAS_COLLATERALIZE_TRANSFER_CALL_01_CONSUME_PRICE: Gas = Gas::from_tgas(6);
220
221 #[private]
222 pub fn collateralize_transfer_call_01_consume_price(
223 &mut self,
224 account_id: AccountId,
225 amount: CollateralAssetAmount,
226 return_style: ReturnStyle,
227 #[callback_unwrap] oracle_response: OracleResponse,
228 ) -> serde_json::Value {
229 let price_pair = self.price_pair(oracle_response);
230
231 self.execute_collateralize(account_id, amount, &price_pair);
232
233 return_style.serialize(CollateralAssetAmount::zero())
234 }
235
236 pub const GAS_REPAY_TRANSFER_CALL_01_CONSUME_PRICE: Gas = Gas::from_tgas(7);
238
239 #[private]
240 pub fn repay_transfer_call_01_consume_price(
241 &mut self,
242 account_id: AccountId,
243 amount: BorrowAssetAmount,
244 return_style: ReturnStyle,
245 #[callback_unwrap] oracle_response: OracleResponse,
246 ) -> serde_json::Value {
247 let price_pair = self.price_pair(oracle_response);
248
249 let amount = self.execute_repay(account_id, amount, &price_pair);
250
251 return_style.serialize(amount)
252 }
253
254 pub const GAS_LIQUIDATE_TRANSFER_CALL_01_CONSUME_PRICE: Gas = Gas::from_tgas(7)
256 .saturating_add(FungibleAsset::<CollateralAsset>::GAS_FT_TRANSFER)
257 .saturating_add(Self::GAS_LIQUIDATE_TRANSFER_CALL_02_FINALIZE);
258
259 #[private]
260 pub fn liquidate_transfer_call_01_consume_price(
261 &mut self,
262 liquidator_id: AccountId,
263 amount: BorrowAssetAmount,
264 msg: LiquidateMsg,
265 return_style: ReturnStyle,
266 #[callback_unwrap] oracle_response: OracleResponse,
267 ) -> Promise {
268 let price_pair = self
269 .configuration
270 .price_oracle_configuration
271 .create_price_pair(&oracle_response)
272 .unwrap_or_else(|e| templar_common::panic_with_message(&e.to_string()));
273
274 let result = {
275 let snapshot = self.snapshot();
276 let mut borrow_position = self
277 .borrow_position_guard(snapshot, msg.account_id.clone())
278 .unwrap_or_else(|| {
279 templar_common::panic_with_message("Borrow position does not exist")
280 });
281
282 let proof = borrow_position.accumulate_interest();
283
284 borrow_position
285 .record_liquidation(
286 proof,
287 liquidator_id.clone(),
288 amount,
289 msg.amount,
290 &price_pair,
291 env::block_timestamp_ms(),
292 )
293 .unwrap_or_else(|e| templar_common::panic_with_message(&e.to_string()))
294 };
295
296 if self.cleanup_borrow_position(&msg.account_id) {
297 self.refund_for_storage(&msg.account_id, self.storage_usage_borrow_position);
298 }
299
300 self.configuration
301 .collateral_asset
302 .transfer(liquidator_id.clone(), result.liquidated)
303 .then(
304 self_ext!(Self::GAS_LIQUIDATE_TRANSFER_CALL_02_FINALIZE)
305 .liquidate_transfer_call_02_finalize(result.refund, return_style),
306 )
307 }
308
309 pub const GAS_LIQUIDATE_TRANSFER_CALL_02_FINALIZE: Gas = Gas::from_tgas(4);
311
312 #[private]
315 pub fn liquidate_transfer_call_02_finalize(
316 &mut self,
317 refund: BorrowAssetAmount,
318 return_style: ReturnStyle,
319 ) -> serde_json::Value {
320 return_style.serialize(refund)
334 }
335
336 pub const GAS_WITHDRAW_COLLATERAL_01_CONSUME_PRICE: Gas = Gas::from_tgas(7)
338 .saturating_add(FungibleAsset::<CollateralAsset>::GAS_FT_TRANSFER)
339 .saturating_add(Self::GAS_WITHDRAW_COLLATERAL_02_FINALIZE);
340
341 #[private]
342 pub fn withdraw_collateral_01_consume_price(
343 &mut self,
344 account_id: AccountId,
345 amount: CollateralAssetAmount,
346 #[callback_unwrap] oracle_response: OracleResponse,
347 ) -> Promise {
348 let price_pair = self.price_pair(oracle_response);
349
350 let snapshot = self.snapshot();
351 let Some(mut borrow_position) = self.borrow_position_guard(snapshot, account_id.clone())
352 else {
353 templar_common::panic_with_message(
354 "No borrower record. Please deposit collateral first.",
355 );
356 };
357
358 let proof = borrow_position.accumulate_interest();
359 borrow_position.record_collateral_asset_withdrawal_initial(proof, amount);
360
361 require!(
362 borrow_position
363 .status(&price_pair, env::block_timestamp_ms())
364 .is_healthy(),
365 "Borrow position must be healthy after collateral withdrawal",
366 );
367
368 drop(borrow_position);
369
370 self.configuration
371 .collateral_asset
372 .transfer(account_id.clone(), amount)
373 .then(
374 self_ext!(Self::GAS_WITHDRAW_COLLATERAL_02_FINALIZE)
375 .withdraw_collateral_02_finalize(account_id, amount),
376 )
377 }
378
379 pub const GAS_WITHDRAW_COLLATERAL_02_FINALIZE: Gas = Gas::from_tgas(5);
381
382 #[private]
383 pub fn withdraw_collateral_02_finalize(
384 &mut self,
385 account_id: AccountId,
386 amount: CollateralAssetAmount,
387 ) {
388 #[allow(deprecated)]
389 let succeeded = matches!(env::promise_result(0), PromiseResult::Successful(_));
390
391 let snapshot = self.snapshot();
392 let Some(mut position) = self.borrow_position_guard(snapshot, account_id.clone()) else {
393 templar_common::panic_with_message(
394 "Invariant violation: Borrow position must exist after collateral withdrawal.",
395 );
396 };
397
398 let proof = position.accumulate_interest();
399 position.record_collateral_asset_withdrawal_final(proof, amount, succeeded);
400
401 if succeeded {
402 drop(position);
403 if self.cleanup_borrow_position(&account_id) {
404 self.refund_for_storage(&account_id, self.storage_usage_borrow_position);
405 }
406 }
407 }
408
409 pub const GAS_WITHDRAW_STATIC_YIELD_01_FINALIZE: Gas = Gas::from_tgas(5);
411
412 #[private]
413 pub fn withdraw_static_yield_01_finalize(
414 &mut self,
415 account_id: AccountId,
416 amount: BorrowAssetAmount,
417 ) {
418 #[allow(deprecated)]
419 if matches!(env::promise_result(0), PromiseResult::Failed) {
420 let mut yield_record = self.static_yield.get(&account_id).unwrap_or_else(|| {
421 templar_common::panic_with_message(
422 "Invariant violation: static yield entry must exist during callback",
423 )
424 });
425 yield_record.add_once(amount);
426 self.static_yield.insert(&account_id, &yield_record);
427 self.borrow_asset_balance += amount;
428 }
429 }
430}