pyra-redis 0.9.2

Shared Redis client, key builders, and common operations for Pyra services
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
//! Typed position data fetching and computation for Kamino.
//!
//! Mirrors the Drift positions module but uses Pubkey-keyed reserves
//! instead of u16 market indices.

use std::collections::HashMap;

use solana_pubkey::Pubkey;

use pyra_margin::{get_kamino_borrow_balance, get_kamino_deposit_balance};
use pyra_types::{Cache, KaminoObligation, KaminoReserve, KAMINO_FRACTION_SCALE};

use crate::{RedisClient, RedisError, RedisKey, RedisResult};

/// Extract market price (f64) from a Kamino reserve's `market_price_sf` field.
///
/// Divides by 2^60 (Kamino Fraction type).
fn market_price_from_reserve(reserve: &KaminoReserve) -> f64 {
    reserve.liquidity.market_price_sf as f64 / KAMINO_FRACTION_SCALE as f64
}

/// Convert a token balance (i128) to a signed USD value in cents using the given price and decimals.
///
/// Uses f64 floating-point arithmetic for display and caching purposes only.
/// The authoritative balance-to-USD conversion for spending decisions lives in
/// `pyra_margin::kamino::balance` / `pyra_margin::kamino::capacity`, which uses
/// checked integer arithmetic (u128/i128) to avoid rounding errors.
fn balance_to_value_cents(token_balance: i128, decimals: u32, price: f64) -> RedisResult<i64> {
    let decimals_pow = 10_f64.powi(i32::try_from(decimals).map_err(|_| RedisError::MathOverflow)?);
    let value = (token_balance as f64) / decimals_pow * price * 100.0;
    let rounded = value.round();
    if rounded.is_finite() && rounded >= i64::MIN as f64 && rounded <= i64::MAX as f64 {
        Ok(rounded as i64)
    } else {
        Err(RedisError::MathOverflow)
    }
}

// ── Data structures ──────────────────────────────────────────────────

/// Parsed Redis position data for a single vault's Kamino obligation.
pub struct VaultKaminoPositionData {
    /// The cached KaminoObligation account (includes slot information).
    pub obligation: Cache<KaminoObligation>,
    /// Kamino reserves keyed by reserve pubkey.
    pub reserves: HashMap<Pubkey, KaminoReserve>,
    /// Market prices (USD) keyed by reserve pubkey, extracted from reserve data.
    pub prices: HashMap<Pubkey, f64>,
}

/// All Kamino obligation positions with shared reserve/price data.
pub struct AllKaminoPositionsData {
    /// `(vault_address, obligation_cache)` pairs for every Kamino obligation in Redis.
    pub obligations: Vec<(Pubkey, Cache<KaminoObligation>)>,
    /// Shared reserves keyed by reserve pubkey.
    pub reserves: HashMap<Pubkey, KaminoReserve>,
    /// Market prices (USD) keyed by reserve pubkey.
    pub prices: HashMap<Pubkey, f64>,
}

// ── Fetch methods on RedisClient ─────────────────────────────────────

