usdc-plus-exchange 0.1.8

USDC <-> USDC+ exchange library for the Reflect protocol.
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
use anchor_lang::prelude::*;
use crate::errors::ReflectErrorCodes;
use crate::reflect::{AutoCompound, deserialise_autocompound};
use crate::spl_mint::get_mint_supply;
use crate::drift::get_usdc_amount_drift_data;
use crate::ids;
use solana_program::pubkey::Pubkey as Pubkey;

// deposited_vault_value = What the vault OWES to users (liability side)
// last_pool_value = What's ACTUALLY in Drift after extraction (asset side)

/// Computes how much USDC would be returned for a given amount of receipt tokens
/// Formula: USDC = token_amount * deposited_vault_value / effective_supply
pub fn compute_usdc_from_tokens(
    token_amount: u64,
    deposited_vault_value: u64,
    effective_supply: u64,
) -> Result<u64> {
    if effective_supply == 0 {
        return Err(ReflectErrorCodes::MathError.into());
    }
    
    // Use u128 to prevent overflow during multiplication.
    let numerator = (token_amount as u128) * (deposited_vault_value as u128);
    let result = numerator / (effective_supply as u128);
    
    // Check if result fits in u64.
    if result > u64::MAX as u128 {
        return Err(ReflectErrorCodes::MathError.into());
    }    
    Ok(result as u64)
}

/// Computes how many receipt tokens would be minted for a given USDC deposit amount
/// Formula: tokens = usdc_amount * effective_supply / deposited_vault_value
pub fn compute_tokens_from_usdc(
    usdc_amount: u64,
    deposited_vault_value: u64,
    effective_supply: u64,
) -> Result<u64> {
    // First deposit gets 1:1 ratio.
    if effective_supply == 0 || deposited_vault_value == 0 {
        return Ok(usdc_amount);
    }
    
    // Existing formula for subsequent deposits.
    let numerator = (usdc_amount as u128) * (effective_supply as u128);
    let result = numerator / (deposited_vault_value as u128);
    
    if result > u64::MAX as u128 {
        return Err(ReflectErrorCodes::MathError.into());
    }
    
    Ok(result as u64)
}

/// Calculates the amount of USDC+ receipt tokens a user will receive for depositing USDC.
/// 
/// This function provides the real-time exchange rate by incorporating the latest yield
/// from Drift protocol before calculating the token amount.
/// 
/// ## Parameters
/// - `data_usdc_controller`: Raw bytes from the USDC strategy controller account.
/// - `data_spot_market_usdc`: Raw bytes from Drift's USDC spot market account containing
///   current market state and interest rates.
/// - `data_user_account`: Raw bytes from Drift user account that holds the protocol's USDC
///   deposits and accumulated yield.
/// - `usdc_amount`: Amount of USDC to deposit, scaled by 10^6 (1 USDC = 1_000_000)
/// 
/// ## Returns
/// Amount of USDC+ tokens the user will receive (with 6 decimals places)
/// 
/// ## Process
/// 1. Extract from accounts following data:
///     - AutoCompound state from controller account
///     - Drift usdc spot market state
///     - Reflect's Drift user account state
///     - USDC+ supply
/// 2. Calculate amount of USDC at Drift
/// 3. Updates the AutoCompound state with latest Drift usdc holdings
/// 4. Calculates USDC+ tokens based on the updated exchange rate
/// 
/// ## Formula
/// tokens = usdc_amount * effective_supply / deposited_vault_value
/// 
/// ## Example
/// 
/// // Deposit 100 USDC
/// let tokens = exchange_rate_usdc_input(
///     &controller_data,
///     &spot_market_data,
///     &user_account_data,
///     69_000_000  // 69 USDC with 6 decimals
/// )?;
/// 
pub fn exchange_rate_usdc_input(    
    data_usdc_controller: &[u8],
    data_spot_market_usdc: &[u8],
    data_user_account: &[u8],
    data_usdc_plus_mint: &[u8],
    usdc_amount: u64,     
) -> Result<u64> {    

    // Get autocompound and recipients.
    let mut auto_compound: AutoCompound = deserialise_autocompound(data_usdc_controller)?;

    // Get supply of USDC+ tokens.
    let usdc_plus_supply = get_mint_supply(data_usdc_plus_mint)?;

    // Get usdc amount in drift
    let usdc_amount_drift = get_usdc_amount_drift_data(data_user_account, data_spot_market_usdc)?;
    
    // Update pool value to latest value from drift.
    auto_compound.update_pool(usdc_amount_drift, &vec![10_000], usdc_plus_supply)?;

    let deposited_vault_value: u64 = auto_compound.deposited_vault_value;
    
    compute_tokens_from_usdc(usdc_amount, deposited_vault_value, usdc_plus_supply)
}


