usdc-plus-exchange 0.1.3

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
use anchor_lang::prelude::{*, borsh::BorshSchema};
use std::io::Write;
use crate::drift::SafeMath;
use crate::errors::ReflectErrorCodes;
use crate::reflect::helpers::{calc_all_cuts, compute_receipt_token};

#[repr(C)]
#[derive(BorshSchema, AnchorDeserialize, AnchorSerialize, Default, Debug, Clone, InitSpace, PartialEq, Eq)]
pub struct AutoCompound {           
   /// Total collateral **amount** currently attributed to vault holders.
   /// - Units: **collateral (base units)**
   /// - Includes: all user deposits + all pool allocations (index 0 cut) captured so far
   /// - Excludes: any value queued for extraction to fee recipients (Q)
   /// - Mutates on:
   ///     * deposit  → V += deposit_collateral
   ///     * redeem   → V -= redeemed_collateral
   ///     * capture  → V += pool_allocation_collateral (index 0 share only)
   pub deposited_vault_value: u64,

   /// Net user cashflow since the last capture.
   /// - Units: **collateral (signed)**
   /// - Purpose: isolate organic PnL from user flows when computing capturable yield
   /// - Updates:
   ///     * after deposit  → += deposit_collateral
   ///     * after redeem   → -= redeemed_collateral
   ///     * after capture  → reset to 0
   pub net_user_flow_since_capture: i64,

   /// Vault's observed total **collateral** at the most recent capture boundary.
   /// - Units: **collateral**
   /// - Used as the baseline for `refresh_autocompounder(current_total_collateral)`
   /// - On capture:
   ///     * compute yield/loss vs `last_pool_value + net_user_flow_since_capture`
   ///     * then set `last_pool_value = post_capture_pool_value`
   pub last_pool_value: u64,

   /// Total receipt tokens currently queued to be minted to recipients.
   /// - Units: **receipt tokens**
   /// - Semantics: recipients' portion of profit, converted to receipt tokens at the current PPS
   /// - On capture/process_yield:
   ///     * Q_receipt += receipt_rate(recipients_collateral)
   /// - On distribution (mint step):
   ///     * consumer reads Q_receipt, mints, then resets/decrements Q_receipt
   pub queued_recipient_shares: u64,
}

impl AutoCompound {

    pub fn update_total_capturable_yield(&mut self, value: u64){
        self.queued_recipient_shares = value;      
    }

    pub fn calculate_capturable_yield(&self, current_value: u64) -> Result<i64> {
        // Expected value = last recorded value + net user flows.
        let expected_value = if self.net_user_flow_since_capture >= 0 {
            self.last_pool_value.safe_add(self.net_user_flow_since_capture as u64)?
        } else {
            self.last_pool_value.safe_sub((-self.net_user_flow_since_capture) as u64)?
        };
        
        // Calculate yield as signed value (can be negative for losses).
        let yield_or_loss = (current_value as i128) - (expected_value as i128);        
        
        if yield_or_loss > i64::MAX as i128 {
            return Err(ReflectErrorCodes::MathError.into());
        } else if yield_or_loss < i64::MIN as i128 {
            return Err(ReflectErrorCodes::MathError.into());
        }
        
        Ok(yield_or_loss as i64)
    }

    pub fn update_pool_value(&mut self, value: u64){
        self.last_pool_value = value;      
    }
    
