pyra-margin 0.9.3

Margin weight, balance, and price calculations for Drift spot positions
Documentation
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
use std::collections::HashMap;

use pyra_tokens::{AssetId, Token};
use pyra_types::{KaminoObligation, KaminoReserve};
use solana_pubkey::Pubkey;

use super::balance::{get_kamino_borrow_balance, get_kamino_deposit_balance};
use super::weights::{get_kamino_asset_weight, get_kamino_liability_weight, get_kamino_price};
use crate::common::usdc_base_units_to_cents;
use crate::drift::balance::calculate_value_usdc_base_units;
use crate::error::{MathError, MathResult};

const MARGIN_PRECISION: i128 = 10_000;

/// Position type for Kamino capacity breakdown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KaminoPositionType {
    Deposit,
    Borrow,
}

/// Per-position info emitted during capacity calculation.
///
/// Matches Drift's `PositionInfo` structure for downstream consistency.
#[derive(Debug, Clone, PartialEq)]
pub struct KaminoPositionInfo {
    /// Pyra asset ID (from `pyra_tokens`). Use `asset_id.token()` for
    /// reserve address, mint, decimals, etc.
    pub asset_id: AssetId,
    /// Unsigned token balance in base units.
    pub balance: u64,
    pub position_type: KaminoPositionType,
    /// Oracle price in USDC base units (PRICE_PRECISION = 1e6).
    pub price_usdc_base_units: u64,
    /// Asset weight in basis points (10_000 = 100%).
    pub weight_bps: u32,
}

/// Result of Kamino capacity calculation.
///
/// Matches Drift's `CapacityResult` interface.
#[derive(Debug, Clone)]
pub struct KaminoCapacityResult {
    /// Raw net worth (unweighted collateral - unweighted liabilities), in cents.
    ///
    /// This is measured before applying any liquidation slippage buffer.
    pub net_worth_cents: u64,
    /// Max spendable via liquidating spend (unweighted collateral - slippage - liabilities), in cents.
    pub total_spendable_cents: u64,
    /// Available credit line (LTV-weighted collateral - borrow-factor-adjusted liabilities), in cents.
    pub available_credit_cents: u64,
    /// USDC balance in cents (identified by `usdc_mint`).
    pub usdc_balance_cents: u64,
    /// Borrow headroom remaining after all USDC collateral is withdrawn.
    /// Equals `available_credit_cents - (usdc_balance_cents × usdc_reserve.loan_to_value_pct / 100)`,
    /// saturating at zero. Used to size the `borrow_amount` portion of a Kamino
    /// withdraw+borrow instruction after USDC is fully drained.
    ///
    /// Assumes a single USDC deposit per obligation: only the first USDC reserve
    /// encountered in `obligation.deposits` is subtracted, matching the
    /// single-reserve convention of `usdc_balance_cents`. An obligation holding
    /// USDC across multiple reserves (e.g. a main-market and an isolated-market
    /// USDC deposit on the same obligation) would have the headroom
    /// overestimated. Kamino's isolated markets today use separate obligations,
    /// so this is not expected in practice.
    pub borrow_headroom_after_usdc_cents: u64,
    /// Max spendable without entering the liquidating route, in cents.
    ///
    /// This is the direct USDC balance plus post-USDC borrow headroom, capped by
    /// raw net worth so credit spend classification cannot exceed the user's
    /// unweighted assets minus loans.
    pub credit_spendable_cents: u64,
    /// Total weighted collateral in USDC base units (LTV-weighted).
    pub weighted_collateral_usdc_base_units: u64,
    /// Total weighted liabilities in USDC base units (borrow-factor-adjusted).
    pub weighted_liabilities_usdc_base_units: u64,
    /// Per-position breakdown for downstream use.
    pub position_infos: Vec<KaminoPositionInfo>,
}

/// Card spend route selected from Kamino capacity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpendRoute {
    Debit,
    Credit,
    Liquidating,
    Insufficient,
}