/// Calculates USDC+ tokens for a USDC deposit using Anchor account validation.
/// 
/// This wrapper function provides account validation before calculating the exchange rate,
/// ensuring the correct Reflect protocol accounts are being used.
/// 
/// ## Parameters
/// - `usdc_controller_account`: The USDC strategy controller AccountInfo, must match `ids::usdc_controller::ID`
/// - `spot_market_usdc_account`: Drift's USDC spot market AccountInfo, must match `ids::usdc_spot_market::ID`
/// - `reflect_user_account`: Reflect's Drift user AccountInfo, must match `ids::reflect_user_account_strategy_0::ID`
/// - `usdc_amount`: Amount of USDC to deposit, scaled by 10^6 (1 USDC = 1_000_000)
/// 
/// ## Returns
/// Amount of USDC+ tokens the user will receive (with 6 decimal places)
/// 
/// ## Security
/// - Validates all account addresses match expected protocol accounts
/// - Prevents account substitution attacks
/// - Returns `InvalidAccount` error if any account doesn't match
/// 
/// ## Example
/// ```ignore
/// let tokens = exchange_rate_usdc_input_accounts(
///     &ctx.accounts.usdc_controller,
///     &ctx.accounts.spot_market,
///     &ctx.accounts.drift_user,
///     69_000_000  // 69 USDC
/// )?;
/// ```
pub fn exchange_rate_usdc_accounts(
    usdc_controller_account: &AccountInfo,
    spot_market_usdc_account: &AccountInfo,
    reflect_user_account: &AccountInfo,
    usdc_plus_mint_account: &AccountInfo,
    usdc_amount: u64,     
) -> Result<u64> { 
    require!(usdc_controller_account.key == &ids::usdc_controller::ID, ReflectErrorCodes::InvalidUsdcControllerAccount);
    require!(spot_market_usdc_account.key == &ids::usdc_spot_market::ID, ReflectErrorCodes::InvalidUsdcSpotMarketAccount);
    require!(reflect_user_account.key == &ids::reflect_user_account_strategy_0::ID, ReflectErrorCodes::InvalidReflectUserAccount);
    exchange_rate_usdc_input(    
        &usdc_controller_account.data.borrow(),
        &spot_market_usdc_account.data.borrow(),
        &reflect_user_account.data.borrow(),
        &usdc_plus_mint_account.data.borrow(),
        usdc_amount,     
    )
}