impl RedisClient {
    /// Fetch KaminoObligation, reserves, and prices for a vault via MGET.
    ///
    /// Builds keys as: `[obligation, reserve_0..N]` and extracts prices
    /// from `reserve.liquidity.market_price_sf`.
    ///
    /// Returns `NotFound` if the obligation key is missing.
    pub async fn fetch_vault_kamino_position_data(
        &self,
        vault_address: &Pubkey,
        lending_market: &Pubkey,
        reserve_pubkeys: &[Pubkey],
    ) -> RedisResult<VaultKaminoPositionData> {
        let obligation_key = RedisKey::kamino_obligation(vault_address, lending_market).to_string();
        let mut keys = vec![obligation_key];
        for pk in reserve_pubkeys {
            keys.push(RedisKey::kamino_reserve(pk).to_string());
        }

        let values = self.mget(&keys).await?;

        let obligation_raw = values
            .first()
            .and_then(|v| v.as_ref())
            .ok_or_else(|| RedisError::NotFound("KaminoObligation not found in Redis".into()))?;
        let obligation: Cache<KaminoObligation> = serde_json::from_str(obligation_raw)?;

        let mut reserves: HashMap<Pubkey, KaminoReserve> = HashMap::new();
        let mut prices: HashMap<Pubkey, f64> = HashMap::new();

        for (i, pk) in reserve_pubkeys.iter().enumerate() {
            if let Some(Some(raw)) =
                values.get(1usize.checked_add(i).ok_or(RedisError::MathOverflow)?)
            {
                if let Ok(cached) = serde_json::from_str::<Cache<KaminoReserve>>(raw) {
                    let price = market_price_from_reserve(&cached.account);
                    prices.insert(*pk, price);
                    reserves.insert(*pk, cached.account);
                }
            }
        }

        Ok(VaultKaminoPositionData {
            obligation,
            reserves,
            prices,
        })
    }

    /// Fetch ALL Kamino obligations from Redis via SCAN + MGET.
    ///
    /// Scans every `account:kamino:obligation:*` key and fetches all
    /// obligation data in a single MGET round-trip.
    pub async fn fetch_all_kamino_positions(
        &self,
        reserve_pubkeys: &[Pubkey],
    ) -> RedisResult<AllKaminoPositionsData> {
        // 1. Scan for all obligation keys
        let obligation_keys = self.scan_keys(&RedisKey::kamino_obligation_glob()).await?;

        let prefix_with_colon = format!("{}:", RedisKey::KAMINO_OBLIGATION_PREFIX);
        let vault_addresses: Vec<Option<Pubkey>> = obligation_keys
            .iter()
            .map(|k| {
                k.strip_prefix(prefix_with_colon.as_str())
                    .and_then(|rest| rest.split(':').next())
                    .and_then(|s| s.parse::<Pubkey>().ok())
            })
            .collect();

        // 2. Build MGET: [obligations...] [reserves...]
        let num_obligations = obligation_keys.len();
        let mut all_keys: Vec<String> = obligation_keys;

        for pk in reserve_pubkeys {
            all_keys.push(RedisKey::kamino_reserve(pk).to_string());
        }

        let values = self.mget(&all_keys).await?;

        // 3. Parse obligations
        let mut obligations: Vec<(Pubkey, Cache<KaminoObligation>)> = Vec::new();
        for (i, vault_pk) in vault_addresses.iter().enumerate() {
            if let (Some(pk), Some(Some(raw))) = (vault_pk, values.get(i)) {
                if let Ok(cached) = serde_json::from_str::<Cache<KaminoObligation>>(raw) {
                    obligations.push((*pk, cached));
                }
            }
        }

        // 4. Parse reserves and extract prices
        let mut reserves: HashMap<Pubkey, KaminoReserve> = HashMap::new();
        let mut prices: HashMap<Pubkey, f64> = HashMap::new();

        for (i, pk) in reserve_pubkeys.iter().enumerate() {
            let offset = num_obligations
                .checked_add(i)
                .ok_or(RedisError::MathOverflow)?;
            if let Some(Some(raw)) = values.get(offset) {
                if let Ok(cached) = serde_json::from_str::<Cache<KaminoReserve>>(raw) {
                    let price = market_price_from_reserve(&cached.account);
                    prices.insert(*pk, price);
                    reserves.insert(*pk, cached.account);
                }
            }
        }

        Ok(AllKaminoPositionsData {
            obligations,
            reserves,
            prices,
        })
    }
}

// ── Computation helpers ──────────────────────────────────────────────

/// Compute the signed USD-cent value for each position in a Kamino obligation.
///
/// Deposits are positive, borrows are negative.
pub fn compute_kamino_position_values(data: &VaultKaminoPositionData) -> RedisResult<Vec<i64>> {
    compute_user_kamino_position_values(&data.obligation.account, &data.reserves, &data.prices)
}