pub fn classify_card_spend(amount_cents: u64, capacity: &KaminoCapacityResult) -> SpendRoute {
    let debit_spendable_cents =
        std::cmp::min(capacity.usdc_balance_cents, capacity.credit_spendable_cents);

    if amount_cents <= debit_spendable_cents {
        SpendRoute::Debit
    } else if amount_cents <= capacity.credit_spendable_cents {
        SpendRoute::Credit
    } else if amount_cents <= capacity.total_spendable_cents {
        SpendRoute::Liquidating
    } else {
        SpendRoute::Insufficient
    }
}

/// Calculate Kamino spending capacity from an obligation and reserve data.
///
/// Matches Drift's `calculate_capacity` interface:
/// - **net_worth_cents**: raw net worth before slippage (unweighted collateral - unweighted liabilities)
/// - **total_spendable_cents**: max amount for liquidating spends (collateral - slippage - liabilities)
/// - **available_credit_cents**: credit line (LTV-weighted collateral - borrow-factor-adjusted liabilities)
/// - **usdc_balance_cents**: direct USDC holdings
/// - **credit_spendable_cents**: max non-liquidating spend after applying the net-worth cap
///
/// Reserves are looked up by pubkey in the `reserves` map. Positions whose
/// reserve is missing from the map are skipped. Positions whose reserve has
/// no matching `pyra_tokens` entry are also skipped.
pub fn calculate_kamino_capacity(
    obligation: &KaminoObligation,
    reserves: &HashMap<Pubkey, KaminoReserve>,
    max_slippage_bps: u64,
) -> MathResult<KaminoCapacityResult> {
    // Elevation group support not implemented. When elevation_group > 0,
    // LTV/liquidation_threshold come from the elevation group config (not
    // reserve.config) and borrow_factor becomes 1.0. Fail loudly rather
    // than silently computing wrong values.
    if obligation.elevation_group != 0 {
        return Err(MathError::Overflow);
    }

    let mut total_collateral_usdc_base_units: u64 = 0;
    let mut total_liabilities_usdc_base_units: u64 = 0;
    let mut total_weighted_collateral: u64 = 0;
    let mut total_weighted_liabilities: u64 = 0;
    let mut usdc_balance_base_units: u64 = 0;
    let mut usdc_ltv_pct: u8 = 0;
    let mut position_infos: Vec<KaminoPositionInfo> = Vec::new();

    for deposit in &obligation.deposits {
        if deposit.deposited_amount == 0 {
            continue;
        }
        let Some(reserve) = reserves.get(&deposit.deposit_reserve) else {
            continue;
        };
        let Some(token) = Token::find_by_kamino_reserve(&deposit.deposit_reserve) else {
            continue;
        };
        let asset_id = token.asset_id;

        let balance = get_kamino_deposit_balance(deposit, reserve)?;
        let price = get_kamino_price(reserve)?;
        let price_u64 = u64::try_from(price).map_err(|_| MathError::Overflow)?;
        let decimals =
            u32::try_from(reserve.liquidity.mint_decimals).map_err(|_| MathError::Overflow)?;
        let value = calculate_value_usdc_base_units(balance, price_u64, decimals)?;
        let value_u64 = u64::try_from(value).map_err(|_| MathError::Overflow)?;

        // Accumulate unweighted collateral
        total_collateral_usdc_base_units = total_collateral_usdc_base_units
            .checked_add(value_u64)
            .ok_or(MathError::Overflow)?;

        // LTV-weighted value
        let asset_weight = get_kamino_asset_weight(reserve) as i128;
        let weighted = value
            .checked_mul(asset_weight)
            .ok_or(MathError::Overflow)?
            .checked_div(MARGIN_PRECISION)
            .ok_or(MathError::Overflow)?;
        let weighted_u64 = u64::try_from(weighted).map_err(|_| MathError::Overflow)?;
        total_weighted_collateral = total_weighted_collateral
            .checked_add(weighted_u64)
            .ok_or(MathError::Overflow)?;

        // Track USDC balance and LTV (used for borrow-headroom-after-USDC calculation)
        if token.mint == pyra_tokens::USDC.mint && usdc_balance_base_units == 0 {
            let balance_u64 = u64::try_from(balance).map_err(|_| MathError::Overflow)?;
            usdc_balance_base_units = balance_u64;
            usdc_ltv_pct = reserve.config.loan_to_value_pct;
        }

        // Store position info
        let balance_u64 = u64::try_from(balance.unsigned_abs()).map_err(|_| MathError::Overflow)?;
        let weight_bps =
            u32::try_from(get_kamino_asset_weight(reserve)).map_err(|_| MathError::Overflow)?;
        position_infos.push(KaminoPositionInfo {
            asset_id,
            balance: balance_u64,
            position_type: KaminoPositionType::Deposit,
            price_usdc_base_units: price_u64,
            weight_bps,
        });
    }

    for borrow in &obligation.borrows {
        if borrow.borrowed_amount_sf == 0 {
            continue;
        }
        let Some(reserve) = reserves.get(&borrow.borrow_reserve) else {
            continue;
        };
        let Some(token) = Token::find_by_kamino_reserve(&borrow.borrow_reserve) else {
            continue;
        };
        let asset_id = token.asset_id;

        let balance = get_kamino_borrow_balance(borrow, reserve)?;
        let price = get_kamino_price(reserve)?;
        let price_u64 = u64::try_from(price).map_err(|_| MathError::Overflow)?;
        let decimals =
            u32::try_from(reserve.liquidity.mint_decimals).map_err(|_| MathError::Overflow)?;
        let value = calculate_value_usdc_base_units(balance, price_u64, decimals)?;

        // value is negative (borrow convention), negate to get positive
        let raw_borrow = value.checked_neg().ok_or(MathError::Overflow)?;
        let raw_borrow_u64 = u64::try_from(raw_borrow).map_err(|_| MathError::Overflow)?;
        total_liabilities_usdc_base_units = total_liabilities_usdc_base_units
            .checked_add(raw_borrow_u64)
            .ok_or(MathError::Overflow)?;

        // Apply borrow factor: max(1.0, borrow_factor_pct/100)
        let borrow_factor = i128::from(std::cmp::max(100u64, reserve.config.borrow_factor_pct));
        let adjusted_borrow = raw_borrow
            .checked_mul(borrow_factor)
            .ok_or(MathError::Overflow)?
            .checked_div(100)
            .ok_or(MathError::Overflow)?;
        let adjusted_u64 = u64::try_from(adjusted_borrow).map_err(|_| MathError::Overflow)?;
        total_weighted_liabilities = total_weighted_liabilities
            .checked_add(adjusted_u64)
            .ok_or(MathError::Overflow)?;

        // Store position info
        let balance_u64 = u64::try_from(balance.unsigned_abs()).map_err(|_| MathError::Overflow)?;
        let weight_bps = u32::try_from(get_kamino_liability_weight(reserve)?)
            .map_err(|_| MathError::Overflow)?;
        position_infos.push(KaminoPositionInfo {
            asset_id,
            balance: balance_u64,
            position_type: KaminoPositionType::Borrow,
            price_usdc_base_units: price_u64,
            weight_bps,
        });
    }

    // Available credit = weighted collateral - weighted liabilities
    let available_credit_base_units =
        total_weighted_collateral.saturating_sub(total_weighted_liabilities);
    let available_credit_cents = usdc_base_units_to_cents(available_credit_base_units)?;

    // Raw net worth = collateral - liabilities, before liquidation slippage.
    let net_worth_base_units =
        total_collateral_usdc_base_units.saturating_sub(total_liabilities_usdc_base_units);
    let net_worth_cents = usdc_base_units_to_cents(net_worth_base_units)?;

    // Total spendable = collateral - slippage - liabilities (for liquidating spends)
    let max_slippage_usdc_base_units = total_collateral_usdc_base_units
        .checked_mul(max_slippage_bps)
        .ok_or(MathError::Overflow)?
        .checked_div(10_000)
        .ok_or(MathError::Overflow)?;
    let total_spendable_base_units = total_collateral_usdc_base_units
        .saturating_sub(max_slippage_usdc_base_units)
        .saturating_sub(total_liabilities_usdc_base_units);
    let total_spendable_cents = usdc_base_units_to_cents(total_spendable_base_units)?;

    let usdc_balance_cents = usdc_base_units_to_cents(usdc_balance_base_units)?;

    // Borrow headroom remaining after USDC is fully withdrawn: subtract the
    // LTV-weighted contribution USDC was making to available credit.
    // When no USDC is deposited, `usdc_balance_cents` is 0 and the subtraction
    // is a no-op, leaving headroom equal to `available_credit_cents`.
    let usdc_ltv_contribution_cents = usdc_balance_cents
        .checked_mul(u64::from(usdc_ltv_pct))
        .ok_or(MathError::Overflow)?
        .checked_div(100)
        .ok_or(MathError::Overflow)?;
    let borrow_headroom_after_usdc_cents =
        available_credit_cents.saturating_sub(usdc_ltv_contribution_cents);
    let credit_spendable_before_net_worth_cap = usdc_balance_cents
        .checked_add(borrow_headroom_after_usdc_cents)
        .ok_or(MathError::Overflow)?;
    let credit_spendable_cents =
        std::cmp::min(credit_spendable_before_net_worth_cap, net_worth_cents);

    Ok(KaminoCapacityResult {
        net_worth_cents,
        total_spendable_cents,
        available_credit_cents,
        usdc_balance_cents,
        borrow_headroom_after_usdc_cents,
        credit_spendable_cents,
        weighted_collateral_usdc_base_units: total_weighted_collateral,
        weighted_liabilities_usdc_base_units: total_weighted_liabilities,
        position_infos,
    })
}