    /// Settle yield/loss vs. the baseline, book pool keep into V (USDC),
    /// queue **recipient mints** as SHARES (USDC+), and advance the baseline.
    ///
    /// ### Invariants & Units
    /// - `current_total_usdc`: observed assets under management (USDC).
    /// - `cuts_bp[0]`: pool keep (stays in V, **no mint** to index 0).
    /// - `cuts_bp[1..]`: recipients to **mint** (SHARES) later.
    /// - `deposited_vault_value (V)`: USDC.
    /// - `effective_supply (S)`: SHARES (USDC+ tokens).
    /// - `queued_recipient_shares (Q)`: **SHARES to mint** to recipients i≥1 (not value).
    ///
    /// ### Cases
    /// 1) Loss: V -= loss; Q unchanged; baseline = current_total_usdc.
    /// 2) No change: nothing; baseline = current_total_usdc.
    /// 3) Profit:
    ///    - Split profit in **USDC** with `cuts_bp`.
    ///    - Add pool keep (index 0) to **V** (PPS ↑), **mint nothing** for index 0.
    ///    - Convert recipients' **USDC** portion to **SHARES** at **current PPS** (after pool keep is booked).
    ///    - Q += shares_for_recipients.
    ///    - Baseline = current_total_usdc (no assets left; we’re minting later).
    ///
    /// ### Why baseline = current_total_usdc on profit?
    /// Minting shares to recipients does not move USDC out of the pool; it inflates S.
    /// Therefore the on-chain assets remain the observed amount; only PPS is affected when
    /// we later mint those shares.
    pub fn update_pool(&mut self, current_total_usdc: u64, cuts_bp: &[u16], token_supply: u64) -> Result<()> {
        // Compute organic signed PnL vs the moving baseline:        
        // y = current_total_usdc - (last_pool_value +/- net_user_flow_since_capture)        
        let y: i64 = self.calculate_capturable_yield(current_total_usdc)?;
        
        // --------- LOSS PATH ---------
        if y < 0 {            
            // Book the loss directly into V. No recipient queue changes.            
            self.deposited_vault_value = self.deposited_vault_value.safe_sub(y.unsigned_abs())?;

        // --------- PROFIT PATH ---------
        } else if y > 0 {            
            // Split profit as: pool_keep (index 0) + recipients (i>=1).
            let profit_usdc: u64 = y as u64;
            let amounts_usdc: Vec<u64> = calc_all_cuts(profit_usdc, cuts_bp.to_vec())?;
            let pool_keep_usdc = amounts_usdc.get(0).copied().unwrap_or(0);
            let recipients_usdc = profit_usdc.safe_sub(pool_keep_usdc)?;

            // Let profit_usdc = pool_keep_usdc + recipients_usdc.
            // No USDC leaves the external vault during capture; recipients (i>=1) are paid via new share issuance.
            // Therefore the vault's assets under management (V) must increase by the FULL profit:
            //     V_after = V_before + profit_usdc
            //             = V_before + (pool_keep_usdc + recipients_usdc)
            // If we only added pool_keep_usdc to V and then minted recipient shares (S↑),
            // PPS = V/S would be depressed, enabling cheap mints and underpaying redemptions until the next capture.
            self.deposited_vault_value = self.deposited_vault_value.safe_add(profit_usdc)?;

            // Now compute how many shares to mint to recipients so their post-mint value equals exactly recipients_usdc with no dilution:
            if recipients_usdc > 0 {                           
                require!(token_supply > 0, ReflectErrorCodes::MathError);
                require!(self.deposited_vault_value > recipients_usdc, ReflectErrorCodes::MathError);

                // Denominator should be V_before + pool_keep_usdc:
                let v_minus_r: u64 = self.deposited_vault_value.safe_sub(recipients_usdc)?;

                // Solve:  shares to mint = recipients_usdc * S / (V_after - recipients_usdc)                
                let shares_to_mint: u64 = compute_receipt_token(recipients_usdc, v_minus_r, token_supply)?;

                // Shares minted to recipients by the caller in the same tx path.
                self.queued_recipient_shares = self.queued_recipient_shares.safe_add(shares_to_mint)?;
            }
            // Note: no shares to index 0 in AutoCompound mode; pool_keep_usdc is already
            // reflected in V and benefits existing LPs via higher PPS.
        } 

        // Advance the capture baseline to the observed total vault collateral.
        self.last_pool_value = current_total_usdc;

        // Reset net user flows for the next interval.
        self.net_user_flow_since_capture = 0;

        Ok(())
    }
    
    pub fn deserialize(buf: &mut &[u8]) -> Result<Self> {        
        let deposited_vault_value = u64::deserialize(buf)?;
        let net_user_flow_since_capture = i64::deserialize(buf)?;
        let last_pool_value = u64::deserialize(buf)?;
        let queued_recipient_shares = u64::deserialize(buf)?;
        
        Ok(AutoCompound {            
            deposited_vault_value,
            net_user_flow_since_capture,
            last_pool_value,
            queued_recipient_shares,
        })
    }
    
    pub fn try_serialise<W: Write>(&self, writer: &mut W) -> Result<()> {
        self.deposited_vault_value.serialize(writer)?;
        self.net_user_flow_since_capture.serialize(writer)?;
        self.last_pool_value.serialize(writer)?;
        self.queued_recipient_shares.serialize(writer)?;
        Ok(())
    }
}