/// Compute per-asset data: `(reserve_pubkey, balance_base_units, value_cents)`.
pub fn compute_kamino_asset_data(
    data: &VaultKaminoPositionData,
) -> RedisResult<Vec<(Pubkey, i64, i64)>> {
    compute_user_kamino_asset_data(&data.obligation.account, &data.reserves, &data.prices)
}

/// Compute signed USD-cent position values for a single Kamino obligation,
/// using shared reserve and price maps.
pub fn compute_user_kamino_position_values(
    obligation: &KaminoObligation,
    reserves: &HashMap<Pubkey, KaminoReserve>,
    prices: &HashMap<Pubkey, f64>,
) -> RedisResult<Vec<i64>> {
    let mut results = 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(&price) = prices.get(&deposit.deposit_reserve) else {
            continue;
        };
        let balance = get_kamino_deposit_balance(deposit, reserve)?;
        let decimals =
            u32::try_from(reserve.liquidity.mint_decimals).map_err(|_| RedisError::MathOverflow)?;
        let cents = balance_to_value_cents(balance, decimals, price)?;
        results.push(cents);
    }

    for borrow in &obligation.borrows {
        if borrow.borrowed_amount_sf == 0 {
            continue;
        }
        let Some(reserve) = reserves.get(&borrow.borrow_reserve) else {
            continue;
        };
        let Some(&price) = prices.get(&borrow.borrow_reserve) else {
            continue;
        };
        let balance = get_kamino_borrow_balance(borrow, reserve)?;
        let decimals =
            u32::try_from(reserve.liquidity.mint_decimals).map_err(|_| RedisError::MathOverflow)?;
        let cents = balance_to_value_cents(balance, decimals, price)?;
        results.push(cents);
    }

    Ok(results)
}

/// Compute per-asset data for a single Kamino obligation using shared reserve/price maps.
///
/// Returns `(reserve_pubkey, signed_token_balance_i64, signed_value_cents)` tuples.
pub fn compute_user_kamino_asset_data(
    obligation: &KaminoObligation,
    reserves: &HashMap<Pubkey, KaminoReserve>,
    prices: &HashMap<Pubkey, f64>,
) -> RedisResult<Vec<(Pubkey, i64, i64)>> {
    let mut results = 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(&price) = prices.get(&deposit.deposit_reserve) else {
            continue;
        };
        let balance_i128 = get_kamino_deposit_balance(deposit, reserve)?;
        let balance = i64::try_from(balance_i128).map_err(|_| RedisError::MathOverflow)?;
        let decimals =
            u32::try_from(reserve.liquidity.mint_decimals).map_err(|_| RedisError::MathOverflow)?;
        let cents = balance_to_value_cents(balance_i128, decimals, price)?;
        results.push((deposit.deposit_reserve, balance, cents));
    }

    for borrow in &obligation.borrows {
        if borrow.borrowed_amount_sf == 0 {
            continue;
        }
        let Some(reserve) = reserves.get(&borrow.borrow_reserve) else {
            continue;
        };
        let Some(&price) = prices.get(&borrow.borrow_reserve) else {
            continue;
        };
        let balance_i128 = get_kamino_borrow_balance(borrow, reserve)?;
        let balance = i64::try_from(balance_i128).map_err(|_| RedisError::MathOverflow)?;
        let decimals =
            u32::try_from(reserve.liquidity.mint_decimals).map_err(|_| RedisError::MathOverflow)?;
        let cents = balance_to_value_cents(balance_i128, decimals, price)?;
        results.push((borrow.borrow_reserve, balance, cents));
    }

    Ok(results)
}

