1use near_sdk::{
2 collections::{LookupMap, UnorderedMap},
3 env, near, AccountId, BorshStorageKey, IntoStorageKey,
4};
5use templar_primitives::number::Decimal;
6
7use crate::{
8 accumulator::{AccumulationRecord, Accumulator},
9 asset::{BorrowAsset, BorrowAssetAmount, CollateralAssetAmount},
10 borrow::{BorrowPosition, BorrowPositionGuard, BorrowPositionRef},
11 chunked_append_only_list::ChunkedAppendOnlyList,
12 event::MarketEvent,
13 incoming_deposit::IncomingDeposit,
14 market::MarketConfiguration,
15 snapshot::Snapshot,
16 supply::{SupplyPosition, SupplyPositionGuard, SupplyPositionRef},
17 time_chunk::TimeChunk,
18 withdrawal_queue::WithdrawalQueue,
19 YEAR_PER_MS,
20};
21
22#[derive(Debug, Copy, Clone)]
23pub struct SnapshotProof(());
24
25#[derive(BorshStorageKey)]
26#[near]
27enum StorageKey {
28 SupplyPositions,
29 BorrowPositions,
30 FinalizedSnapshots,
31 WithdrawalQueue,
32 StaticYield,
33}
34
35#[near]
36pub struct Market {
37 prefix: Vec<u8>,
38 pub configuration: MarketConfiguration,
39 pub borrow_asset_balance: BorrowAssetAmount,
41 pub borrow_asset_deposited_active: BorrowAssetAmount,
43 pub borrow_asset_deposited_incoming: Vec<IncomingDeposit>,
45 pub borrow_asset_withdrawal_in_flight: BorrowAssetAmount,
46 pub borrow_asset_borrowed_in_flight: BorrowAssetAmount,
50 pub borrow_asset_borrowed: BorrowAssetAmount,
54 pub borrow_asset_paid_to_fees: BorrowAssetAmount,
56 pub collateral_asset_deposited: CollateralAssetAmount,
58 pub(crate) supply_positions: UnorderedMap<AccountId, SupplyPosition>,
59 pub(crate) borrow_positions: UnorderedMap<AccountId, BorrowPosition>,
60 pub current_time_chunk: TimeChunk,
61 pub current_yield_distribution: BorrowAssetAmount,
62 pub finalized_snapshots: ChunkedAppendOnlyList<Snapshot, 32>,
63 pub withdrawal_queue: WithdrawalQueue,
64 pub static_yield: LookupMap<AccountId, Accumulator<BorrowAsset>>,
65 single_snapshot_maximum_interest_precomputed: Decimal,
66}
67
68impl Market {
69 pub fn new(prefix: impl IntoStorageKey, configuration: MarketConfiguration) -> Self {
70 if let Err(e) = configuration.validate() {
71 crate::panic_with_message(&e.to_string());
72 }
73
74 let prefix = prefix.into_storage_key();
75 macro_rules! key {
76 ($key: ident) => {
77 [
78 prefix.as_slice(),
79 StorageKey::$key.into_storage_key().as_slice(),
80 ]
81 .concat()
82 };
83 }
84
85 let first_snapshot = Snapshot::new(configuration.time_chunk_configuration.previous());
86 let last_time_chunk = configuration.time_chunk_configuration.now();
87
88 let single_snapshot_maximum_interest_precomputed =
89 configuration.single_snapshot_maximum_interest();
90
91 let mut self_ = Self {
92 prefix: prefix.clone(),
93 configuration,
94 borrow_asset_balance: 0.into(),
95 borrow_asset_deposited_active: 0.into(),
96 borrow_asset_deposited_incoming: Vec::new(),
97 borrow_asset_withdrawal_in_flight: 0.into(),
98 borrow_asset_borrowed_in_flight: 0.into(),
99 borrow_asset_borrowed: 0.into(),
100 borrow_asset_paid_to_fees: 0.into(),
101 collateral_asset_deposited: 0.into(),
102 supply_positions: UnorderedMap::new(key!(SupplyPositions)),
103 borrow_positions: UnorderedMap::new(key!(BorrowPositions)),
104 current_time_chunk: last_time_chunk,
105 current_yield_distribution: 0.into(),
106 finalized_snapshots: ChunkedAppendOnlyList::new(key!(FinalizedSnapshots)),
107 withdrawal_queue: WithdrawalQueue::new(key!(WithdrawalQueue)),
108 static_yield: LookupMap::new(key!(StaticYield)),
109 single_snapshot_maximum_interest_precomputed,
110 };
111
112 self_.finalized_snapshots.push(first_snapshot);
113
114 self_
115 }
116
117 pub fn borrowed(&self) -> BorrowAssetAmount {
118 self.borrow_asset_borrowed + self.borrow_asset_borrowed_in_flight
119 }
120
121 pub fn total_incoming(&self) -> BorrowAssetAmount {
122 self.borrow_asset_deposited_incoming
123 .iter()
124 .fold(BorrowAssetAmount::zero(), |total_incoming, incoming| {
125 total_incoming + incoming.amount
126 })
127 }
128
129 pub fn incoming_at(&self, snapshot_index: u32) -> BorrowAssetAmount {
130 self.borrow_asset_deposited_incoming
131 .iter()
132 .find_map(|incoming| {
133 (incoming.activate_at_snapshot_index == snapshot_index).then_some(incoming.amount)
134 })
135 .unwrap_or(0.into())
136 }
137
138 pub fn get_last_finalized_snapshot(&self) -> &Snapshot {
139 #[allow(clippy::unwrap_used, reason = "Snapshots are never empty")]
140 self.finalized_snapshots
141 .get(self.finalized_snapshots.len() - 1)
142 .unwrap()
143 }
144
145 pub fn current_snapshot(&self) -> Snapshot {
146 let current_snapshot_index = self.finalized_snapshots.len();
147 let incoming = self.incoming_at(current_snapshot_index);
148
149 let active = self.borrow_asset_deposited_active + incoming;
150
151 let borrowed = self.borrowed();
152
153 let interest_rate = self
154 .configuration
155 .borrow_interest_rate_strategy
156 .at(usage_ratio(active, borrowed));
157
158 Snapshot {
159 time_chunk: self.current_time_chunk,
160 end_timestamp_ms: env::block_timestamp_ms().into(),
161 borrow_asset_deposited_active: active,
162 borrow_asset_borrowed: borrowed,
163 collateral_asset_deposited: self.collateral_asset_deposited,
164 yield_distribution: self.current_yield_distribution,
165 interest_rate,
166 }
167 }
168
169 pub fn snapshot(&mut self) -> SnapshotProof {
170 let now = self.configuration.time_chunk_configuration.now();
171
172 if self.current_time_chunk == now {
174 return SnapshotProof(());
175 }
176
177 let snapshot = self.current_snapshot();
178 let current_snapshot_index = self.finalized_snapshots.len();
179
180 MarketEvent::SnapshotFinalized {
182 index: current_snapshot_index,
183 snapshot: snapshot.clone(),
184 }
185 .emit();
186 self.finalized_snapshots.push(snapshot);
187
188 let current_snapshot_index = current_snapshot_index + 1;
190
191 for i in 0..self.borrow_asset_deposited_incoming.len() {
193 let incoming = &self.borrow_asset_deposited_incoming[i];
194 if incoming.activate_at_snapshot_index == current_snapshot_index {
195 self.borrow_asset_deposited_active += incoming.amount;
196 self.borrow_asset_deposited_incoming.remove(i);
197 break;
198 }
199 }
200
201 self.current_time_chunk = now;
203 self.current_yield_distribution = 0.into();
204
205 SnapshotProof(())
206 }
207
208 pub fn single_snapshot_fee(&self, amount: BorrowAssetAmount) -> Option<BorrowAssetAmount> {
209 (u128::from(amount) * self.single_snapshot_maximum_interest_precomputed)
210 .to_u128_ceil()
211 .map(Into::into)
212 }
213
214 pub fn interest_rate(&self) -> Decimal {
215 self.configuration
216 .borrow_interest_rate_strategy
217 .at(usage_ratio(
218 self.borrow_asset_deposited_active,
219 self.borrowed(),
220 ))
221 }
222
223 pub fn get_borrow_asset_available_to_borrow(&self) -> BorrowAssetAmount {
224 #[allow(
225 clippy::unwrap_used,
226 reason = "Factor is guaranteed to be <=1, so value must still fit in u128"
227 )]
228 let must_retain: BorrowAssetAmount = ((1u32
229 - self.configuration.borrow_asset_maximum_usage_ratio)
230 * Decimal::from(self.borrow_asset_deposited_active))
231 .to_u128_ceil()
232 .unwrap()
233 .into();
234
235 self.borrow_asset_deposited_active
236 .saturating_sub(self.borrowed())
237 .saturating_sub(must_retain)
238 }
239
240 pub fn iter_supply_positions(&self) -> impl Iterator<Item = (AccountId, SupplyPosition)> + '_ {
241 self.supply_positions.iter()
242 }
243
244 pub fn supply_position_ref(&self, account_id: AccountId) -> Option<SupplyPositionRef<&Self>> {
245 self.supply_positions
246 .get(&account_id)
247 .map(|position| SupplyPositionRef::new(self, account_id, position))
248 }
249
250 pub fn supply_position_guard(
251 &mut self,
252 _proof: SnapshotProof,
253 account_id: AccountId,
254 ) -> Option<SupplyPositionGuard<'_>> {
255 self.supply_positions
256 .get(&account_id)
257 .map(|position| SupplyPositionGuard::new(self, account_id, position))
258 }
259
260 pub fn get_or_create_supply_position_guard(
261 &mut self,
262 _proof: SnapshotProof,
263 account_id: AccountId,
264 ) -> SupplyPositionGuard<'_> {
265 let position = self
266 .supply_positions
267 .get(&account_id)
268 .unwrap_or_else(|| SupplyPosition::new(self.finalized_snapshots.len()));
269
270 SupplyPositionGuard::new(self, account_id, position)
271 }
272
273 pub fn cleanup_supply_position(&mut self, account_id: &AccountId) -> bool {
274 self.supply_positions
275 .get(account_id)
276 .filter(SupplyPosition::can_be_removed)
277 .and_then(|_| self.supply_positions.remove(account_id))
278 .is_some()
279 }
280
281 pub fn iter_borrow_positions(&self) -> impl Iterator<Item = (AccountId, BorrowPosition)> + '_ {
282 self.borrow_positions.iter()
283 }
284
285 pub fn borrow_position_ref(&self, account_id: AccountId) -> Option<BorrowPositionRef<&Self>> {
286 self.borrow_positions
287 .get(&account_id)
288 .map(|position| BorrowPositionRef::new(self, account_id, position))
289 }
290
291 pub fn borrow_position_guard(
292 &mut self,
293 _proof: SnapshotProof,
294 account_id: AccountId,
295 ) -> Option<BorrowPositionGuard<'_>> {
296 self.borrow_positions
297 .get(&account_id)
298 .map(|position| BorrowPositionGuard::new(self, account_id, position))
299 }
300
301 pub fn get_or_create_borrow_position_guard(
302 &mut self,
303 _proof: SnapshotProof,
304 account_id: AccountId,
305 ) -> BorrowPositionGuard<'_> {
306 let position = self
307 .borrow_positions
308 .get(&account_id)
309 .unwrap_or_else(|| BorrowPosition::new(self.finalized_snapshots.len()));
310
311 BorrowPositionGuard::new(self, account_id, position)
312 }
313
314 pub fn cleanup_borrow_position(&mut self, account_id: &AccountId) -> bool {
315 self.borrow_positions
316 .get(account_id)
317 .filter(|p| !p.exists())
318 .and_then(|_| self.borrow_positions.remove(account_id))
319 .is_some()
320 }
321
322 pub fn record_borrow_asset_protocol_yield(&mut self, amount: BorrowAssetAmount) {
323 let mut yield_record = self
324 .static_yield
325 .get(&self.configuration.protocol_account_id)
326 .unwrap_or_else(|| Accumulator::new(1));
327
328 yield_record.add_once(amount);
329
330 self.static_yield
331 .insert(&self.configuration.protocol_account_id, &yield_record);
332 }
333
334 pub fn record_borrow_asset_yield_distribution(&mut self, amount: BorrowAssetAmount) {
335 if amount.is_zero() {
337 return;
338 }
339
340 self.current_yield_distribution += amount;
341 }
342
343 pub fn accumulate_static_yield(
349 &mut self,
350 account_id: &AccountId,
351 snapshot_limit: u32,
352 ) -> Result<(), UnknownAccount> {
353 let weight_numerator = *self
354 .configuration
355 .yield_weights
356 .r#static
357 .get(account_id)
358 .ok_or(UnknownAccount)?;
359 let weight_denominator = self.configuration.yield_weights.total_weight().get();
360 let mut accumulator = self
361 .static_yield
362 .get(account_id)
363 .unwrap_or_else(|| Accumulator::new(1));
364
365 let mut next_snapshot_index = accumulator.get_next_snapshot_index();
366 let mut accumulated = Decimal::ZERO;
367
368 #[allow(clippy::unwrap_used, reason = "Guaranteed previous snapshot exists")]
369 let mut prev_end_timestamp_ms = self
370 .finalized_snapshots
371 .get(next_snapshot_index.checked_sub(1).unwrap())
372 .unwrap()
373 .end_timestamp_ms
374 .0;
375
376 #[allow(
377 clippy::cast_possible_truncation,
378 reason = "Assume # of snapshots is never >u32::MAX"
379 )]
380 for (i, snapshot) in self
381 .finalized_snapshots
382 .iter()
383 .enumerate()
384 .skip(next_snapshot_index as usize)
385 .take(snapshot_limit as usize)
386 {
387 let snapshot_duration_ms = snapshot.end_timestamp_ms.0 - prev_end_timestamp_ms;
388 let interest_paid_by_borrowers = Decimal::from(snapshot.borrow_asset_borrowed)
389 * snapshot.interest_rate
390 * snapshot_duration_ms
391 * YEAR_PER_MS;
392 let other_yield = Decimal::from(snapshot.yield_distribution);
393 accumulated +=
394 (interest_paid_by_borrowers + other_yield) * weight_numerator / weight_denominator;
395
396 next_snapshot_index = i as u32 + 1;
397 prev_end_timestamp_ms = snapshot.end_timestamp_ms.0;
398 }
399
400 let accumulation_record = AccumulationRecord {
401 #[allow(clippy::unwrap_used, reason = "Derived from real balances")]
404 amount: accumulated.to_u128_floor().unwrap().into(),
405 fraction_as_u128_dividend: accumulated.fractional_part_as_u128_dividend(),
406 next_snapshot_index,
407 };
408
409 accumulator.accumulate(accumulation_record);
410
411 self.static_yield.insert(account_id, &accumulator);
412
413 Ok(())
414 }
415}
416
417#[derive(Debug, thiserror::Error)]
418#[error("This account does not earn static yield")]
419pub struct UnknownAccount;
420
421pub fn usage_ratio(active: BorrowAssetAmount, borrowed: BorrowAssetAmount) -> Decimal {
423 if active.is_zero() || borrowed.is_zero() {
424 Decimal::ZERO
425 } else if borrowed >= active {
426 Decimal::ONE
427 } else {
428 Decimal::from(borrowed) / Decimal::from(active)
429 }
430}
431
432#[allow(clippy::too_many_lines)]
433#[cfg(test)]
434mod tests {
435 use near_sdk::{test_utils::*, testing_env, VMContext};
436 use templar_primitives::dec;
437
438 use crate::{
439 asset::FungibleAsset,
440 borrow::InitialBorrow,
441 fee::{Fee, TimeBasedFee},
442 interest_rate_strategy::InterestRateStrategy,
443 market::{PriceOracleConfiguration, Withdrawal, YieldWeights},
444 oracle::pyth::{PriceIdentifier, PythTimestamp},
445 price::PricePair,
446 supply::WithdrawalAttempt,
447 time_chunk::TimeChunkConfiguration,
448 };
449
450 use super::*;
451
452 fn configuration() -> MarketConfiguration {
453 MarketConfiguration {
454 time_chunk_configuration: TimeChunkConfiguration::new(1),
455 borrow_asset: FungibleAsset::nep141("borrow.near".parse().unwrap()),
456 collateral_asset: FungibleAsset::nep141("collateral.near".parse().unwrap()),
457 price_oracle_configuration: PriceOracleConfiguration {
458 account_id: "pyth-oracle.near".parse().unwrap(),
459 collateral_asset_price_id: PriceIdentifier([0xcc; 32]),
460 collateral_asset_decimals: 24,
461 borrow_asset_price_id: PriceIdentifier([0xbb; 32]),
462 borrow_asset_decimals: 24,
463 price_maximum_age_s: 60,
464 },
465 borrow_mcr_maintenance: dec!("1.25"),
466 borrow_mcr_liquidation: dec!("1.2"),
467 borrow_asset_maximum_usage_ratio: dec!("0.9"),
468 borrow_origination_fee: Fee::Proportional(dec!("0.25")),
469 borrow_interest_rate_strategy: InterestRateStrategy::zero(),
470 borrow_maximum_duration_ms: None,
471 borrow_range: (1, None).try_into().unwrap(),
472 supply_range: (1, None).try_into().unwrap(),
473 supply_withdrawal_range: (1, None).try_into().unwrap(),
474 supply_withdrawal_fee: TimeBasedFee::zero(),
475 yield_weights: YieldWeights::new_with_supply_weight(9)
476 .with_static("revenue.tmplr.near".parse().unwrap(), 1),
477 protocol_account_id: "revenue.tmplr.near".parse().unwrap(),
478 liquidation_maximum_spread: dec!("0.05"),
479 }
480 }
481
482 fn price_pair(collateral: i64, borrow: i64) -> PricePair {
483 PricePair::new(
484 &crate::oracle::pyth::Price {
485 price: collateral.into(),
486 conf: 0.into(),
487 expo: 24,
488 publish_time: PythTimestamp::from_secs(10),
489 },
490 24,
491 &crate::oracle::pyth::Price {
492 price: borrow.into(),
493 conf: 0.into(),
494 expo: 24,
495 publish_time: PythTimestamp::from_secs(10),
496 },
497 24,
498 )
499 .unwrap()
500 }
501
502 struct TestMarketController {
503 pub context: VMContext,
504 pub market: Market,
505 }
506
507 impl TestMarketController {
508 pub fn print(&self) {
509 eprintln!(
510 "Available: {}",
511 self.market.get_borrow_asset_available_to_borrow(),
512 );
513 eprintln!("Balance: {}", self.market.borrow_asset_balance);
514 eprintln!("Borrowed: {}", self.market.borrow_asset_borrowed);
515 eprintln!("Supply: {}", self.market.borrow_asset_deposited_active);
516 eprintln!("Paid to fees: {}", self.market.borrow_asset_paid_to_fees);
517 eprintln!("{:#?}", self.market.borrow_asset_deposited_incoming);
518 }
519
520 pub fn new(configuration: MarketConfiguration) -> Self {
521 let context = VMContextBuilder::new()
522 .block_timestamp(1_000_000_000_000)
523 .build();
524 testing_env!(context.clone());
525
526 let market = Market::new(b"m", configuration);
527
528 Self { context, market }
529 }
530
531 pub fn tick(&mut self) -> SnapshotProof {
532 self.context.block_timestamp += 1_000_000;
533 testing_env!(self.context.clone());
534 self.market.snapshot()
535 }
536
537 pub fn supply(&mut self, account: AccountId, amount: u128) {
538 let snapshot = self.tick();
539 let mut supply_position = self
540 .market
541 .get_or_create_supply_position_guard(snapshot, account);
542 let yield_proof = supply_position.accumulate_yield();
543 supply_position.record_deposit(yield_proof, amount.into(), env::block_timestamp_ms());
544 }
545
546 pub fn collateralize(&mut self, account: AccountId, amount: u128) {
547 let snapshot_proof = self.tick();
548 let mut borrow_position = self
549 .market
550 .get_or_create_borrow_position_guard(snapshot_proof, account);
551 let interest_proof = borrow_position.accumulate_interest();
552 borrow_position.record_collateral_asset_deposit(interest_proof, amount.into());
553 }
554
555 pub fn borrow_initial(&mut self, account_id: AccountId, amount: u128) -> InitialBorrow {
556 let snapshot = self.tick();
557 let mut borrow_position = self
558 .market
559 .borrow_position_guard(snapshot, account_id)
560 .unwrap();
561 let interest_proof = borrow_position.accumulate_interest();
562 borrow_position
563 .record_borrow_initial(
564 snapshot,
565 interest_proof,
566 amount.into(),
567 &price_pair(1, 1),
568 env::block_timestamp_ms(),
569 )
570 .unwrap()
571 }
572
573 pub fn borrow_final(&mut self, account_id: AccountId, initial: &InitialBorrow) {
574 let snapshot = self.tick();
575 let mut borrow_position = self
576 .market
577 .borrow_position_guard(snapshot, account_id)
578 .unwrap();
579 let interest_proof = borrow_position.accumulate_interest();
580 borrow_position.record_borrow_final(
581 snapshot,
582 interest_proof,
583 initial,
584 true,
585 env::block_timestamp_ms(),
586 );
587 }
588
589 pub fn accumulate_interest(&mut self, account_id: AccountId) -> BorrowPosition {
590 let snapshot = self.tick();
591 let mut borrow_position = self
592 .market
593 .borrow_position_guard(snapshot, account_id)
594 .unwrap();
595 let _ = borrow_position.accumulate_interest();
596 borrow_position.inner().clone()
597 }
598
599 pub fn repay(
600 &mut self,
601 account_id: AccountId,
602 amount: impl Into<BorrowAssetAmount>,
603 ) -> BorrowAssetAmount {
604 let snapshot = self.tick();
605 let mut borrow_position = self
606 .market
607 .borrow_position_guard(snapshot, account_id)
608 .unwrap();
609 let interest_proof = borrow_position.accumulate_interest();
610 borrow_position.record_repay(interest_proof, amount.into())
611 }
612
613 pub fn withdraw_collateral_initial(&mut self, account_id: AccountId, amount: u128) {
614 let snapshot = self.tick();
615 let mut borrow_position = self
616 .market
617 .borrow_position_guard(snapshot, account_id)
618 .unwrap();
619 let interest_proof = borrow_position.accumulate_interest();
620 borrow_position
621 .record_collateral_asset_withdrawal_initial(interest_proof, amount.into());
622 }
623
624 pub fn withdraw_collateral_final(&mut self, account_id: AccountId, amount: u128) {
625 let snapshot = self.tick();
626 let mut borrow_position = self
627 .market
628 .borrow_position_guard(snapshot, account_id)
629 .unwrap();
630 let interest_proof = borrow_position.accumulate_interest();
631 borrow_position.record_collateral_asset_withdrawal_final(
632 interest_proof,
633 amount.into(),
634 true,
635 );
636 }
637
638 pub fn liquidate(
639 &mut self,
640 liquidator_id: AccountId,
641 position_id: AccountId,
642 send: u128,
643 request: u128,
644 price_pair: &PricePair,
645 ) {
646 let snapshot = self.tick();
647 let mut borrow_position = self
648 .market
649 .borrow_position_guard(snapshot, position_id)
650 .unwrap();
651 let interest_proof = borrow_position.accumulate_interest();
652 let liquidation = borrow_position
653 .record_liquidation(
654 interest_proof,
655 liquidator_id,
656 send.into(),
657 Some(request.into()),
658 price_pair,
659 env::block_timestamp_ms(),
660 )
661 .unwrap();
662 assert_eq!(u128::from(liquidation.liquidated), request);
663 }
664
665 pub fn accumulate_yield(&mut self, account_id: AccountId) -> SupplyPosition {
666 let snapshot = self.tick();
667 let mut supply_position = self
668 .market
669 .supply_position_guard(snapshot, account_id)
670 .unwrap();
671 let _ = supply_position.accumulate_yield();
672 supply_position.inner().clone()
673 }
674
675 pub fn withdraw_supply_initial(
676 &mut self,
677 account_id: AccountId,
678 amount: u128,
679 ) -> WithdrawalAttempt {
680 let snapshot = self.tick();
681 let mut supply_position = self
682 .market
683 .supply_position_guard(snapshot, account_id)
684 .unwrap();
685 let proof = supply_position.accumulate_yield();
686 supply_position.record_withdrawal_initial(
687 proof,
688 amount.into(),
689 env::block_timestamp_ms(),
690 )
691 }
692
693 pub fn withdraw_supply_final(&mut self, account_id: AccountId, initial: &Withdrawal) {
694 let snapshot = self.tick();
695 let mut supply_position = self
696 .market
697 .supply_position_guard(snapshot, account_id)
698 .unwrap();
699 supply_position.record_withdrawal_final(initial, true);
700 }
701 }
702
703 #[test]
704 fn balance_1() {
705 let supplier: AccountId = "supply.near".parse().unwrap();
706 let borrower: AccountId = "borrow.near".parse().unwrap();
707
708 let mut c = TestMarketController::new(configuration());
709
710 c.supply(supplier.clone(), 10_000_000);
712 assert_eq!(c.market.borrow_asset_balance, 10_000_000.into());
713 assert_eq!(
714 c.market.get_borrow_asset_available_to_borrow(),
715 0.into(),
716 "still incoming, not yet active",
717 );
718
719 c.collateralize(borrower.clone(), 4_000_000);
720 assert_eq!(c.market.borrow_asset_balance, 10_000_000.into());
721 assert_eq!(
722 c.market.get_borrow_asset_available_to_borrow(),
723 9_000_000.into()
724 );
725
726 let initial = c.borrow_initial(borrower.clone(), 2_000_000);
727 c.print();
728 assert_eq!(c.market.borrow_asset_balance, 8_000_000.into());
729 assert_eq!(
730 c.market.get_borrow_asset_available_to_borrow(),
731 7_000_000.into()
732 );
733
734 c.borrow_final(borrower.clone(), &initial);
735 assert_eq!(c.market.borrow_asset_borrowed, 2_000_000.into());
736 assert_eq!(c.market.borrow_asset_balance, 8_000_000.into());
737 assert_eq!(
738 c.market.get_borrow_asset_available_to_borrow(),
739 7_000_000.into()
740 );
741
742 c.repay(borrower.clone(), 1_500_000);
744 assert_eq!(c.market.borrow_asset_borrowed, 1_000_000.into());
745 assert_eq!(c.market.borrow_asset_balance, 9_500_000.into());
746 assert_eq!(
747 c.market.get_borrow_asset_available_to_borrow(),
748 8_000_000.into()
749 );
750
751 c.withdraw_collateral_initial(borrower.clone(), 2_000_000);
753 assert_eq!(c.market.borrow_asset_balance, 9_500_000.into());
754 assert_eq!(
755 c.market.get_borrow_asset_available_to_borrow(),
756 8_000_000.into()
757 );
758
759 c.withdraw_collateral_final(borrower.clone(), 2_000_000);
761 assert_eq!(c.market.borrow_asset_balance, 9_500_000.into());
762 assert_eq!(
763 c.market.get_borrow_asset_available_to_borrow(),
764 8_000_000.into()
765 );
766
767 let liquidator: AccountId = "liquidator.near".parse().unwrap();
769 c.liquidate(
770 liquidator.clone(),
771 borrower.clone(),
772 1_000_000,
773 2_000_000,
774 &price_pair(1, 2),
775 );
776 assert_eq!(c.market.borrow_asset_balance, 10_500_000.into());
777 assert_eq!(
778 c.market.get_borrow_asset_available_to_borrow(),
779 9_000_000.into()
780 );
781
782 let expected_yield_amount: BorrowAssetAmount = (500_000 * 9 / 10).into();
784 let yield_amount = c
785 .accumulate_yield(supplier.clone())
786 .borrow_asset_yield
787 .get_total();
788 assert_eq!(yield_amount, expected_yield_amount);
789 assert_eq!(
790 c.market.borrow_asset_balance,
791 10_500_000.into(),
792 "Yield compounding does not affect the market's recorded balance",
793 );
794 assert_eq!(
795 c.market.get_borrow_asset_available_to_borrow(),
796 BorrowAssetAmount::new(9_000_000), );
798
799 c.tick(); assert_eq!(c.market.borrow_asset_balance, 10_500_000.into());
801 assert_eq!(c.market.borrow_asset_deposited_active, 10_000_000.into());
802 assert_eq!(
804 c.market.get_borrow_asset_available_to_borrow(),
805 BorrowAssetAmount::new(10_000_000 * 9 / 10),
806 );
807
808 let initial = c.withdraw_supply_initial(supplier.clone(), 10_450_000);
810 let initial = match initial {
811 WithdrawalAttempt::Full(initial) => initial,
812 a => {
813 panic!("Should be full withdrawal: {a:?}");
814 }
815 };
816 assert_eq!(c.market.borrow_asset_balance, 50_000.into());
817 assert_eq!(c.market.get_borrow_asset_available_to_borrow(), 0.into());
818
819 c.withdraw_supply_final(supplier.clone(), &initial);
821 assert_eq!(c.market.borrow_asset_balance, 50_000.into());
822 assert_eq!(c.market.get_borrow_asset_available_to_borrow(), 0.into());
823 }
824
825 #[rstest::rstest]
826 #[should_panic = "InsufficientBorrowAssetAvailable"]
827 #[case(65_000_000)]
828 #[case(63_500_000)]
829 fn balance_2(#[case] second_borrow_amount: u128) {
830 let mut configuration = configuration();
831
832 configuration.borrow_origination_fee = Fee::Flat(15_000_000.into());
833 configuration.borrow_interest_rate_strategy = InterestRateStrategy::zero();
834 configuration.borrow_asset_maximum_usage_ratio = Decimal::ONE;
835
836 let mut c = TestMarketController::new(configuration);
837
838 let supply_id: AccountId = "supply.near".parse().unwrap();
839 let borrow_id: AccountId = "borrow.near".parse().unwrap();
840 let borrow_2_id: AccountId = "borrow2.near".parse().unwrap();
841
842 c.supply(supply_id.clone(), 100_000_000);
844 assert_eq!(c.market.borrow_asset_balance, 100_000_000.into());
845 assert_eq!(
846 c.market.get_borrow_asset_available_to_borrow(),
847 0.into() );
849
850 c.collateralize(borrow_id.clone(), 200_000_000);
852 assert_eq!(c.market.borrow_asset_balance, 100_000_000.into());
853 assert_eq!(
854 c.market.get_borrow_asset_available_to_borrow(),
855 100_000_000.into()
856 );
857
858 let initial = c.borrow_initial(borrow_id.clone(), 100_000_000);
860 assert_eq!(c.market.borrow_asset_balance, 0.into());
861 assert_eq!(c.market.get_borrow_asset_available_to_borrow(), 0.into());
862
863 c.borrow_final(borrow_id.clone(), &initial);
865 assert_eq!(c.market.borrow_asset_balance, 0.into());
866 assert_eq!(c.market.get_borrow_asset_available_to_borrow(), 0.into());
867
868 let amount_repaid = c
870 .accumulate_interest(borrow_id.clone())
871 .get_total_borrow_asset_liability();
872 let amount_remaining = c.repay(borrow_id.clone(), amount_repaid);
873 assert_eq!(amount_remaining, 0.into());
874 assert_eq!(c.market.borrow_asset_balance, amount_repaid);
875 assert_eq!(
876 c.market.get_borrow_asset_available_to_borrow(),
877 100_000_000.into()
878 );
879
880 let yield_amount = c
882 .accumulate_yield(supply_id.clone())
883 .borrow_asset_yield
884 .get_total();
885 assert_eq!(
886 c.market.get_borrow_asset_available_to_borrow(),
887 BorrowAssetAmount::new(100_000_000)
888 );
889 let withdrawal = c.withdraw_supply_initial(supply_id.clone(), 50_000_000);
890 let WithdrawalAttempt::Full(withdrawal) = withdrawal else {
891 panic!("Expected full withdrawal");
892 };
893 assert_eq!(
894 c.market.borrow_asset_balance,
895 amount_repaid - BorrowAssetAmount::new(50_000_000),
896 );
897 c.print();
898 assert_eq!(
899 BorrowAssetAmount::new(50_000_000) + yield_amount,
900 63_500_000.into(),
901 );
902 assert_eq!(
903 c.market.get_borrow_asset_available_to_borrow(),
904 63_500_000.into(),
905 );
906
907 c.withdraw_supply_final(supply_id.clone(), &withdrawal);
909 c.print();
910 assert_eq!(
911 c.market.borrow_asset_balance,
912 amount_repaid - BorrowAssetAmount::new(50_000_000),
913 );
914 assert_eq!(c.market.borrow_asset_deposited_incoming.len(), 0);
915 assert_eq!(
916 c.market.get_borrow_asset_available_to_borrow(),
917 63_500_000.into(),
918 );
919
920 c.accumulate_yield(supply_id.clone());
921 c.print();
922 assert_eq!(
923 c.market.get_borrow_asset_available_to_borrow(),
924 63_500_000.into(),
925 );
926
927 c.collateralize(borrow_2_id.clone(), 200_000_000);
929 assert_eq!(
930 c.market.borrow_asset_balance,
931 amount_repaid - BorrowAssetAmount::new(50_000_000),
932 );
933 assert_eq!(
934 c.market.get_borrow_asset_available_to_borrow(),
935 63_500_000.into(),
936 );
937
938 c.print();
939
940 let initial = c.borrow_initial(borrow_2_id.clone(), second_borrow_amount);
942 assert_eq!(
943 c.market.borrow_asset_balance,
944 amount_repaid - BorrowAssetAmount::new(50_000_000) - second_borrow_amount,
945 );
946 assert_eq!(
947 c.market.get_borrow_asset_available_to_borrow(),
948 BorrowAssetAmount::new(63_500_000) - second_borrow_amount,
949 );
950
951 eprintln!("Borrow2 final");
952 eprintln!("{initial:?}");
953 eprintln!("{}", c.market.borrow_asset_borrowed_in_flight);
954
955 c.borrow_final(borrow_2_id.clone(), &initial);
957 assert_eq!(
958 c.market.borrow_asset_balance,
959 amount_repaid - BorrowAssetAmount::new(50_000_000) - second_borrow_amount,
960 );
961
962 c.print();
963 }
964
965 #[test]
966 fn balance_3() {
967 let mut configuration = configuration();
968 configuration.borrow_origination_fee = Fee::Flat(10_000_000.into());
969 configuration.borrow_interest_rate_strategy = InterestRateStrategy::zero();
970 configuration.yield_weights = YieldWeights::new_with_supply_weight(1);
971 configuration.borrow_asset_maximum_usage_ratio = Decimal::ONE;
972
973 let supply_id: AccountId = "supply.near".parse().unwrap();
974 let borrow_id: AccountId = "borrow.near".parse().unwrap();
975
976 let mut c = TestMarketController::new(configuration);
977
978 c.supply(supply_id.clone(), 100_000_000);
980 assert_eq!(c.market.borrow_asset_balance, 100_000_000.into());
981 assert_eq!(
982 c.market.get_borrow_asset_available_to_borrow(),
983 0.into(),
984 "still incoming, not yet active",
985 );
986
987 c.collateralize(borrow_id.clone(), 100_000_000);
989 assert_eq!(c.market.borrow_asset_balance, 100_000_000.into());
990 assert_eq!(
991 c.market.get_borrow_asset_available_to_borrow(),
992 100_000_000.into()
993 );
994
995 let initial = c.borrow_initial(borrow_id.clone(), 60_000_000);
997 c.print();
998 assert_eq!(c.market.borrow_asset_balance, 40_000_000.into());
999 assert_eq!(
1000 c.market.get_borrow_asset_available_to_borrow(),
1001 40_000_000.into()
1002 );
1003
1004 c.borrow_final(borrow_id.clone(), &initial);
1006 assert_eq!(c.market.borrow_asset_borrowed, 60_000_000.into());
1007 assert_eq!(c.market.borrow_asset_balance, 40_000_000.into());
1008 assert_eq!(
1009 c.market.get_borrow_asset_available_to_borrow(),
1010 40_000_000.into()
1011 );
1012
1013 c.accumulate_yield(supply_id.clone())
1014 .borrow_asset_yield
1015 .get_total();
1016 assert_eq!(c.market.borrow_asset_borrowed, 60_000_000.into());
1017 assert_eq!(c.market.borrow_asset_balance, 40_000_000.into());
1018 assert_eq!(
1019 c.market.get_borrow_asset_available_to_borrow(),
1020 40_000_000.into()
1021 );
1022
1023 c.tick();
1024 c.tick();
1025 c.print();
1026
1027 assert_eq!(c.market.borrow_asset_borrowed, 60_000_000.into());
1028 assert_eq!(c.market.borrow_asset_balance, 40_000_000.into());
1029 assert_eq!(
1030 c.market.get_borrow_asset_available_to_borrow(),
1031 40_000_000.into()
1032 );
1033 }
1034}