// 974 is an actual value found by comparison.
pub const AUTOCOMPOUND_START: usize = 1026;
pub const USDC_CONTROLLER_SIZE: usize = 10000;
pub fn deserialise_autocompound(data_usdc_controller: &[u8]) -> Result<AutoCompound> {
    if data_usdc_controller.len() < AUTOCOMPOUND_START + 40 {
        return Err(ReflectErrorCodes::InsufficientData.into());
    }
    
    let mut slice = &data_usdc_controller[AUTOCOMPOUND_START..];
    AutoCompound::deserialize(&mut slice)
        .map_err(|_| ReflectErrorCodes::DeserializationError.into())
}

// cargo test --lib reflect::autocompound -- --nocapture

#[cfg(test)]
mod tests {
    use super::*;        

    #[test]
    fn test_deserialise_autocompound_insufficient_data() {
        let short_data = vec![0u8; AUTOCOMPOUND_START + 39]; // Just under minimum
        let result = deserialise_autocompound(&short_data);
        assert!(result.is_err());
        // assert!(matches!(result.unwrap_err(), SliceError::InsufficientData))
    }

    #[test]
    fn test_deserialise_autocompound_corrupted_data() {
        let bad_data = vec![0xFF; 100]; // Garbage data.
        let result = deserialise_autocompound(&bad_data);
        assert!(result.is_err());
    }    

    #[test]
    fn mainnet_debug_autocompound_from_file() {
        use std::fs;
        use std::path::PathBuf;

        const LOCAL_CONTROLLER: &str = "usdc_controller_account.bin";

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

        let assets_dir = get_test_assets_dir();
        let data = fs::read(assets_dir.join(LOCAL_CONTROLLER)).expect(&format!("Missing: {}", LOCAL_CONTROLLER));

        println!("\n=== AutoCompound decode ===");
        println!("buffer len: {}", data.len());
        println!("AUTOCOMPOUND_START: {}", AUTOCOMPOUND_START);

        // Try to deserialize at the configured offset
        let ac = deserialise_autocompound(&data).expect("Failed to deserialize AutoCompound");

        // Log all fields (raw)
        println!("deposited_vault_value       : {}", ac.deposited_vault_value);
        println!("net_user_flow_since_capture : {}", ac.net_user_flow_since_capture);
        println!("last_pool_value             : {}", ac.last_pool_value);
        println!("queued_recipient_shares     : {}", ac.queued_recipient_shares);

        // Also print human-friendly (USDC, 6 dp) for the u64 fields
        println!("V (USDC)                    : {:.6}", ac.deposited_vault_value as f64 / 1_000_000.0);
        println!("baseline (USDC)             : {:.6}", ac.last_pool_value as f64 / 1_000_000.0);

        // Optional: quick sanity checks that won’t fail CI unless completely broken
        assert!(data.len() >= AUTOCOMPOUND_START + 40, "fixture too small for AutoCompound");
    }

    
// cargo test --lib reflect::autocompound::tests_no_strategy -- --nocapture

// --- robust reader that finds AutoCompound without hard-coding offsets ---

fn plausible(ac: &AutoCompound) -> bool {
    // Heuristics: values in sane ranges, and baseline not wildly different from V
    // Tune these if you have better priors.
    let v = ac.deposited_vault_value as u128;
    let b = ac.last_pool_value as u128;
    let q = ac.queued_recipient_shares as u128;
    let nf = ac.net_user_flow_since_capture;

    // Require at least *some* non-zero signal
    if v == 0 && b == 0 && q == 0 && nf == 0 { return false; }

    // Upper bounds (very loose): < 10^15 base units (~1e9 USDC)
    if v > 1_000_000_000_000_000u128 || b > 1_000_000_000_000_000u128 { return false; }

    // Baseline shouldn’t be > 4x vault or < 0.25x (very loose)
    if v > 0 && (b < v / 4 || b > v.saturating_mul(4)) { return false; }

    // Net flow shouldn’t be orders larger than vault (very loose: 2x)
    if v > 0 && (nf.unsigned_abs() as u128) > v.saturating_mul(2) { return false; }

    true
}

/// Returns (AutoCompound, start_offset)
pub fn deserialise_autocompound_dynamic(buf: &[u8]) -> Result<(AutoCompound, usize)> {
    use anchor_lang::prelude::AnchorDeserialize;

    // 1) Try right after Anchor discriminator (offset 8)
    if buf.len() >= 8 + 32 {
        if let Ok(mut cur) = <&[u8] as TryFrom<&[u8]>>::try_from(&buf[8..]) {
            if let Ok(ac) = AutoCompound::deserialize(&mut cur) {
                if plausible(&ac) {
                    return Ok((ac, 8));
                }
            }
        }
    }

    // 2) Try your legacy constant
    if buf.len() >= AUTOCOMPOUND_START + 32 {
        let mut cur = &buf[AUTOCOMPOUND_START..];
        if let Ok(ac) = AutoCompound::deserialize(&mut cur) {
            if plausible(&ac) {
                return Ok((ac, AUTOCOMPOUND_START));
            }
        }
    }

    // 3) Scan in 8-byte steps for the first plausible decode
    let end = buf.len().saturating_sub(32);
    for start in (0..=end).step_by(8) {
        let mut cur = &buf[start..];
        if let Ok(ac) = AutoCompound::deserialize(&mut cur) {
            if plausible(&ac) {
                return Ok((ac, start));
            }
        }
    }

    Err(ReflectErrorCodes::DeserializationError.into())
}


#[cfg(test)]
mod tests_no_strategy {
    use super::*;
    use std::fs;
    use std::path::PathBuf;
    use anchor_lang::prelude::AnchorDeserialize;