/// Calculates the amount of USDC a user will receive when redeeming USDC+ receipt tokens.
/// 
/// This function provides the real-time redemption value by incorporating the latest yield
/// from Drift protocol before calculating the USDC amount.
/// 
/// ## Parameters
/// - `data_usdc_controller`: Raw bytes from the USDC strategy controller account.
/// - `data_spot_market_usdc`: Raw bytes from Drift's USDC spot market account containing
///   current market state and interest rates.
/// - `data_user_account`: Raw bytes from Drift user account that holds the protocol's USDC
///   deposits and accumulated yield.
/// - `receipt_amount`: Amount of USDC+ tokens to redeem, scaled by 10^6 (1 USDC+ = 1_000_000)
/// 
/// ## Returns
/// Amount of USDC tokens the user will receive (with 6 decimals places)
/// 
/// ## Process
/// 1. Extract from accounts following data:
///     - AutoCompound state from controller account
///     - Drift usdc spot market state
///     - Reflect's Drift user account state
///     - USDC+ supply
/// 2. Calculate amount of USDC at Drift
/// 3. Updates the AutoCompound state with latest Drift usdc holdings
/// 4. Calculates USDC tokens based on the updated exchange rate
/// 
/// ## Formula
/// usdc = receipt_amount * deposited_vault_value / effective_supply
///
/// ## Example
/// 
/// // Redeem 100 USDC+ tokens
/// let usdc = exchange_rate_receipt_input(
///     &controller_data,
///     &spot_market_data,
///     &user_account_data,
///     42_000_000  // 42 USDC+ with 6 decimals
/// )?;
/// 
pub fn exchange_rate_receipt_input(    
    data_usdc_controller: &[u8],
    data_spot_market_usdc: &[u8],
    data_user_account: &[u8],
    data_usdc_plus_mint: &[u8],
    receipt_amount: u64,     
) -> Result<u64> {    

    // Get autocompound and recipients.
    let mut auto_compound: AutoCompound = deserialise_autocompound(data_usdc_controller)?;

    // Get supply of USDC+ tokens.
    let usdc_plus_supply = get_mint_supply(data_usdc_plus_mint)?;

    // Get usdc amount in drift.
    let usdc_amount_drift = get_usdc_amount_drift_data(data_user_account, data_spot_market_usdc)?;
    
    // Update pool value to latest value from drift.
    auto_compound.update_pool(usdc_amount_drift, &vec![10_000], usdc_plus_supply)?;
    let deposited_vault_value: u64 = auto_compound.deposited_vault_value;    
    
    compute_usdc_from_tokens(receipt_amount, deposited_vault_value, usdc_plus_supply)
}

/// Calculates USDC redemption amount for USDC+ tokens using Anchor account validation.
/// 
/// This wrapper function provides account validation before calculating the redemption value,
/// ensuring the correct Reflect protocol accounts are being used.
/// 
/// ## Parameters
/// - `usdc_controller_account`: The USDC strategy controller AccountInfo, must match `ids::usdc_controller::ID`
/// - `spot_market_usdc_account`: Drift's USDC spot market AccountInfo, must match `ids::usdc_spot_market::ID`
/// - `reflect_user_account`: Reflect's Drift user AccountInfo, must match `ids::reflect_user_account_strategy_0::ID`
/// - `receipt_amount`: Amount of USDC+ tokens to redeem, scaled by 10^6 (1 USDC+ = 1_000_000)
/// 
/// ## Returns
/// Amount of USDC the user will receive (with 6 decimal places)
/// 
/// ## Security
/// - Validates all account addresses match expected protocol accounts
/// - Prevents account substitution attacks
/// - Returns `InvalidAccount` error if any account doesn't match
/// 
/// ## Example
/// ```ignore
/// let usdc = exchange_rate_receipt_accounts(
///     &ctx.accounts.usdc_controller,
///     &ctx.accounts.spot_market,
///     &ctx.accounts.drift_user,
///     42_000_000  // 42 USDC+
/// )?;
/// ```
pub fn exchange_rate_receipt_accounts(    
    usdc_controller_account: &AccountInfo,
    spot_market_usdc_account: &AccountInfo,
    reflect_user_account: &AccountInfo,
    usdc_plus_mint_account: &AccountInfo,
    receipt_amount: u64,     
) -> Result<u64> {  
    require!(usdc_controller_account.key == &ids::usdc_controller::ID, ReflectErrorCodes::InvalidUsdcControllerAccount);
    require!(spot_market_usdc_account.key == &ids::usdc_spot_market::ID, ReflectErrorCodes::InvalidUsdcSpotMarketAccount);
    require!(reflect_user_account.key == &ids::reflect_user_account_strategy_0::ID, ReflectErrorCodes::InvalidReflectUserAccount);
    exchange_rate_receipt_input(    
        &usdc_controller_account.data.borrow(),
        &spot_market_usdc_account.data.borrow(),
        &reflect_user_account.data.borrow(),
        &usdc_plus_mint_account.data.borrow(),
        receipt_amount,     
    )
}