#[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, KaminoBorrowRateCurve, KaminoCurvePoint,
        KaminoObligationCollateral, KaminoObligationLiquidity, KaminoReserveCollateral,
        KaminoReserveConfig, KaminoReserveFees, KaminoReserveLiquidity, KaminoWithdrawalCaps,
    };
    fn test_pubkey(seed: u8) -> Pubkey {
        Pubkey::new_from_array([seed; 32])
    }

    const FRACTION_ONE: u128 = 1 << 60;

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

    fn make_reserve(mint_decimals: u64, market_price_sf: u128) -> KaminoReserve {
        KaminoReserve {
            liquidity: KaminoReserveLiquidity {
                total_available_amount: 1_000_000,
                cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
                mint_decimals,
                market_price_sf,
                ..Default::default()
            },
            collateral: KaminoReserveCollateral {
                mint_total_supply: 1_000_000,
                ..Default::default()
            },
            config: KaminoReserveConfig {
                loan_to_value_pct: 80,
                liquidation_threshold_pct: 85,
                protocol_take_rate_pct: 10,
                protocol_liquidation_fee_pct: 5,
                borrow_factor_pct: 100,
                deposit_limit: u64::MAX,
                borrow_limit: u64::MAX,
                fees: KaminoReserveFees {
                    origination_fee_sf: 0,
                    flash_loan_fee_sf: 0,
                },
                borrow_rate_curve: KaminoBorrowRateCurve {
                    points: [KaminoCurvePoint {
                        utilization_rate_bps: 0,
                        borrow_rate_bps: 0,
                    }; 11],
                },
                deposit_withdrawal_cap: KaminoWithdrawalCaps {
                    config_capacity: 0,
                    current_total: 0,
                    last_interval_start_timestamp: 0,
                    config_interval_length_seconds: 0,
                },
                debt_withdrawal_cap: KaminoWithdrawalCaps {
                    config_capacity: 0,
                    current_total: 0,
                    last_interval_start_timestamp: 0,
                    config_interval_length_seconds: 0,
                },
                elevation_groups: [0; 20],
                ..Default::default()
            },
            ..Default::default()
        }
    }

    fn make_obligation(
        deposits_vec: Vec<KaminoObligationCollateral>,
        borrows_vec: Vec<KaminoObligationLiquidity>,
    ) -> KaminoObligation {
        let mut deposits = <[KaminoObligationCollateral; 8]>::default();
        for (i, d) in deposits_vec.into_iter().enumerate() {
            deposits[i] = d;
        }
        let mut borrows = <[KaminoObligationLiquidity; 5]>::default();
        for (i, b) in borrows_vec.into_iter().enumerate() {
            borrows[i] = b;
        }
        KaminoObligation {
            deposits,
            borrows,
            ..Default::default()
        }
    }

    #[test]
    fn market_price_extraction() {
        // 1.0 USD = 1 * 2^60
        let reserve = make_reserve(6, KAMINO_FRACTION_SCALE);
        let price = market_price_from_reserve(&reserve);
        assert!((price - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn market_price_extraction_150_usd() {
        // 150.0 USD = 150 * 2^60
        let price_sf = KAMINO_FRACTION_SCALE
            .checked_mul(150)
            .expect("test value fits");
        let reserve = make_reserve(9, price_sf);
        let price = market_price_from_reserve(&reserve);
        assert!((price - 150.0).abs() < 0.001);
    }

    #[test]
    fn vault_position_data_struct_construction() {
        let reserve_pk = test_pubkey(1);
        let reserve = make_reserve(6, KAMINO_FRACTION_SCALE);

        let mut reserves = HashMap::new();
        reserves.insert(reserve_pk, reserve);
        let mut prices = HashMap::new();
        prices.insert(reserve_pk, 1.0);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: reserve_pk,
            deposited_amount: 1_000_000,
            market_value_sf: KAMINO_FRACTION_SCALE,
            ..Default::default()
        };
        let obligation = make_obligation(vec![deposit], vec![]);

        let data = VaultKaminoPositionData {
            obligation: Cache {
                account: obligation,
                last_updated_slot: 12345,
            },
            reserves,
            prices,
        };

        assert_eq!(data.obligation.last_updated_slot, 12345);
        assert_eq!(data.reserves.len(), 1);
        assert_eq!(data.prices.len(), 1);
    }

    #[test]
    fn all_positions_data_struct_construction() {
        let data = AllKaminoPositionsData {
            obligations: vec![],
            reserves: HashMap::new(),
            prices: HashMap::new(),
        };
        assert!(data.obligations.is_empty());
        assert!(data.reserves.is_empty());
        assert!(data.prices.is_empty());
    }

    #[test]
    fn compute_values_empty_obligation() {
        let obligation = make_obligation(vec![], vec![]);
        let data = VaultKaminoPositionData {
            obligation: Cache {
                account: obligation,
                last_updated_slot: 0,
            },
            reserves: HashMap::new(),
            prices: HashMap::new(),
        };
        let values = compute_kamino_position_values(&data).unwrap();
        assert!(values.is_empty());
    }

    #[test]
    fn compute_values_single_deposit() {
        let reserve_pk = test_pubkey(1);
        // 1:1 exchange rate, 6 decimals, $1.00
        let reserve = make_reserve(6, KAMINO_FRACTION_SCALE);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: reserve_pk,
            deposited_amount: 1_000_000, // 1 token
            market_value_sf: 0,
            ..Default::default()
        };
        let obligation = make_obligation(vec![deposit], vec![]);

        let mut reserves = HashMap::new();
        reserves.insert(reserve_pk, reserve);
        let mut prices = HashMap::new();
        prices.insert(reserve_pk, 1.0);

        let values = compute_user_kamino_position_values(&obligation, &reserves, &prices).unwrap();
        assert_eq!(values.len(), 1);
        assert_eq!(values[0], 100); // 1 token * $1.00 = 100 cents
    }

    #[test]
    fn compute_values_deposit_and_borrow() {
        let deposit_pk = test_pubkey(1);
        let borrow_pk = test_pubkey(2);

        let deposit_reserve = make_reserve(6, KAMINO_FRACTION_SCALE);
        let borrow_reserve = make_reserve(6, KAMINO_FRACTION_SCALE);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: deposit_pk,
            deposited_amount: 2_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        let borrow = KaminoObligationLiquidity {
            borrow_reserve: borrow_pk,
            cumulative_borrow_rate_bsf: rate_to_bsf(FRACTION_ONE),
            borrowed_amount_sf: 500_000 * FRACTION_ONE,
            market_value_sf: 0,
            borrow_factor_adjusted_market_value_sf: 0,
            ..Default::default()
        };
        let obligation = make_obligation(vec![deposit], vec![borrow]);

        let mut reserves = HashMap::new();
        reserves.insert(deposit_pk, deposit_reserve);
        reserves.insert(borrow_pk, borrow_reserve);
        let mut prices = HashMap::new();
        prices.insert(deposit_pk, 1.0);
        prices.insert(borrow_pk, 1.0);

        let values = compute_user_kamino_position_values(&obligation, &reserves, &prices).unwrap();
        assert_eq!(values.len(), 2);
        assert_eq!(values[0], 200); // 2 tokens deposited = 200 cents
        assert_eq!(values[1], -50); // 0.5 tokens borrowed = -50 cents
    }

    #[test]
    fn compute_values_skips_zero_deposit() {
        let reserve_pk = test_pubkey(1);
        let reserve = make_reserve(6, KAMINO_FRACTION_SCALE);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: reserve_pk,
            deposited_amount: 0,
            market_value_sf: 0,
            ..Default::default()
        };
        let obligation = make_obligation(vec![deposit], vec![]);

        let mut reserves = HashMap::new();
        reserves.insert(reserve_pk, reserve);
        let mut prices = HashMap::new();
        prices.insert(reserve_pk, 1.0);

        let values = compute_user_kamino_position_values(&obligation, &reserves, &prices).unwrap();
        assert!(values.is_empty());
    }

    #[test]
    fn compute_values_skips_missing_reserve() {
        let reserve_pk = test_pubkey(1);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: reserve_pk,
            deposited_amount: 1_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        let obligation = make_obligation(vec![deposit], vec![]);

        let reserves = HashMap::new();
        let mut prices = HashMap::new();
        prices.insert(reserve_pk, 1.0);

        let values = compute_user_kamino_position_values(&obligation, &reserves, &prices).unwrap();
        assert!(values.is_empty());
    }

    #[test]
    fn compute_values_skips_missing_price() {
        let reserve_pk = test_pubkey(1);
        let reserve = make_reserve(6, KAMINO_FRACTION_SCALE);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: reserve_pk,
            deposited_amount: 1_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        let obligation = make_obligation(vec![deposit], vec![]);

        let mut reserves = HashMap::new();
        reserves.insert(reserve_pk, reserve);
        let prices = HashMap::new();

        let values = compute_user_kamino_position_values(&obligation, &reserves, &prices).unwrap();
        assert!(values.is_empty());
    }

    #[test]
    fn compute_values_high_price_sol() {
        let reserve_pk = test_pubkey(1);
        // SOL: 9 decimals, $150
        let price_sf = KAMINO_FRACTION_SCALE.checked_mul(150).unwrap();
        let reserve = make_reserve(9, price_sf);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: reserve_pk,
            deposited_amount: 100_000_000, // 0.1 SOL
            market_value_sf: 0,
            ..Default::default()
        };
        let obligation = make_obligation(vec![deposit], vec![]);

        let mut reserves = HashMap::new();
        reserves.insert(reserve_pk, reserve);
        let mut prices = HashMap::new();
        prices.insert(reserve_pk, 150.0);

        let values = compute_user_kamino_position_values(&obligation, &reserves, &prices).unwrap();
        assert_eq!(values.len(), 1);
        assert_eq!(values[0], 1500); // 0.1 SOL * $150 = $15 = 1500 cents
    }

    #[test]
    fn compute_asset_data_returns_tuples() {
        let reserve_pk = test_pubkey(1);
        let reserve = make_reserve(6, KAMINO_FRACTION_SCALE);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: reserve_pk,
            deposited_amount: 5_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        let obligation = make_obligation(vec![deposit], vec![]);

        let mut reserves = HashMap::new();
        reserves.insert(reserve_pk, reserve);
        let mut prices = HashMap::new();
        prices.insert(reserve_pk, 1.0);

        let data = compute_user_kamino_asset_data(&obligation, &reserves, &prices).unwrap();
        assert_eq!(data.len(), 1);
        let (pk, token_balance, value_cents) = data[0];
        assert_eq!(pk, reserve_pk);
        assert_eq!(token_balance, 5_000_000);
        assert_eq!(value_cents, 500); // 5 USDC = 500 cents
    }

    #[test]
    fn compute_position_values_delegates_to_user_variant() {
        let reserve_pk = test_pubkey(1);
        let reserve = make_reserve(6, KAMINO_FRACTION_SCALE);

        let deposit = KaminoObligationCollateral {
            deposit_reserve: reserve_pk,
            deposited_amount: 1_000_000,
            market_value_sf: 0,
            ..Default::default()
        };
        let obligation = Cache {
            account: make_obligation(vec![deposit], vec![]),
            last_updated_slot: 12345,
        };

        let mut reserves = HashMap::new();
        reserves.insert(reserve_pk, reserve);
        let mut prices = HashMap::new();
        prices.insert(reserve_pk, 1.0);

        let vpd = VaultKaminoPositionData {
            obligation,
            reserves,
            prices,
        };
        let values = compute_kamino_position_values(&vpd).unwrap();
        assert_eq!(values.len(), 1);
        assert_eq!(values[0], 100);
    }
}