-
-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathmarginfi_account.rs
More file actions
3375 lines (3015 loc) · 124 KB
/
Copy pathmarginfi_account.rs
File metadata and controls
3375 lines (3015 loc) · 124 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::price::{OraclePriceFeedAdapter, PriceAdapter};
use crate::{
allocator::{heap_pos, heap_restore},
check, check_eq, debug, live, math_error,
prelude::{MarginfiError, MarginfiResult},
state::bank::BankImpl,
utils::{is_integration_asset_tag, NumTraitsWithTolerance},
};
use anchor_lang::prelude::*;
use fixed::types::I80F48;
use marginfi_type_crate::{
constants::{
ASSET_TAG_DEFAULT, ASSET_TAG_DRIFT, ASSET_TAG_JUPLEND, ASSET_TAG_KAMINO, ASSET_TAG_SOL,
ASSET_TAG_SOLEND, ASSET_TAG_STAKED, BANKRUPT_THRESHOLD, BANK_SAME_ASSET_EMODE_ELIGIBLE,
CIRCUIT_BREAKER_ENABLED, EXP_10_I80F48, MAX_INTEGRATION_POSITIONS, ORDER_ACTIVE_TAGS,
ZERO_AMOUNT_THRESHOLD,
},
types::{
compute_same_asset_emode_weight, reconcile_emode_configs, u32_to_basis, Balance,
BalanceSide, Bank, BankOperationalState, EmodeConfig, HealthCache, HealthPriceMode,
LendingAccount, LiquidationPriceCache, MarginfiAccount, MarginfiGroup, OracleFeedFamily,
OraclePriceType, OraclePriceWithConfidence, OracleSetup, PriceBias, ReconciledEmodeConfig,
RequirementType, RiskTier, ACCOUNT_DISABLED, ACCOUNT_FROZEN, ACCOUNT_IN_FLASHLOAN,
ACCOUNT_IN_ORDER_EXECUTION, ACCOUNT_IN_RECEIVERSHIP,
},
};
use std::{
cmp::{max, min},
collections::BTreeSet,
};
/// Returns the number of remaining accounts required for a bank (bank account + oracle/venue accounts).
///
/// Account counts by oracle setup and asset tag:
/// - `Fixed`: 1 (bank only)
/// - `FixedKamino`: 2 (bank + reserve)
/// - `FixedDrift`: 2 (bank + spot market)
/// - `FixedJuplend`: 2 (bank + lending state)
/// - `ASSET_TAG_STAKED`: 5 (bank + oracle + lst_mint + stake_pool + onramp)
/// - `ASSET_TAG_KAMINO` / `ASSET_TAG_DRIFT` / `ASSET_TAG_SOLEND` / `ASSET_TAG_JUPLEND`: 3 (bank + oracle + reserve)
/// - `ASSET_TAG_DEFAULT` / `ASSET_TAG_SOL`: 2 (bank + oracle)
pub fn get_remaining_accounts_per_bank(bank: &Bank) -> MarginfiResult<usize> {
match bank.config.oracle_setup {
OracleSetup::Fixed => Ok(1),
// Fixed + Kamino: bank + reserve (no oracle)
OracleSetup::FixedKamino => Ok(2),
// Fixed + Drift: bank + spot market (no oracle)
OracleSetup::FixedDrift => Ok(2),
// Fixed + JupLend: bank + lending state (no oracle)
OracleSetup::FixedJuplend => Ok(2),
_ => get_remaining_accounts_per_asset_tag(bank.config.asset_tag),
}
}
/// 5 for `ASSET_TAG_STAKED` (bank, oracle, lst mint, lst pool, onramp), 2 for most others (bank, oracle), 3
/// for Kamino (bank, oracle, reserve), 1 for Fixed
fn get_remaining_accounts_per_asset_tag(asset_tag: u8) -> MarginfiResult<usize> {
match asset_tag {
ASSET_TAG_DEFAULT | ASSET_TAG_SOL => Ok(2),
ASSET_TAG_KAMINO | ASSET_TAG_DRIFT | ASSET_TAG_SOLEND | ASSET_TAG_JUPLEND => Ok(3),
ASSET_TAG_STAKED => Ok(5),
_ => err!(MarginfiError::AssetTagMismatch),
}
}
pub trait MarginfiAccountImpl {
fn initialize(&mut self, group: Pubkey, authority: Pubkey, current_timestamp: u64);
fn set_flag(&mut self, flag: u64, msg: bool);
fn unset_flag(&mut self, flag: u64, msg: bool);
fn get_flag(&self, flag: u64) -> bool;
fn increment_active_orders(&mut self) -> MarginfiResult;
fn decrement_active_orders(&mut self) -> MarginfiResult;
fn can_be_closed(&self) -> bool;
fn sync_indexer_flags(&mut self);
}
/// Checks if a signer is authorized to perform actions on a marginfi account.
///
/// Returns `true` if the signer is authorized, `false` otherwise.
///
/// Authorization rules (checked in order):
/// 1. If `allow_receivership` is true and the (NOT signer's) account is in receivership → `true`
/// 2. If `allow_order_execution` is true and the account is in order execution → `true`
/// 3. If the account is frozen → `true` only if signer is the group admin
/// 4. Otherwise → `true` only if signer is the account authority
pub fn is_signer_authorized(
marginfi_account: &MarginfiAccount,
group_admin: Pubkey,
signer: Pubkey,
allow_receivership: bool,
allow_order_execution: bool,
) -> bool {
if allow_receivership && marginfi_account.get_flag(ACCOUNT_IN_RECEIVERSHIP) {
return marginfi_account.authority != signer; // forbidden to take receivership of your own account
}
if allow_order_execution && marginfi_account.get_flag(ACCOUNT_IN_ORDER_EXECUTION) {
return true;
}
if marginfi_account.get_flag(ACCOUNT_FROZEN) {
return group_admin == signer;
}
marginfi_account.authority == signer
}
/// Checks if the account authority is allowed to act on their account based on frozen status.
///
/// Returns `true` if the action is allowed, `false` if blocked.
///
/// Returns `false` when both conditions are met:
/// - The account is frozen
/// - The signer is the account authority
///
/// This is intentionally separate from [`is_signer_authorized`] to return a distinct
/// `AccountFrozen` error in the instruction context rather than `Unauthorized`.
pub fn account_not_frozen_for_authority(
marginfi_account: &MarginfiAccount,
signer: Pubkey,
) -> bool {
!(marginfi_account.get_flag(ACCOUNT_FROZEN) && marginfi_account.authority == signer)
}
/// Returns `true` if any bank backing an active balance on `marginfi_account` is CB-halted.
/// `remaining_ais` must be the standard bank+oracle layout used by the health computation:
/// one bank account followed by `get_remaining_accounts_per_bank(bank) - 1` venue/oracle
/// accounts per active balance.
pub fn any_balance_bank_is_cb_halted<'info>(
marginfi_account: &MarginfiAccount,
remaining_ais: &'info [AccountInfo<'info>],
) -> MarginfiResult<bool> {
let now = Clock::get()?.unix_timestamp;
let mut account_index = 0usize;
for balance in marginfi_account
.lending_account
.balances
.iter()
.filter(|b| b.is_active())
{
let bank_ai = remaining_ais
.get(account_index)
.ok_or(MarginfiError::InvalidBankAccount)?;
let bank_al = AccountLoader::<Bank>::try_from(bank_ai)?;
let bank = bank_al.load()?;
check_eq!(
balance.bank_pk,
*bank_ai.key,
MarginfiError::InvalidBankAccount
);
// Both a temporal halt and the non-expiring `CircuitBroken` state count as halted.
if bank.is_cb_halted(now)
|| bank.config.operational_state == BankOperationalState::CircuitBroken
{
return Ok(true);
}
let num_accounts = get_remaining_accounts_per_bank(&bank)?;
account_index = account_index.saturating_add(num_accounts);
}
Ok(false)
}
/// A deposit is halt-safe only when the account already holds an active balance in the bank.
/// Opening a new balance during a halt would let a liquidatable borrower dust-deposit into an
/// unrelated halted bank, flipping `any_balance_bank_is_cb_halted` and forcing liquidation of
/// the account into the admin-only path.
pub fn deposit_is_halt_safe(marginfi_account: &MarginfiAccount, bank_pk: &Pubkey) -> bool {
marginfi_account
.lending_account
.get_balance_index(bank_pk)
.is_ok()
}
/// Runs the inline circuit-breaker price gate (`BankImpl::cb_price_gate`) for every CB-enabled
/// bank backing an active balance on `marginfi_account`. Pure read — reverts with
/// `BankCircuitBreakerHalted` if any such bank is currently halted or `CircuitBroken` (a halted
/// bank's price has already been deemed unsafe, so it cannot back a risk-carrying action), or
/// with `CircuitBreakerPriceJump` if any such bank's live oracle price has jumped past the
/// breach threshold. Non-CB banks are skipped, so the common case pays no extra oracle reads.
///
/// Policy (deliberate fail-safe): the gate blocks risk-increasing actions (borrow, risk-carrying
/// withdraw, order execution, and the liquidator's own leg) on any price breach, whether the move
/// is oracle manipulation or genuine volatility, since the breaker cannot distinguish them and
/// erring toward a halt protects solvency. Risk-reducing / risk-neutral actions are intentionally
/// NOT gated so users can always de-risk during a breach: deposits and repayments run no gate, and
/// a liability-free withdraw is treated as halt-safe.
///
/// `remaining_ais` must be the standard bank+oracle layout used by the health computation.
pub fn run_cb_price_gate<'info>(
marginfi_account: &MarginfiAccount,
remaining_ais: &'info [AccountInfo<'info>],
) -> MarginfiResult<()> {
let clock = Clock::get()?;
let mut account_index = 0usize;
for balance in marginfi_account
.lending_account
.balances
.iter()
.filter(|b| b.is_active())
{
let bank_ai = remaining_ais
.get(account_index)
.ok_or(MarginfiError::InvalidBankAccount)?;
let bank_al = AccountLoader::<Bank>::try_from(bank_ai)?;
let bank = bank_al.load()?;
check_eq!(
balance.bank_pk,
*bank_ai.key,
MarginfiError::InvalidBankAccount
);
check!(
!bank.is_cb_halted(clock.unix_timestamp)
&& bank.config.operational_state != BankOperationalState::CircuitBroken,
MarginfiError::BankCircuitBreakerHalted
);
let num_accounts = get_remaining_accounts_per_bank(&bank)?;
if bank.get_flag(CIRCUIT_BREAKER_ENABLED) {
let oracle_start = account_index + 1;
let oracle_end = oracle_start + num_accounts - 1;
require_gte!(
remaining_ais.len(),
oracle_end,
MarginfiError::WrongNumberOfOracleAccounts
);
let oracle_ais = &remaining_ais[oracle_start..oracle_end];
// The breaker tracks the multiplier-adjusted price (see `cb_observation`), so the gate
// must compare against the same effective price.
let (_, cache_price) =
OraclePriceFeedAdapter::get_price_and_confidence_and_cache_of_type(
&bank,
oracle_ais,
&clock,
OraclePriceType::RealTime,
)?;
bank.cb_price_gate(cache_price.cb_observation()?)?;
}
account_index = account_index.saturating_add(num_accounts);
}
Ok(())
}
impl MarginfiAccountImpl for MarginfiAccount {
/// Set the initial data for the marginfi account.
fn initialize(&mut self, group: Pubkey, authority: Pubkey, current_timestamp: u64) {
self.authority = authority;
self.group = group;
self.emissions_destination_account = Pubkey::default();
self.migrated_from = Pubkey::default();
self.last_update = current_timestamp;
self.migrated_to = Pubkey::default();
self.indexer_flags.is_empty = 1;
// Seed activity flags so freshly-created accounts aren't immediately eligible for the
// permissionless close path before the first pulse.
self.indexer_flags.was_active_30d = 1;
self.indexer_flags.was_active_60d = 1;
self.active_orders = 0;
}
fn set_flag(&mut self, flag: u64, msg: bool) {
if msg {
msg!("Setting account flag {:b}", flag);
}
self.account_flags |= flag;
}
fn unset_flag(&mut self, flag: u64, msg: bool) {
if msg {
msg!("Unsetting account flag {:b}", flag);
}
self.account_flags &= !flag;
}
fn get_flag(&self, flag: u64) -> bool {
self.account_flags & flag != 0
}
fn increment_active_orders(&mut self) -> MarginfiResult {
// Note: Sanity check, expected to be unreachable, as this vastly exceeds max theoretical
// orders one account can open.
check!(
self.active_orders < u8::MAX,
MarginfiError::IllegalAction,
"Too many active orders"
);
self.active_orders += 1;
Ok(())
}
fn decrement_active_orders(&mut self) -> MarginfiResult {
// Note: Sanity check, expected to be unreachable
check!(
self.active_orders > 0,
MarginfiError::IllegalAction,
"No active orders to close"
);
self.active_orders -= 1;
Ok(())
}
fn can_be_closed(&self) -> bool {
let is_disabled = self.get_flag(ACCOUNT_DISABLED);
let is_in_flashloan = self.get_flag(ACCOUNT_IN_FLASHLOAN);
let is_in_receivership = self.get_flag(ACCOUNT_IN_RECEIVERSHIP);
let is_frozen = self.get_flag(ACCOUNT_FROZEN);
let only_has_empty_balances = self.lending_account.balances.iter().all(|balance| {
let liability_shares: I80F48 = balance.liability_shares.into();
balance.get_side().is_none() && liability_shares <= I80F48::ZERO
});
!is_disabled
&& only_has_empty_balances
&& !is_in_flashloan
&& !is_in_receivership
&& !is_frozen
}
fn sync_indexer_flags(&mut self) {
self.indexer_flags
.sync_balance_derived(&self.lending_account.balances);
self.indexer_flags.mark_active_now();
}
}
#[derive(Debug)]
pub enum BalanceIncreaseType {
Any,
RepayOnly,
DepositOnly,
BypassDepositLimit,
}
#[derive(Debug)]
pub enum BalanceDecreaseType {
WithdrawOnly,
BorrowOnly,
BypassBorrowLimit,
}
#[inline]
fn apply_price_bias(price: OraclePriceWithConfidence, bias: PriceBias) -> MarginfiResult<I80F48> {
let price = match bias {
PriceBias::Low => price
.price
.checked_sub(price.confidence)
.ok_or_else(math_error!()),
PriceBias::High => price
.price
.checked_add(price.confidence)
.ok_or_else(math_error!()),
}?;
Ok(price)
}
pub struct BankAccountWithCache<'a, 'info> {
bank: AccountLoader<'info, Bank>,
balance: &'a Balance,
}
impl<'info> BankAccountWithCache<'_, 'info> {
pub fn load<'a>(
lending_account: &'a LendingAccount,
remaining_ais: &'info [AccountInfo<'info>],
) -> MarginfiResult<Vec<BankAccountWithCache<'a, 'info>>> {
let mut account_index = 0;
let mut active_balance_count = 0;
for balance in lending_account.balances.iter() {
if balance.is_active() {
active_balance_count += 1;
}
}
let banks_only = remaining_ais.len() == active_balance_count;
lending_account
.balances
.iter()
.filter(|balance| balance.is_active())
.map(|balance| {
let bank_ai: Option<&AccountInfo<'info>> = remaining_ais.get(account_index);
if bank_ai.is_none() {
msg!("Ran out of remaining accounts at {:?}", account_index);
return err!(MarginfiError::InvalidBankAccount);
}
let bank_ai = bank_ai.unwrap();
let bank_al = AccountLoader::<Bank>::try_from(bank_ai)?;
let bank = bank_al.load()?;
let num_accounts = if banks_only {
1
} else {
get_remaining_accounts_per_bank(&bank)?
};
check_eq!(
balance.bank_pk,
*bank_ai.key,
MarginfiError::InvalidBankAccount
);
if !banks_only {
let end_idx = account_index + num_accounts;
require_gte!(
remaining_ais.len(),
end_idx,
MarginfiError::WrongNumberOfOracleAccounts
);
}
account_index += num_accounts;
Ok(BankAccountWithCache {
bank: bank_al.clone(),
balance,
})
})
.collect::<Result<Vec<_>>>()
}
fn write_liquidation_price_cache_from(
&self,
liq_cache: &LiquidationPriceCache,
index: usize,
) -> MarginfiResult<()> {
let mut bank = self.bank.load_mut()?;
let zero_price = OraclePriceWithConfidence {
price: I80F48::ZERO,
confidence: I80F48::ZERO,
source_time: 0,
};
let price_rt = liq_cache
.get_price(OraclePriceType::RealTime, index)
.unwrap_or(zero_price);
let price_twap = liq_cache
.get_price(OraclePriceType::TimeWeighted, index)
.unwrap_or(zero_price);
bank.cache.liquidation_price_rt = price_rt.price.into();
bank.cache.liquidation_price_rt_confidence = price_rt.confidence.into();
bank.cache.liquidation_price_twap = price_twap.price.into();
bank.cache.liquidation_price_twap_confidence = price_twap.confidence.into();
bank.cache.set_liquidation_price_cache_locked();
Ok(())
}
#[inline]
pub fn is_empty(&self, side: BalanceSide) -> bool {
self.balance.is_empty(side)
}
}
pub(crate) fn write_liquidation_price_cache_from<'info>(
marginfi_account: &MarginfiAccount,
remaining_ais: &'info [AccountInfo<'info>],
liq_cache: &LiquidationPriceCache,
) -> MarginfiResult<()> {
let bank_accounts_with_cache =
BankAccountWithCache::load(&marginfi_account.lending_account, remaining_ais)?;
for (i, bank_account) in bank_accounts_with_cache.iter().enumerate() {
bank_account.write_liquidation_price_cache_from(liq_cache, i)?;
}
Ok(())
}
fn get_cached_price_with_confidence(
bank: &Bank,
requirement_type: RequirementType,
) -> OraclePriceWithConfidence {
match requirement_type.get_oracle_price_type() {
OraclePriceType::RealTime => OraclePriceWithConfidence {
price: bank.cache.liquidation_price_rt.into(),
confidence: bank.cache.liquidation_price_rt_confidence.into(),
// Cached prices are used for risk-engine math, not CB detection — source_time is
// meaningful only inside `update_circuit_breaker`.
source_time: 0,
},
OraclePriceType::TimeWeighted => OraclePriceWithConfidence {
price: bank.cache.liquidation_price_twap.into(),
confidence: bank.cache.liquidation_price_twap_confidence.into(),
source_time: 0,
},
}
}
fn get_same_asset_weight_for_balance(
balance: &Balance,
bank: &Bank,
requirement_type: RequirementType,
reconciled_emode_config: &ReconciledEmodeConfig,
) -> Option<I80F48> {
if balance.is_empty(BalanceSide::Assets)
|| !reconciled_emode_config.same_asset.is_enabled()
|| bank.mint != reconciled_emode_config.same_asset.mint
|| bank.config.oracle_keys[0] != reconciled_emode_config.same_asset.oracle_key
|| bank.config.oracle_setup.feed_family() != reconciled_emode_config.same_asset.feed_family
|| !bank.get_flag(BANK_SAME_ASSET_EMODE_ELIGIBLE)
|| !matches!(bank.config.risk_tier, RiskTier::Collateral)
|| matches!(
(bank.config.operational_state, requirement_type),
(BankOperationalState::ReduceOnly, RequirementType::Initial)
)
{
return None;
}
Some(reconciled_emode_config.same_asset.asset_weight)
}
#[inline(always)]
fn calc_weighted_asset_value_cached_standalone(
balance: &Balance,
bank: &Bank,
requirement_type: RequirementType,
reconciled_emode_config: &ReconciledEmodeConfig,
) -> MarginfiResult<(I80F48, I80F48)> {
match bank.config.risk_tier {
RiskTier::Collateral => {
if matches!(
(bank.config.operational_state, requirement_type),
(BankOperationalState::ReduceOnly, RequirementType::Initial)
) {
debug!("ReduceOnly bank assets worth 0 for Initial margin");
return Ok((I80F48::ZERO, I80F48::ZERO));
}
let mut asset_weight = bank
.config
.get_weight(requirement_type, BalanceSide::Assets);
if let Some(emode_entry) = reconciled_emode_config.find_with_tag(bank.emode.emode_tag) {
asset_weight = max(asset_weight, emode_entry.asset_weight);
}
if let Some(same_asset_weight) = get_same_asset_weight_for_balance(
balance,
bank,
requirement_type,
reconciled_emode_config,
) {
asset_weight = max(asset_weight, same_asset_weight);
}
let price_with_confidence = get_cached_price_with_confidence(bank, requirement_type);
let lower_price = apply_price_bias(price_with_confidence, PriceBias::Low)?;
if matches!(requirement_type, RequirementType::Initial) {
if let Some(discount) = bank.maybe_get_asset_weight_init_discount(lower_price)? {
asset_weight = asset_weight
.checked_mul(discount)
.ok_or_else(math_error!())?;
}
}
let value = calc_value(
bank.get_asset_amount(balance.asset_shares.into())?,
lower_price,
bank.get_balance_decimals(),
Some(asset_weight),
)?;
Ok((value, lower_price))
}
RiskTier::Isolated => Ok((I80F48::ZERO, I80F48::ZERO)),
}
}
#[inline(always)]
fn calc_weighted_liab_value_cached_standalone(
balance: &Balance,
bank: &Bank,
requirement_type: RequirementType,
) -> MarginfiResult<(I80F48, I80F48)> {
let liability_weight = bank
.config
.get_weight(requirement_type, BalanceSide::Liabilities);
let price_with_confidence = get_cached_price_with_confidence(bank, requirement_type);
let higher_price = apply_price_bias(price_with_confidence, PriceBias::High)?;
let value = calc_value(
bank.get_liability_amount(balance.liability_shares.into())?,
higher_price,
bank.get_balance_decimals(),
Some(liability_weight),
)?;
Ok((value, higher_price))
}
#[inline(always)]
fn calc_weighted_value_cached_for_balance(
balance: &Balance,
bank: &Bank,
requirement_type: RequirementType,
reconciled_emode_config: &ReconciledEmodeConfig,
) -> MarginfiResult<(I80F48, I80F48, I80F48)> {
match balance.get_side() {
Some(side) => match side {
BalanceSide::Assets => {
let (value, price) = calc_weighted_asset_value_cached_standalone(
balance,
bank,
requirement_type,
reconciled_emode_config,
)?;
Ok((value, I80F48::ZERO, price))
}
BalanceSide::Liabilities => {
let (value, price) =
calc_weighted_liab_value_cached_standalone(balance, bank, requirement_type)?;
Ok((I80F48::ZERO, value, price))
}
},
None => Ok((I80F48::ZERO, I80F48::ZERO, I80F48::ZERO)),
}
}
/// Calculate the value of an asset, given its quantity with a decimal exponent, and a price with a decimal exponent, and an optional weight.
#[inline]
pub fn calc_value(
amount: I80F48,
price: I80F48,
mint_decimals: u8,
weight: Option<I80F48>,
) -> MarginfiResult<I80F48> {
if amount == I80F48::ZERO {
return Ok(I80F48::ZERO);
}
let scaling_factor = EXP_10_I80F48[mint_decimals as usize];
let weighted_asset_amount = if let Some(weight) = weight {
amount.checked_mul(weight).unwrap()
} else {
amount
};
#[cfg(target_os = "solana")]
debug!(
"weighted_asset_qt: {}, price: {}, expo: {}",
weighted_asset_amount, price, mint_decimals
);
let value = weighted_asset_amount
.checked_mul(price)
.ok_or_else(math_error!())?
.checked_div(scaling_factor)
.ok_or_else(math_error!())?;
Ok(value)
}
#[inline]
pub fn calc_amount(value: I80F48, price: I80F48, mint_decimals: u8) -> MarginfiResult<I80F48> {
let scaling_factor = EXP_10_I80F48[mint_decimals as usize];
let qt = value
.checked_mul(scaling_factor)
.ok_or_else(math_error!())?
.checked_div(price)
.ok_or_else(math_error!())?;
Ok(qt)
}
// =============================================================================
// RISK ENGINE - HEAP-EFFICIENT HEALTH CALCULATION
// =============================================================================
//
// These functions provide the core risk engine functionality for marginfi accounts.
// They calculate account health, validate liquidation conditions, and enforce
// risk constraints.
//
// ## Public API
//
// - `check_account_init_health` - Validates health after risky actions (borrow/withdraw)
// - `check_pre_liquidation_condition_and_get_account_health` - Pre-liquidation validation
// - `check_post_liquidation_condition_and_get_account_health` - Post-liquidation validation
// - `check_account_bankrupt` - Bankruptcy condition check
// - `get_health_components` - Core health calculation (assets vs liabilities)
//
// ## Heap Reuse Optimization
//
// All functions use the custom allocator's heap reuse feature (heap_pos/heap_restore)
// to process positions one at a time, keeping peak heap usage low. This enables
// support for up to 16 positions (MAX_LENDING_ACCOUNT_BALANCES) without exceeding
// the default 32 KiB heap limit or requiring requestHeapFrame.
//
// See allocator.rs for details on the heap reuse mechanism.
// =============================================================================
// -----------------------------------------------------------------------------
// Internal Helpers
// -----------------------------------------------------------------------------
/// Iterator that yields each liability balance's `EmodeConfig` from a lending account while
/// folding the same-asset accumulators in a single pass. Each `EmodeConfig` is ~400 bytes, so
/// yielding one at a time keeps peak stack usage manageable across the 16-position limit.
///
/// When `same_asset_leverage` is `Some`, `next()` also tracks the shared liability mint and the
/// running lowest liability-side weight; the post-iteration `reconcile()` folds those into the
/// returned `ReconciledEmodeConfig`.
struct EmodeConfigIterator<'a, 'info> {
lending_account: &'a LendingAccount,
remaining_ais: &'info [AccountInfo<'info>],
balance_index: usize,
account_index: usize,
banks_only: bool,
requirement_type: RequirementType,
same_asset_leverage: Option<I80F48>,
shared_mint: Option<Pubkey>,
shared_oracle_key: Option<Pubkey>,
shared_feed_family: Option<OracleFeedFamily>,
lowest_liab_weight: Option<I80F48>,
same_asset_invalid: bool,
}
impl<'a, 'info> EmodeConfigIterator<'a, 'info> {
fn new(
lending_account: &'a LendingAccount,
remaining_ais: &'info [AccountInfo<'info>],
banks_only: bool,
requirement_type: RequirementType,
same_asset_leverage: Option<I80F48>,
) -> Self {
Self {
lending_account,
remaining_ais,
balance_index: 0,
account_index: 0,
banks_only,
requirement_type,
same_asset_leverage,
shared_mint: None,
shared_oracle_key: None,
shared_feed_family: None,
lowest_liab_weight: None,
same_asset_invalid: false,
}
}
/// Drives the iterator to completion via `reconcile_emode_configs`, then folds any tracked
/// same-asset state into the reconciled config when same-asset emode is active and all active
/// liabilities shared a single mint.
fn reconcile(mut self) -> ReconciledEmodeConfig {
let requirement_type = self.requirement_type;
let mut reconciled = reconcile_emode_configs(&mut self, requirement_type);
if let (
Some(leverage),
false,
Some(mint),
Some(oracle_key),
Some(feed_family),
Some(liab_weight),
) = (
self.same_asset_leverage,
self.same_asset_invalid,
self.shared_mint,
self.shared_oracle_key,
self.shared_feed_family,
self.lowest_liab_weight,
) {
reconciled.same_asset.mint = mint;
reconciled.same_asset.oracle_key = oracle_key;
reconciled.same_asset.feed_family = Some(feed_family);
reconciled.same_asset.asset_weight =
compute_same_asset_emode_weight(leverage, liab_weight);
}
reconciled
}
}
impl<'a, 'info> Iterator for EmodeConfigIterator<'a, 'info> {
type Item = EmodeConfig;
fn next(&mut self) -> Option<Self::Item> {
while self.balance_index < self.lending_account.balances.len() {
let balance = &self.lending_account.balances[self.balance_index];
if !balance.is_active() {
self.balance_index += 1;
continue;
}
let bank_ai = self.remaining_ais.get(self.account_index)?;
let bank_al = AccountLoader::<Bank>::try_from(bank_ai).ok()?;
let bank = bank_al.load().ok()?;
if balance.bank_pk != *bank_ai.key {
return None;
}
let num_accounts = if self.banks_only {
1
} else {
get_remaining_accounts_per_bank(&bank).ok()?
};
self.account_index += num_accounts;
self.balance_index += 1;
if !balance.is_empty(BalanceSide::Liabilities) {
if self.same_asset_leverage.is_some() && !self.same_asset_invalid {
let liab_weight = bank
.config
.get_weight(self.requirement_type, BalanceSide::Liabilities);
if !update_reconciled_same_asset_config(
&mut self.shared_mint,
&mut self.shared_oracle_key,
&mut self.shared_feed_family,
&mut self.lowest_liab_weight,
&bank,
bank.mint,
liab_weight,
) {
self.same_asset_invalid = true;
}
}
return Some(bank.emode.emode_config);
}
}
None
}
}
fn same_asset_leverage_for_requirement(
requirement_type: RequirementType,
group: &MarginfiGroup,
) -> Option<I80F48> {
let leverage = match requirement_type {
RequirementType::Initial => u32_to_basis(group.same_asset_emode_init_leverage),
RequirementType::Maintenance => u32_to_basis(group.same_asset_emode_maint_leverage),
RequirementType::Equity => return None,
};
(leverage > I80F48::ONE).then_some(leverage)
}
/// Folds one liability mint/weight into the running same-asset accumulators.
/// Returns `false` when any liability bank is ineligible, uses an integration pricing setup,
/// lacks a feed family (fixed-price, deprecated, or unset oracle setup), is missing an oracle
/// key, or diverges from a previously seen mint/oracle-key/feed-family triple. Callers must stop
/// folding on `false`.
fn update_reconciled_same_asset_config(
shared_mint: &mut Option<Pubkey>,
shared_oracle_key: &mut Option<Pubkey>,
shared_feed_family: &mut Option<OracleFeedFamily>,
lowest_liab_weight: &mut Option<I80F48>,
bank: &Bank,
mint: Pubkey,
liab_weight: I80F48,
) -> bool {
// Same-asset e-mode deliberately allows integration banks on the collateral side: their
// exchange-rate multiplier represents redemption-value risk. They must never establish the
// liability side, however, because that would make independently moving multipliers appear
// price-equivalent. Do not rely on `asset_tag` here; it is an admin-configurable field.
if !matches!(
bank.config.oracle_setup,
OracleSetup::PythPushOracle
| OracleSetup::SwitchboardPull
| OracleSetup::StakedWithPythPush
) {
*lowest_liab_weight = None;
return false;
}
let feed_family = match bank.config.oracle_setup.feed_family() {
Some(family) if bank.get_flag(BANK_SAME_ASSET_EMODE_ELIGIBLE) => family,
_ => {
*lowest_liab_weight = None;
return false;
}
};
if bank.config.oracle_keys[0] == Pubkey::default() {
*lowest_liab_weight = None;
return false;
}
let oracle_key = bank.config.oracle_keys[0];
match shared_mint {
Some(existing_mint)
if *existing_mint != mint
|| shared_oracle_key.as_ref() != Some(&oracle_key)
|| shared_feed_family.as_ref() != Some(&feed_family) =>
{
*lowest_liab_weight = None;
false
}
Some(_) => {
if lowest_liab_weight.is_none_or(|existing| liab_weight < existing) {
*lowest_liab_weight = Some(liab_weight);
}
true
}
None => {
*shared_mint = Some(mint);
*shared_oracle_key = Some(oracle_key);
*shared_feed_family = Some(feed_family);
*lowest_liab_weight = Some(liab_weight);
true
}
}
}
// -----------------------------------------------------------------------------
// Public API - Risk Engine Functions
// -----------------------------------------------------------------------------
/// Calculates account health components with heap reuse optimization.
///
/// This function processes each balance position one at a time, using heap
/// checkpoints to recycle memory between positions. This keeps peak heap
/// usage low enough to handle up to 16 positions without `requestHeapFrame`.
///
/// ## Memory Pattern
///
/// Without heap reuse: O(N) heap where N = number of positions
/// With heap reuse: O(1) heap (memory recycled per position)
///
/// ## Parameters
///
/// - `marginfi_account`: The account to calculate health for
/// - `group`: The group whose same-asset auto-emode settings apply to this account
/// - `remaining_ais`: Remaining accounts containing banks and oracles
/// - `requirement_type`: Initial, Maintenance, or Equity requirement
/// - `health_cache`: Optional cache to populate with results
///
/// ## Returns
///
/// (total_assets, total_liabilities) weighted according to requirement_type
pub fn get_health_components<'info>(
marginfi_account: &MarginfiAccount,
group: &MarginfiGroup,
remaining_ais: &'info [AccountInfo<'info>],
requirement_type: RequirementType,
health_cache: &mut Option<&mut HealthCache>,
price_mode: HealthPriceMode<'_>,
) -> MarginfiResult<(I80F48, I80F48)> {
check!(
!marginfi_account.get_flag(ACCOUNT_IN_FLASHLOAN),
MarginfiError::AccountInFlashloan
);
let (is_cached, mut liq_cache, clock) = match price_mode {
HealthPriceMode::Live { liq_cache } => (false, liq_cache, Some(Clock::get()?)),
HealthPriceMode::Cached => (true, None, None),
HealthPriceMode::Client(clock) => (false, None, Some(clock)),
};
let lending_account = &marginfi_account.lending_account;
// =========================================================================
// Phase 1: Reconcile emode configuration (incl. same-asset) with heap reuse
// =========================================================================
let same_asset_leverage = same_asset_leverage_for_requirement(requirement_type, group);
let emode_checkpoint = heap_pos();
let reconciled_emode_config = EmodeConfigIterator::new(
lending_account,
remaining_ais,
is_cached,
requirement_type,
same_asset_leverage,
)
.reconcile();
heap_restore(emode_checkpoint);
// =========================================================================
// Phase 2: Calculate health with heap reuse per position
// =========================================================================
let mut total_assets: I80F48 = I80F48::ZERO;
let mut total_liabilities: I80F48 = I80F48::ZERO;
const NO_INDEX_FOUND: usize = 255;
let mut first_err_index = NO_INDEX_FOUND;
let mut account_index = 0usize;
for (position_index, balance) in lending_account
.balances
.iter()
.filter(|b| b.is_active())
.enumerate()
{
let heap_checkpoint = heap_pos();
// Load bank
let bank_ai = remaining_ais
.get(account_index)
.ok_or(MarginfiError::InvalidBankAccount)?;
let bank_al = AccountLoader::<Bank>::try_from(bank_ai)?;
let bank = bank_al.load()?;
check_eq!(
balance.bank_pk,
*bank_ai.key,
MarginfiError::InvalidBankAccount
);
let num_accounts = if is_cached {
check!(
bank.cache.is_liquidation_price_cache_locked(),