#[cfg(test)]
#[allow(
    clippy::allow_attributes,
    clippy::allow_attributes_without_reason,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::arithmetic_side_effects
)]
mod tests {
    use super::*;
    use pyra_types::{
        KaminoBigFractionBytes, KaminoLastUpdate, KaminoObligationCollateral,
        KaminoObligationLiquidity, KaminoReserveCollateral, KaminoReserveConfig,
        KaminoReserveLiquidity,
    };

    const FRACTION_ONE: u128 = 1 << 60;

    /// Real USDC kamino reserve address from pyra_tokens.
    fn usdc_reserve_key() -> Pubkey {
        pyra_tokens::USDC.kamino_reserve.unwrap()
    }

    fn rate_to_bsf(rate: u128) -> KaminoBigFractionBytes {
        KaminoBigFractionBytes {
            value: [rate as u64, (rate >> 64) as u64, 0, 0],
        }
    }

    fn make_usdc_reserve(
        ltv: u8,
        liq_threshold: u8,
        total_available: u64,
        collateral_supply: u64,
    ) -> KaminoReserve {
        let price_sf = 1u128 << 60; // $1
        KaminoReserve {
            lending_market: Pubkey::default(),
            liquidity: KaminoReserveLiquidity {
                mint_pubkey: pyra_tokens::USDC.mint,
                supply_vault: Pubkey::default(),
                fee_vault: Pubkey::default(),
                total_available_amount: total_available,
                borrowed_amount_sf: 0,
                cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
                mint_decimals: 6,
                market_price_sf: price_sf,
                accumulated_protocol_fees_sf: 0,
                accumulated_referrer_fees_sf: 0,
                pending_referrer_fees_sf: 0,
                token_program: Pubkey::default(),
                ..Default::default()
            },
            collateral: KaminoReserveCollateral {
                mint_pubkey: Pubkey::default(),
                supply_vault: Pubkey::default(),
                mint_total_supply: collateral_supply,
            },
            config: KaminoReserveConfig {
                loan_to_value_pct: ltv,
                liquidation_threshold_pct: liq_threshold,
                protocol_take_rate_pct: 0,
                protocol_liquidation_fee_pct: 0,
                borrow_factor_pct: 100,
                deposit_limit: 0,
                borrow_limit: 0,
                fees: Default::default(),
                borrow_rate_curve: Default::default(),
                deposit_withdrawal_cap: Default::default(),
                debt_withdrawal_cap: Default::default(),
                elevation_groups: [0; 20],
                ..Default::default()
            },
            last_update: KaminoLastUpdate::default(),
            ..Default::default()
        }
    }