    const LOCAL_CONTROLLER: &str = "usdc_controller_account.bin";

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

    fn log_ac(label: &str, ac: &AutoCompound, start: usize, data: &[u8]) {
        println!("\n--- {} ---", label);
        println!("AutoCompound @ offset      : {}", start);
        println!("deposited_vault_value      : {}", ac.deposited_vault_value);
        println!("net_user_flow_since_capture: {}", ac.net_user_flow_since_capture);
        println!("last_pool_value            : {}", ac.last_pool_value);
        println!("queued_recipient_shares    : {}", ac.queued_recipient_shares);
        println!("V (USDC)                   : {:.6}", ac.deposited_vault_value as f64 / 1_000_000.0);
        println!("baseline (USDC)            : {:.6}", ac.last_pool_value as f64 / 1_000_000.0);

        // Show first 32 raw bytes at this offset for sanity
        let end = (start + 32).min(data.len());
        print!("raw bytes [{}..{}]:", start, end);
        for b in &data[start..end] {
            print!(" {:02x}", b);
        }
        println!();
    }

    fn try_decode_at(data: &[u8], start: usize) -> Option<AutoCompound> {
        if data.len() < start + 32 {
            return None;
        }
        let mut cur = &data[start..];
        AnchorDeserialize::deserialize(&mut cur).ok()
    }