/// Returns the raw components needed for exchange calculation
/// Call this once, cache the results, then use compute_tokens_from_usdc directly
pub fn get_exchange_components(
    data_usdc_controller: &[u8],
    data_spot_market_usdc: &[u8],
    data_user_account: &[u8],
    data_usdc_plus_mint: &[u8],
) -> Result<(u64, u64)> {  // (deposited_vault_value, effective_supply)
    
    let mut auto_compound = deserialise_autocompound(data_usdc_controller)?;
    let usdc_plus_supply = get_mint_supply(data_usdc_plus_mint)?;
    let usdc_amount_drift = get_usdc_amount_drift_data(data_user_account, data_spot_market_usdc)?;
    
    auto_compound.update_pool(usdc_amount_drift, &vec![10_000], usdc_plus_supply)?;
    
    Ok((auto_compound.deposited_vault_value, usdc_plus_supply))
}

// cargo test --lib exchange::tests -- --nocapture

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::PathBuf;

    const LOCAL_CONTROLLER: &str = "usdc_controller_account.bin";
    const LOCAL_SPOT_MARKET: &str = "spot_market_usdc.bin";
    const LOCAL_USER_ACCOUNT: &str = "user_account.bin";    
    const LOCAL_USDC_PLUS_MINT: &str = "usdc_plus_mint.bin";

    fn get_test_assets_dir() -> PathBuf {
        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("./test_assets/local/");
        path
    }

    #[test]
    fn test_compute() {
        let result = compute_usdc_from_tokens(1000, 1_100_000, 1_000_000).unwrap();
        assert_eq!(result, 1100);
        let result = compute_usdc_from_tokens(1000, 1_000_000, 0);
        assert!(result.is_err());
        let result = compute_usdc_from_tokens(u64::MAX, u64::MAX, 1);
        assert!(result.is_err());
        let result = compute_tokens_from_usdc(u64::MAX, 1, u64::MAX);
        assert!(result.is_err());
    }

    /// Tests exchange rate calculations with real mainnet/local account data.
    #[test]
    fn test_exchange_rate_functions() {
        let assets_dir = get_test_assets_dir();
        let controller_data = fs::read(assets_dir.join(LOCAL_CONTROLLER)).expect(&format!("Missing: {}", LOCAL_CONTROLLER));
        let spot_data = fs::read(assets_dir.join(LOCAL_SPOT_MARKET)).expect(&format!("Missing: {}", LOCAL_SPOT_MARKET));
        let user_data: Vec<u8> = fs::read(assets_dir.join(LOCAL_USER_ACCOUNT)).expect(&format!("Missing: {}", LOCAL_USER_ACCOUNT));
        let usdc_plus_mint_data = fs::read(assets_dir.join(LOCAL_USDC_PLUS_MINT)).expect(&format!("Missing: {}", LOCAL_USDC_PLUS_MINT));

        println!("\n=== Deposit Tests ===");
        for amount in [1_000_000, 100_000_000, 1_000_000_000] {
            let tokens = exchange_rate_usdc_input(
                &controller_data,
                &spot_data,
                &user_data,
                &usdc_plus_mint_data,
                amount,
            ).expect("Failed to calculate deposit");
            let rate = tokens as f64 / amount as f64;
            println!(
                "Deposit {:.2} USDC → {:.6} USDC+ (1 USDC = {:.6} USDC+)",
                amount as f64 / 1_000_000.0,
                tokens as f64 / 1_000_000.0,
                rate
            );
        }

        println!("\n=== Redemption Tests ===");
        for amount in [1_000_000, 100_000_000, 1_000_000_000] {
            let usdc = exchange_rate_receipt_input(
                &controller_data,
                &spot_data,
                &user_data,
                &usdc_plus_mint_data,
                amount,
            ).expect("Failed to calculate redemption");
            let rate = usdc as f64 / amount as f64;
            println!(
                "Redeem {:.2} USDC+ → {:.6} USDC (1 USDC+ = {:.6} USDC)",
                amount as f64 / 1_000_000.0,
                usdc as f64 / 1_000_000.0,
                rate
            );
        }
    }

    /// Verifies USDC → USDC+ → USDC round trip maintains value (±1 unit for rounding).
    #[test]
    fn test_round_trip_conversion() {
        let assets_dir = get_test_assets_dir();

        let controller_data = fs::read(assets_dir.join(LOCAL_CONTROLLER)).expect(&format!("Missing: {}", LOCAL_CONTROLLER));
        let spot_data = fs::read(assets_dir.join(LOCAL_SPOT_MARKET)).expect(&format!("Missing: {}", LOCAL_SPOT_MARKET));
        let user_data = fs::read(assets_dir.join(LOCAL_USER_ACCOUNT)).expect(&format!("Missing: {}", LOCAL_USER_ACCOUNT));
        let mint_data = fs::read(assets_dir.join(LOCAL_USDC_PLUS_MINT)).expect(&format!("Missing: {}", LOCAL_USDC_PLUS_MINT));

        let initial_usdc = 1_000_000_000; // 1000 USDC

        let tokens = exchange_rate_usdc_input(
            &controller_data, &spot_data, &user_data, &mint_data, initial_usdc
        ).expect("Failed to calculate deposit");
        let final_usdc = exchange_rate_receipt_input(
            &controller_data, &spot_data, &user_data, &mint_data, tokens
        ).expect("Failed to calculate redemption");

        println!(
            "\nRound trip: {} USDC → {} USDC+ → {} USDC",
            initial_usdc / 1_000_000,
            tokens / 1_000_000,
            final_usdc / 1_000_000
        );
        let difference = (final_usdc as i64 - initial_usdc as i64).abs();
        assert!(difference <= 1, "Round trip loss exceeds tolerance: {} units", difference);
    }

    /// Compares rates with and without pending yield. Uses mint supply only.
    #[test]
    fn test_yield_impact_on_exchange_rate() {
        let assets_dir = get_test_assets_dir();

        let controller_data = fs::read(assets_dir.join(LOCAL_CONTROLLER)).expect(&format!("Missing: {}", LOCAL_CONTROLLER));
        let spot_data = fs::read(assets_dir.join(LOCAL_SPOT_MARKET)).expect(&format!("Missing: {}", LOCAL_SPOT_MARKET));
        let user_data = fs::read(assets_dir.join(LOCAL_USER_ACCOUNT)).expect(&format!("Missing: {}", LOCAL_USER_ACCOUNT));
        let mint_data = vec![0u8; 82];

        // Stored (on-chain) exchange rate: V / S, with S from the mint.
        let auto_compound = deserialise_autocompound(&controller_data).expect("Failed to deserialize autocompound");
        let usdc_plus_supply = get_mint_supply(&mint_data).unwrap_or(0);
        let stored_rate = if usdc_plus_supply > 0 {
            auto_compound.deposited_vault_value as f64 / usdc_plus_supply as f64
        } else {
            1.0
        };

        // Updated rate with pending yield captured.
        let test_amount = 1_000_000_000;
        let tokens = exchange_rate_usdc_input(
            &controller_data, &spot_data, &user_data, &mint_data, test_amount
        ).expect("Failed to calculate with yield");
        let updated_rate = test_amount as f64 / tokens as f64;

        println!("\nStored rate (no pending yield): 1 USDC+ = {:.6} USDC", stored_rate);
        println!("Updated rate (with pending yield): 1 USDC+ = {:.6} USDC", updated_rate);
        println!("Yield impact: {:.4}%", ((updated_rate / stored_rate) - 1.0) * 100.0);
    }

    /// Functions should error on invalid controller data.
    #[test]
    fn test_error_handling() {
        let bad_controller = vec![0u8; 100]; // Too short to contain AutoCompound
        let valid_spot = vec![0u8; 10000];
        let valid_user = vec![0u8; 10000];
        let mint_data = vec![0u8; 82];

        assert!(exchange_rate_usdc_input(&bad_controller, &valid_spot, &valid_user, &mint_data, 1_000_000).is_err());
        assert!(exchange_rate_receipt_input(&bad_controller, &valid_spot, &valid_user, &mint_data, 1_000_000).is_err());
    }

    /// After capture, PPS is fixed until new yield accrues. We use mint supply (S) everywhere.
    #[test]
    fn test_exchange_rate_progression() {
        let assets_dir = get_test_assets_dir();

        let controller_data = fs::read(assets_dir.join(LOCAL_CONTROLLER)).expect(&format!("Missing: {}", LOCAL_CONTROLLER));
        let spot_data = fs::read(assets_dir.join(LOCAL_SPOT_MARKET)).expect(&format!("Missing: {}", LOCAL_SPOT_MARKET));
        let user_data = fs::read(assets_dir.join(LOCAL_USER_ACCOUNT)).expect(&format!("Missing: {}", LOCAL_USER_ACCOUNT));
        let usdc_plus_mint_data = fs::read(assets_dir.join(LOCAL_USDC_PLUS_MINT)).expect(&format!("Missing: {}", LOCAL_USDC_PLUS_MINT));

        
        let mut auto_compound = deserialise_autocompound(&controller_data).expect("Failed to deserialize");
        let initial_drift_value = get_usdc_amount_drift_data(&user_data, &spot_data).expect("Failed to get drift value");
        let usdc_plus_supply = get_mint_supply(&usdc_plus_mint_data).unwrap_or(0);

        println!("\n=== Exchange Rate Progression Test ===");
        println!("Initial drift value: {:.2}", initial_drift_value as f64 / 1_000_000.0);

        // Test amounts.
        let test_usdc = 1_000_000_000;   // 1000 USDC
        let test_receipt = 1_000_000_000; // 1000 USDC+

        // Simulate multiple rounds of yield accumulation and capture.
        let mut last_deposit_rate = 0.0;
        let mut last_redeem_rate = 0.0;

        for round in 0..5 {
            println!("\n--- Round {} ---", round);

            // Simulate yield accumulation (2% per round for testing)
            let simulated_yield = (initial_drift_value as f64 * 0.02 * (round + 1) as f64) as u64;
            let current_drift_value = initial_drift_value + simulated_yield;

            println!(
                "Simulated drift value: {:.2} (yield: {:.2})",
                current_drift_value as f64 / 1_000_000.0,
                simulated_yield as f64 / 1_000_000.0
            );

            // Use SUPPLY FROM MINT (S). If zero (placeholder), the recipient path won’t mint anyway
            // with cuts = [10_000] (100% pool keep), so this is safe.
            let token_supply = usdc_plus_supply;

            // New update_pool signature
            auto_compound.update_pool(current_drift_value, &[10_000], token_supply).unwrap();

            let deposit_tokens = compute_tokens_from_usdc(
                test_usdc,
                auto_compound.deposited_vault_value,
                token_supply,
            ).unwrap();

            let redeem_usdc = compute_usdc_from_tokens(
                test_receipt,
                auto_compound.deposited_vault_value,
                token_supply,
            ).unwrap();

            let deposit_rate = deposit_tokens as f64 / test_usdc as f64;
            let redeem_rate = redeem_usdc as f64 / test_receipt as f64;

            println!("After capture:");
            println!("  1 USDC = {:.6} USDC+ (deposit rate)", deposit_rate);
            println!("  1 USDC+ = {:.6} USDC (redeem rate)", redeem_rate);
            println!("  deposited_vault_value (V): {}", auto_compound.deposited_vault_value);
            println!("  token_supply (S from mint): {}", token_supply);

            if round > 0 {
                // Deposit rate should not improve after capture.
                assert!(
                    deposit_rate <= last_deposit_rate + 0.000001,
                    "Deposit rate improved after capture: {} > {} at round {}",
                    deposit_rate, last_deposit_rate, round
                );
                // Redeem rate should not worsen after capture.
                assert!(
                    redeem_rate >= last_redeem_rate - 0.000001,
                    "Redeem rate worsened after capture: {} < {} at round {}",
                    redeem_rate, last_redeem_rate, round
                );
            }

            last_deposit_rate = deposit_rate;
            last_redeem_rate = redeem_rate;

            // Consistency across amounts
            for amount in [1_000_000, 100_000_000, 10_000_000_000] {
                let tokens = compute_tokens_from_usdc(
                    amount,
                    auto_compound.deposited_vault_value,
                    token_supply,
                ).unwrap();
                let rate = tokens as f64 / amount as f64;
                assert!(
                    (rate - deposit_rate).abs() < 0.000001,
                    "Rate inconsistent for different amounts"
                );
            }
        }

        println!("\n=== Summary ===");
        println!("Deposit rate progression (USDC+ per USDC should decrease):");
        println!("  Started at: ~1.0");
        println!("  Ended at: {:.6}", last_deposit_rate);
        println!("Redeem rate progression (USDC per USDC+ should increase):");
        println!("  Started at: ~1.0");
        println!("  Ended at: {:.6}", last_redeem_rate);
    }


    #[test]
    fn test_get_exchange_components() {
        let assets_dir = get_test_assets_dir();
        let controller_data = fs::read(assets_dir.join(LOCAL_CONTROLLER)).expect(&format!("Missing: {}", LOCAL_CONTROLLER));
        let spot_data = fs::read(assets_dir.join(LOCAL_SPOT_MARKET)).expect(&format!("Missing: {}", LOCAL_SPOT_MARKET));
        let user_data = fs::read(assets_dir.join(LOCAL_USER_ACCOUNT)).expect(&format!("Missing: {}", LOCAL_USER_ACCOUNT));
        let mint_data = fs::read(assets_dir.join(LOCAL_USDC_PLUS_MINT)).expect(&format!("Missing: {}", LOCAL_USDC_PLUS_MINT));

        let (vault_value, supply) = get_exchange_components(
            &controller_data,
            &spot_data,
            &user_data,
            &mint_data,
        ).expect("Failed to get exchange components");

        assert!(vault_value > 0, "Vault value should be > 0");
        assert!(supply > 0, "Supply should be > 0");

        println!("deposited_vault_value: {}", vault_value);
        println!("effective_supply: {}", supply);
    }

    #[test]
    fn test_get_exchange_components_matches_direct_call() {
        let assets_dir = get_test_assets_dir();
        let controller_data = fs::read(assets_dir.join(LOCAL_CONTROLLER)).expect(&format!("Missing: {}", LOCAL_CONTROLLER));
        let spot_data = fs::read(assets_dir.join(LOCAL_SPOT_MARKET)).expect(&format!("Missing: {}", LOCAL_SPOT_MARKET));
        let user_data = fs::read(assets_dir.join(LOCAL_USER_ACCOUNT)).expect(&format!("Missing: {}", LOCAL_USER_ACCOUNT));
        let mint_data = fs::read(assets_dir.join(LOCAL_USDC_PLUS_MINT)).expect(&format!("Missing: {}", LOCAL_USDC_PLUS_MINT));

        let (vault_value, supply) = get_exchange_components(
            &controller_data,
            &spot_data,
            &user_data,
            &mint_data,
        ).expect("Failed to get exchange components");

        // Test multiple amounts
        for amount in [1_000_000u64, 100_000_000, 1_000_000_000, 69_420_000] {
            // Using cached components
            let tokens_cached = compute_tokens_from_usdc(amount, vault_value, supply).unwrap();
            
            // Using direct call
            let tokens_direct = exchange_rate_usdc_input(
                &controller_data,
                &spot_data,
                &user_data,
                &mint_data,
                amount,
            ).unwrap();

            assert_eq!(
                tokens_cached, tokens_direct,
                "Mismatch for amount {}: cached={} direct={}",
                amount, tokens_cached, tokens_direct
            );

            // Same for redemption
            let usdc_cached = compute_usdc_from_tokens(amount, vault_value, supply).unwrap();
            let usdc_direct = exchange_rate_receipt_input(
                &controller_data,
                &spot_data,
                &user_data,
                &mint_data,
                amount,
            ).unwrap();

            assert_eq!(
                usdc_cached, usdc_direct,
                "Redemption mismatch for amount {}: cached={} direct={}",
                amount, usdc_cached, usdc_direct
            );
        }

        println!("All amounts match between cached components and direct calls");
    }

}