    fn empty_obligation() -> KaminoObligation {
        KaminoObligation {
            lending_market: Pubkey::default(),
            owner: Pubkey::default(),
            deposits: Default::default(),
            borrows: Default::default(),
            deposited_value_sf: 0,
            borrowed_assets_market_value_sf: 0,
            allowed_borrow_value_sf: 0,
            unhealthy_borrow_value_sf: 0,
            has_debt: 0,
            elevation_group: 0,
            last_update: KaminoLastUpdate::default(),
            ..Default::default()
        }
    }

    #[test]
    fn empty_obligation_zero_capacity() {
        let result = calculate_kamino_capacity(&empty_obligation(), &HashMap::new(), 0).unwrap();
        assert_eq!(result.net_worth_cents, 0);
        assert_eq!(result.total_spendable_cents, 0);
        assert_eq!(result.available_credit_cents, 0);
        assert_eq!(result.usdc_balance_cents, 0);
        assert_eq!(result.credit_spendable_cents, 0);
        assert_eq!(result.weighted_collateral_usdc_base_units, 0);
        assert_eq!(result.weighted_liabilities_usdc_base_units, 0);
        assert!(result.position_infos.is_empty());
    }

    #[test]
    fn single_usdc_deposit() {
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000, // 100 USDC
            market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        assert_eq!(result.net_worth_cents, 10_000);
        assert_eq!(result.total_spendable_cents, 10_000);
        assert_eq!(result.available_credit_cents, 10_000);
        assert_eq!(result.usdc_balance_cents, 10_000);
        assert_eq!(result.credit_spendable_cents, 10_000);
        assert_eq!(result.weighted_collateral_usdc_base_units, 100_000_000);
        assert_eq!(result.weighted_liabilities_usdc_base_units, 0);
        assert_eq!(result.position_infos.len(), 1);
        assert_eq!(
            result.position_infos[0].asset_id,
            pyra_tokens::USDC.asset_id
        );
        assert_eq!(
            result.position_infos[0].position_type,
            KaminoPositionType::Deposit
        );
    }