    #[test]
    fn debug_autocompound_no_strategy() {
        let assets_dir = get_test_assets_dir();
        let data = fs::read(assets_dir.join(LOCAL_CONTROLLER))
            .expect(&format!("Missing: {}", LOCAL_CONTROLLER));

        println!("\n=== AutoCompound (no-Strategy) decode ===");
        println!("buffer len           : {}", data.len());
        println!("AUTOCOMPOUND_START   : {}", AUTOCOMPOUND_START);

        assert!(data.len() >= 8, "account too short for discriminator");
        let disc = &data[..8];
        print!("discriminator bytes  :");
        for b in disc { print!(" {:02x}", b); }
        println!();

        // 1) Try right after discriminator (offset 8)
        if let Some(ac) = try_decode_at(&data, 8) {
            log_ac("decode @8 (after discriminator)", &ac, 8, &data);
        } else {
            println!("\n--- decode @8 failed ---");
        }

        // 2) Try the configured fixed offset
        if let Some(ac) = try_decode_at(&data, AUTOCOMPOUND_START) {
            log_ac("decode @AUTOCOMPOUND_START", &ac, AUTOCOMPOUND_START, &data);
        } else {
            println!("\n--- decode @AUTOCOMPOUND_START failed ---");
        }

        // 3) Scan for a plausible AC in 8-byte steps
        let mut found = None;
        for start in (0..data.len().saturating_sub(32)).step_by(8) {
            if let Some(ac) = try_decode_at(&data, start) {
                // Plausibility: not ALL zeros
                if !(ac.deposited_vault_value == 0
                    && ac.last_pool_value == 0
                    && ac.net_user_flow_since_capture == 0
                    && ac.queued_recipient_shares == 0)
                {
                    log_ac("decode @scan (plausible)", &ac, start, &data);
                    found = Some(start);
                    break;
                }
            }
        }

        if found.is_none() {
            println!("\n--- scan failed to find a plausible AutoCompound ---");
        }
    }
}

#[test]
fn ddd() {
    use std::fs;
    use std::path::PathBuf;

    const LOCAL_CONTROLLER: &str = "usdc_controller_account.bin";

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

    let data = fs::read(assets_dir().join(LOCAL_CONTROLLER))
        .expect(&format!("Missing: {}", LOCAL_CONTROLLER));

    println!("\n=== AutoCompound decode ===");
    println!("buffer len: {}", data.len());
    println!("AUTOCOMPOUND_START: {}", AUTOCOMPOUND_START);

    let (ac, start) = deserialise_autocompound_dynamic(&data)
        .expect("failed to locate/deserialize AutoCompound");

    println!("AutoCompound @ offset      : {}", start);
    println!("deposited_vault_value      : {}", ac.deposited_vault_value);
    println!("net_user_flow_since_capture: {}", ac.net_user_flow_since_capture);
    println!("last_pool_value            : {}", ac.last_pool_value);
    println!("queued_recipient_shares    : {}", ac.queued_recipient_shares);
    println!("V (USDC)                   : {:.6}", ac.deposited_vault_value as f64 / 1_000_000.0);
    println!("baseline (USDC)            : {:.6}", ac.last_pool_value as f64 / 1_000_000.0);

    // raw bytes preview
    let end = (start + 32).min(data.len());
    print!("raw bytes [{}..{}]:", start, end);
    for b in &data[start..end] { print!(" {:02x}", b); }
    println!();
}


}



// cargo test --lib mainnet_log_autocompound -- --nocapture

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

    // pull these from inside the crate
    use crate::reflect::{deserialise_autocompound, AUTOCOMPOUND_START};

    const CONTROLLER_BIN: &str = "usdc_controller_account.bin";

    fn find_assets_dir() -> PathBuf {
        // prefer mainnet/, fall back to local/
        let base = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let mainnet = base.join("test_assets/mainnet");
        if mainnet.join(CONTROLLER_BIN).exists() {
            return mainnet;
        }
        let local = base.join("test_assets/local");
        assert!(
            local.join(CONTROLLER_BIN).exists(),
            "Could not find {} in test_assets/mainnet or test_assets/local",
            CONTROLLER_BIN
        );
        local
    }

    fn dump_hex(label: &str, bytes: &[u8]) {
        print!("{label}:");
        for b in bytes { print!(" {:02x}", b); }
        println!();
    }

    #[test]
    fn mainnet_log_autocompound() {
        let dir = find_assets_dir();
        let path = dir.join(CONTROLLER_BIN);
        let data = fs::read(&path).expect("failed to read controller dump");

        println!("Using assets dir: {}", dir.display());
        println!("buffer len            : {}", data.len());
        println!("AUTOCOMPOUND_START    : {}", AUTOCOMPOUND_START);

        // show a small window around the magic offset
        let s = AUTOCOMPOUND_START;
        let before = s.saturating_sub(16);
        let end32 = (s + 32).min(data.len());
        let end48 = (s + 48).min(data.len());

        dump_hex("bytes [start-16 .. start)", &data[before..s]);
        dump_hex("bytes [start .. start+32]", &data[s..end32]);
        dump_hex("bytes [start+32 .. +48]  ", &data[end32..end48]);

        // use the crate’s deserializer (which uses AUTOCOMPOUND_START internally)
        let ac = deserialise_autocompound(&data).expect("deserialize AutoCompound");

        println!("deposited_vault_value      : {}", ac.deposited_vault_value);
        println!("net_user_flow_since_capture: {}", ac.net_user_flow_since_capture);
        println!("last_pool_value            : {}", ac.last_pool_value);
        println!("queued_recipient_shares    : {}", ac.queued_recipient_shares);        
        println!("V (USDC)                   : {:.6}", ac.deposited_vault_value as f64 / 1_000_000.0);
        println!("baseline (USDC)            : {:.6}", ac.last_pool_value as f64 / 1_000_000.0);        
    }
}