    #[test]
    fn deposit_and_borrow() {
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        obligation.borrows[0] = KaminoObligationLiquidity {
            borrow_reserve: key,
            cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
            borrowed_amount_sf: 50_000_000u128 * FRACTION_ONE,
            market_value_sf: 0,
            borrow_factor_adjusted_market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        assert_eq!(result.net_worth_cents, 5_000);
        assert_eq!(result.total_spendable_cents, 5_000);
        assert_eq!(result.available_credit_cents, 5_000);
        assert_eq!(result.usdc_balance_cents, 10_000);
        assert_eq!(result.credit_spendable_cents, 5_000);
        assert_eq!(result.position_infos.len(), 2);
    }

    #[test]
    fn ltv_weight_applied() {
        let key = usdc_reserve_key();
        // 80% LTV — weighted collateral should be 80% of unweighted
        let reserve = make_usdc_reserve(80, 85, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000, // 100 USDC
            market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        // Unweighted = $100 = 10_000 cents
        assert_eq!(result.total_spendable_cents, 10_000);
        // LTV-weighted = $80 = 8_000 cents
        assert_eq!(result.available_credit_cents, 8_000);
        assert_eq!(result.weighted_collateral_usdc_base_units, 80_000_000);
        assert_eq!(result.position_infos[0].weight_bps, 8_000);
    }

    #[test]
    fn at_limit_spendable_zero() {
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        obligation.borrows[0] = KaminoObligationLiquidity {
            borrow_reserve: key,
            cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
            borrowed_amount_sf: 100_000_000u128 * FRACTION_ONE,
            market_value_sf: 0,
            borrow_factor_adjusted_market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        assert_eq!(result.total_spendable_cents, 0);
        assert_eq!(result.available_credit_cents, 0);
    }

    #[test]
    fn borrow_factor_increases_effective_borrow() {
        let key = usdc_reserve_key();
        let mut reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        reserve.config.borrow_factor_pct = 150;
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        obligation.borrows[0] = KaminoObligationLiquidity {
            borrow_reserve: key,
            cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
            borrowed_amount_sf: 50_000_000u128 * FRACTION_ONE,
            market_value_sf: 0,
            borrow_factor_adjusted_market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        assert_eq!(result.total_spendable_cents, 5_000);
        assert_eq!(result.available_credit_cents, 2_500);
        assert_eq!(result.weighted_liabilities_usdc_base_units, 75_000_000);
    }

    #[test]
    fn slippage_reduces_spendable() {
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 1_000).unwrap();
        assert_eq!(result.net_worth_cents, 10_000);
        assert_eq!(result.total_spendable_cents, 9_000);
        assert_eq!(result.available_credit_cents, 10_000);
    }

    #[test]
    fn net_worth_is_before_liquidation_slippage() {
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        obligation.borrows[0] = KaminoObligationLiquidity {
            borrow_reserve: key,
            cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
            borrowed_amount_sf: 50_000_000u128 * FRACTION_ONE,
            market_value_sf: 0,
            borrow_factor_adjusted_market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 1_000).unwrap();

        assert_eq!(result.net_worth_cents, 5_000);
        assert_eq!(result.total_spendable_cents, 4_000);
    }

    #[test]
    fn credit_spendable_is_capped_by_net_worth() {
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        obligation.borrows[0] = KaminoObligationLiquidity {
            borrow_reserve: key,
            cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
            borrowed_amount_sf: 90_000_000u128 * FRACTION_ONE,
            market_value_sf: 0,
            borrow_factor_adjusted_market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();

        assert_eq!(result.usdc_balance_cents, 10_000);
        assert_eq!(result.borrow_headroom_after_usdc_cents, 0);
        assert_eq!(result.net_worth_cents, 1_000);
        assert_eq!(result.credit_spendable_cents, 1_000);
        assert_eq!(result.total_spendable_cents, 1_000);
        assert_eq!(
            classify_card_spend(9_000, &result),
            SpendRoute::Insufficient
        );
    }

    #[test]
    fn classify_card_spend_uses_debit_credit_liquidating_order() {
        let capacity = KaminoCapacityResult {
            net_worth_cents: 12_000,
            total_spendable_cents: 11_000,
            available_credit_cents: 8_000,
            usdc_balance_cents: 2_000,
            borrow_headroom_after_usdc_cents: 6_000,
            credit_spendable_cents: 8_000,
            weighted_collateral_usdc_base_units: 0,
            weighted_liabilities_usdc_base_units: 0,
            position_infos: Vec::new(),
        };

        assert_eq!(classify_card_spend(2_000, &capacity), SpendRoute::Debit);
        assert_eq!(classify_card_spend(8_000, &capacity), SpendRoute::Credit);
        assert_eq!(
            classify_card_spend(11_000, &capacity),
            SpendRoute::Liquidating
        );
        assert_eq!(
            classify_card_spend(11_001, &capacity),
            SpendRoute::Insufficient
        );
    }

    #[test]
    fn elevation_group_nonzero_errors() {
        let mut obligation = empty_obligation();
        obligation.elevation_group = 1;
        assert!(calculate_kamino_capacity(&obligation, &HashMap::new(), 0).is_err());
    }

    #[test]
    fn missing_reserve_skipped() {
        let unknown_key = Pubkey::new_unique();
        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: unknown_key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &HashMap::new(), 0).unwrap();
        assert_eq!(result.total_spendable_cents, 0);
        assert!(result.position_infos.is_empty());
    }

    #[test]
    fn unknown_token_reserve_skipped() {
        // Reserve exists in HashMap but has no matching pyra_tokens entry
        let unknown_key = Pubkey::new_unique();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(unknown_key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: unknown_key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        assert_eq!(result.total_spendable_cents, 0);
        assert!(result.position_infos.is_empty());
    }

    #[test]
    fn borrow_headroom_usdc_on_zero_ltv_reserve() {
        // USDC deposited into an isolated reserve with LTV=0 (xStocks pattern).
        // available_credit_cents is 0 (no LTV weight) and the headroom must
        // also be 0 — nothing left to borrow once USDC is drained.
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(0, 0, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000, // 100 USDC
            market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        assert_eq!(result.usdc_balance_cents, 10_000);
        assert_eq!(result.available_credit_cents, 0);
        assert_eq!(result.borrow_headroom_after_usdc_cents, 0);
    }

    #[test]
    fn borrow_headroom_usdc_only_full_ltv() {
        // USDC-only wallet on a 100% LTV reserve: available credit equals the
        // USDC contribution, so the post-USDC-withdrawal headroom is 0.
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        assert_eq!(result.usdc_balance_cents, 10_000);
        assert_eq!(result.available_credit_cents, 10_000);
        // 10_000 - (10_000 * 100 / 100) = 0
        assert_eq!(result.borrow_headroom_after_usdc_cents, 0);
    }

    #[test]
    fn borrow_headroom_no_usdc_equals_available_credit() {
        // No USDC deposit: headroom should equal available_credit_cents.
        let result = calculate_kamino_capacity(&empty_obligation(), &HashMap::new(), 0).unwrap();
        assert_eq!(result.usdc_balance_cents, 0);
        assert_eq!(result.available_credit_cents, 0);
        assert_eq!(result.borrow_headroom_after_usdc_cents, 0);
    }

    #[test]
    fn position_infos_correct_types() {
        let key = usdc_reserve_key();
        let reserve = make_usdc_reserve(100, 100, 10_000_000_000, 10_000_000_000);
        let reserves: HashMap<Pubkey, KaminoReserve> = [(key, reserve)].into();

        let mut obligation = empty_obligation();
        obligation.deposits[0] = KaminoObligationCollateral {
            deposit_reserve: key,
            deposited_amount: 100_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        obligation.borrows[0] = KaminoObligationLiquidity {
            borrow_reserve: key,
            cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
            borrowed_amount_sf: 30_000_000u128 * FRACTION_ONE,
            market_value_sf: 0,
            borrow_factor_adjusted_market_value_sf: 0,
            ..Default::default()
        };

        let result = calculate_kamino_capacity(&obligation, &reserves, 0).unwrap();
        assert_eq!(result.position_infos.len(), 2);
        assert_eq!(
            result.position_infos[0].asset_id,
            pyra_tokens::USDC.asset_id
        );
        assert_eq!(
            result.position_infos[0].position_type,
            KaminoPositionType::Deposit
        );
        assert_eq!(result.position_infos[0].balance, 100_000_000);
        assert_eq!(result.position_infos[0].weight_bps, 10_000);
        assert_eq!(
            result.position_infos[1].asset_id,
            pyra_tokens::USDC.asset_id
        );
        assert_eq!(
            result.position_infos[1].position_type,
            KaminoPositionType::Borrow
        );
        assert_eq!(result.position_infos[1].balance, 30_000_000);
        assert_eq!(result.position_infos[1].weight_bps, 10_000);
    }
}