multiliquid-svm-sdk 0.1.2

Unsigned transaction builders, account codecs, and quoting for Multiliquid on Solana
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! Oracle account resolution and nine-decimal NAV evaluation.
//!
//! Pyth and Redstone evaluation requires a caller-supplied cluster timestamp;
//! fixed-address and hardcoded prices do not require a clock.

use std::collections::{HashMap, HashSet};

use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};

use crate::{
    error::{Result, SdkError},
    types::{AssetConfigAccount, NavData},
};

const PRICE_UPDATE_V2_DISCRIMINATOR: [u8; 8] = [34, 241, 35, 99, 157, 126, 244, 205];
const PYTH_VERIFICATION_LEVEL_OFFSET: usize = 40;
const PYTH_FULL_MESSAGE_OFFSET: usize = 41;
const PYTH_MESSAGE_LENGTH: usize = 84;
const PYTH_PRICE_OFFSET: usize = 32;
const PYTH_CONFIDENCE_OFFSET: usize = 40;
const PYTH_EXPONENT_OFFSET: usize = 48;
const PYTH_PUBLISH_TIME_OFFSET: usize = 52;
const MAX_PYTH_EXPONENT_ADJUSTMENT: i64 = 38;
const REDSTONE_FEED_ID_OFFSET: usize = 8;
const REDSTONE_VALUE_OFFSET: usize = 40;
const REDSTONE_TIMESTAMP_OFFSET: usize = 72;
const REDSTONE_WRITE_TIMESTAMP_OPTION_OFFSET: usize = 80;

/// Resolve read-only, non-signer oracle accounts in first-appearance order.
/// Hardcoded prices contribute no accounts; duplicates across all configs and
/// oracle kinds are returned only once.
pub fn resolve_oracle_accounts(asset_configs: &[&AssetConfigAccount]) -> Vec<AccountMeta> {
    let mut seen = HashSet::new();
    let mut accounts = Vec::new();
    for config in asset_configs {
        for item in &config.nav_data {
            let address = match item {
                NavData::U64FixedAddress {
                    nav_account_address,
                    ..
                } => nav_account_address,
                NavData::PythPush {
                    pyth_push_account_address,
                    ..
                } => pyth_push_account_address,
                NavData::RedstonePush {
                    price_feed_account, ..
                } => price_feed_account,
                NavData::Hardcoded { .. } => continue,
            };
            if seen.insert(*address) {
                accounts.push(AccountMeta::new_readonly(*address, false));
            }
        }
    }
    accounts
}

/// Collect configured Pyth feeds in first-appearance order for RPC ownership validation.
pub fn resolve_pyth_oracle_accounts(configs: &[&AssetConfigAccount]) -> Vec<Pubkey> {
    let nav_data: Vec<_> = configs
        .iter()
        .map(|config| config.nav_data.as_slice())
        .collect();
    pyth_oracle_addresses(&nav_data)
}

/// NAV-list form of [`resolve_pyth_oracle_accounts`], shared with treasury asset configs.
pub(crate) fn pyth_oracle_addresses(nav_data: &[&[NavData]]) -> Vec<Pubkey> {
    let mut seen = HashSet::new();
    let mut addresses = Vec::new();
    for items in nav_data {
        for item in *items {
            if let NavData::PythPush {
                pyth_push_account_address,
                ..
            } = item
            {
                if seen.insert(*pyth_push_account_address) {
                    addresses.push(*pyth_push_account_address);
                }
            }
        }
    }
    addresses
}

/// Calculate the integer average of normalized oracle prices.
///
/// Returns zero for an empty source list or prices outside the configured
/// divergence tolerance. Individual prices and the result fit `u64`; the sum
/// and divergence numerator use checked `u128` arithmetic, matching production.
/// Pyth requires full verification and rejects stale prices, but accepts future
/// publish times like the TypeScript SDK. Redstone rejects future timestamps and
/// compares whole-second ages, flooring elapsed milliseconds like the program.
///
/// This raw byte-map API is ownership-agnostic. Callers must authenticate Pyth
/// accounts before evaluation, for example with
/// [`crate::quote_core::fetch_oracle_account_data_map`] and configured Pyth addresses.
pub fn calculate_nav(
    nav_data: &[NavData],
    account_data_map: &HashMap<Pubkey, Vec<u8>>,
    price_difference_bps: u16,
    current_unix_timestamp: Option<i64>,
) -> Result<u64> {
    let mut nav_sum = 0_u128;
    let mut max_nav = 0_u128;
    let mut min_nav = u128::MAX;

    for item in nav_data {
        let nav = match item {
            NavData::U64FixedAddress {
                nav_account_address,
                nav_price_offset,
                price_decimals,
            } => {
                let account_data = account_data_map.get(nav_account_address).ok_or_else(|| {
                    SdkError::Oracle(format!("Missing NAV account: {nav_account_address}"))
                })?;
                let price = read_u64_le(account_data, usize::from(*nav_price_offset))?;
                normalize_nav_to_nine_decimals(price, *price_decimals)?
            }
            NavData::Hardcoded {
                hardcoded_price,
                price_decimals,
            } => normalize_nav_to_nine_decimals(*hardcoded_price, *price_decimals)?,
            NavData::PythPush {
                pyth_push_account_address,
                feed_id,
                max_age_secs,
                max_conf_bps,
            } => {
                let account_data =
                    account_data_map
                        .get(pyth_push_account_address)
                        .ok_or_else(|| {
                            SdkError::Oracle(format!(
                                "Missing Pyth account: {pyth_push_account_address}"
                            ))
                        })?;
                let offset = pyth_price_message_offset(account_data)?;
                if account_data.get(offset..offset + 32) != Some(feed_id.as_slice()) {
                    return Err(SdkError::Oracle("Pyth feed mismatch".into()));
                }
                let price = read_i64_le(account_data, offset + PYTH_PRICE_OFFSET)?;
                let confidence = read_u64_le(account_data, offset + PYTH_CONFIDENCE_OFFSET)?;
                let exponent = read_i32_le(account_data, offset + PYTH_EXPONENT_OFFSET)?;
                let publish_time = read_i64_le(account_data, offset + PYTH_PUBLISH_TIME_OFFSET)?;
                let now = current_unix_timestamp.ok_or_else(|| {
                    SdkError::Oracle(
                        "currentUnixTimestamp is required for Pyth price freshness".into(),
                    )
                })?;
                if i128::from(publish_time) + i128::from(*max_age_secs) < i128::from(now) {
                    return Err(SdkError::Oracle("Pyth price too old".into()));
                }
                if price <= 0 {
                    return Err(SdkError::Oracle("Nav must be positive".into()));
                }
                if *max_conf_bps > 0
                    && u128::from(confidence) * 10_000 / price as u128 > u128::from(*max_conf_bps)
                {
                    return Err(SdkError::Oracle("Confidence too low".into()));
                }
                normalize_pyth_price_to_nav(price as u64, exponent)?
            }
            NavData::RedstonePush {
                price_feed_account,
                feed_id,
                max_age_secs,
            } => {
                let account_data = account_data_map.get(price_feed_account).ok_or_else(|| {
                    SdkError::Oracle(format!("Missing Redstone account: {price_feed_account}"))
                })?;
                // The npm SDK checks the feed ID, not Redstone's account discriminator.
                if account_data.get(REDSTONE_FEED_ID_OFFSET..REDSTONE_FEED_ID_OFFSET + 32)
                    != Some(feed_id.as_slice())
                {
                    return Err(SdkError::Oracle("Redstone feed mismatch".into()));
                }
                let now = current_unix_timestamp.ok_or_else(|| {
                    SdkError::Oracle(
                        "currentUnixTimestamp is required for Redstone price freshness".into(),
                    )
                })?;
                let timestamp_ms =
                    i128::from(read_u64_le(account_data, REDSTONE_TIMESTAMP_OFFSET)?);
                let current_timestamp_ms = i128::from(now) * 1_000;
                if timestamp_ms > current_timestamp_ms
                    || (current_timestamp_ms - timestamp_ms) / 1_000 > i128::from(*max_age_secs)
                {
                    return Err(SdkError::Oracle("Invalid Redstone NAV".into()));
                }
                let price = read_redstone_value(account_data)?;
                if price == 0 {
                    return Err(SdkError::Oracle("Nav must be positive".into()));
                }
                normalize_nav_to_nine_decimals(price, redstone_decimals(account_data)?)?
            }
        };
        let nav = u128::from(nav);
        max_nav = max_nav.max(nav);
        min_nav = min_nav.min(nav);
        nav_sum = nav_sum.checked_add(nav).ok_or(SdkError::MathOverflow)?;
    }

    if min_nav == u128::MAX {
        return Ok(0);
    }
    let tolerance = 10_000_u128
        .checked_sub(u128::from(price_difference_bps))
        .ok_or(SdkError::MathOverflow)?;
    let min_acceptable_nav = max_nav
        .checked_mul(tolerance)
        .ok_or(SdkError::MathOverflow)?
        / 10_000;
    if min_nav < min_acceptable_nav {
        return Ok(0);
    }
    let average = nav_sum / nav_data.len() as u128;
    u64::try_from(average).map_err(|_| SdkError::MathOverflow)
}

fn normalize_nav_to_nine_decimals(price: u64, decimals: u8) -> Result<u64> {
    if price == 0 {
        return Err(SdkError::Oracle("Nav must be positive".into()));
    }
    let scale = 9_u8
        .checked_sub(decimals)
        .ok_or_else(|| SdkError::Oracle("Price decimals too large".into()))?;
    price
        .checked_mul(10_u64.pow(u32::from(scale)))
        .ok_or(SdkError::MathOverflow)
}

fn normalize_pyth_price_to_nav(price: u64, exponent: i32) -> Result<u64> {
    let adjustment = i64::from(exponent) + 9;
    if adjustment.abs() > MAX_PYTH_EXPONENT_ADJUSTMENT {
        return Err(SdkError::MathOverflow);
    }
    let nav = if adjustment >= 0 {
        let scale = 10_u64
            .checked_pow(adjustment as u32)
            .ok_or(SdkError::MathOverflow)?;
        price.checked_mul(scale).ok_or(SdkError::MathOverflow)?
    } else {
        (u128::from(price) / 10_u128.pow((-adjustment) as u32)) as u64
    };
    if nav == 0 {
        return Err(SdkError::Oracle("Nav must be positive".into()));
    }
    Ok(nav)
}

fn pyth_price_message_offset(data: &[u8]) -> Result<usize> {
    if data.len() < PYTH_FULL_MESSAGE_OFFSET + PYTH_MESSAGE_LENGTH
        || data.get(..8) != Some(PRICE_UPDATE_V2_DISCRIMINATOR.as_slice())
    {
        return Err(SdkError::Oracle("Invalid Pyth price update account".into()));
    }
    if data[PYTH_VERIFICATION_LEVEL_OFFSET] != 1 {
        return Err(SdkError::Oracle("Invalid Pyth verification level".into()));
    }
    Ok(PYTH_FULL_MESSAGE_OFFSET)
}

fn redstone_decimals(data: &[u8]) -> Result<u8> {
    let write_timestamp_length = match data.get(REDSTONE_WRITE_TIMESTAMP_OPTION_OFFSET) {
        Some(0) => 0,
        Some(1) => 8,
        _ => return Err(SdkError::Oracle("Invalid Redstone price account".into())),
    };
    let offset = REDSTONE_WRITE_TIMESTAMP_OPTION_OFFSET + 1 + write_timestamp_length + 8;
    data.get(offset)
        .copied()
        .ok_or_else(|| SdkError::Oracle("Invalid Redstone price account".into()))
}

fn read_redstone_value(data: &[u8]) -> Result<u64> {
    let bytes: &[u8; 32] = data
        .get(REDSTONE_VALUE_OFFSET..REDSTONE_VALUE_OFFSET + 32)
        .and_then(|bytes| bytes.try_into().ok())
        .ok_or_else(|| SdkError::Oracle("Redstone price value overflows u64".into()))?;
    if bytes[..24].iter().any(|byte| *byte != 0) {
        return Err(SdkError::Oracle(
            "Redstone price value overflows u64".into(),
        ));
    }
    let mut value_bytes = [0; 8];
    value_bytes.copy_from_slice(&bytes[24..]);
    Ok(u64::from_be_bytes(value_bytes))
}

fn read_bytes<const N: usize>(data: &[u8], offset: usize, kind: &str) -> Result<[u8; N]> {
    data.get(offset..)
        .and_then(|bytes| bytes.get(..N))
        .and_then(|bytes| bytes.try_into().ok())
        .ok_or_else(|| SdkError::Oracle(format!("{kind} offset out of bounds")))
}

/// Read an unsigned little-endian 64-bit integer at a byte offset.
pub fn read_u64_le(data: &[u8], offset: usize) -> Result<u64> {
    Ok(u64::from_le_bytes(read_bytes(data, offset, "u64")?))
}

/// Read a signed little-endian 64-bit integer at a byte offset.
pub fn read_i64_le(data: &[u8], offset: usize) -> Result<i64> {
    Ok(i64::from_le_bytes(read_bytes(data, offset, "i64")?))
}

/// Read a signed little-endian 32-bit integer at a byte offset.
pub fn read_i32_le(data: &[u8], offset: usize) -> Result<i32> {
    Ok(i32::from_le_bytes(read_bytes(data, offset, "i32")?))
}

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

    const ORACLE: Pubkey = Pubkey::new_from_array([1; 32]);
    const FEED_ID: [u8; 32] = [7; 32];
    const PUBLISH_TIME: i64 = 1_700_000_000;

    fn hardcoded(price: u64, decimals: u8) -> NavData {
        NavData::Hardcoded {
            hardcoded_price: price,
            price_decimals: decimals,
        }
    }

    fn pyth(max_age_secs: u64, max_conf_bps: u16) -> NavData {
        NavData::PythPush {
            pyth_push_account_address: ORACLE,
            feed_id: FEED_ID,
            max_age_secs,
            max_conf_bps,
        }
    }

    fn pyth_fixture(
        price: i64,
        confidence: u64,
        exponent: i32,
        publish_time: i64,
        verification: u8,
    ) -> Vec<u8> {
        let offset = if verification == 0 { 42 } else { 41 };
        let mut data = vec![0; offset + 84 + 8];
        data[..8].copy_from_slice(&PRICE_UPDATE_V2_DISCRIMINATOR);
        data[40] = verification;
        if verification == 0 {
            data[41] = 5;
        }
        data[offset..offset + 32].copy_from_slice(&FEED_ID);
        data[offset + 32..offset + 40].copy_from_slice(&price.to_le_bytes());
        data[offset + 40..offset + 48].copy_from_slice(&confidence.to_le_bytes());
        data[offset + 48..offset + 52].copy_from_slice(&exponent.to_le_bytes());
        data[offset + 52..offset + 60].copy_from_slice(&publish_time.to_le_bytes());
        data
    }

    fn redstone(max_age_secs: u64) -> NavData {
        NavData::RedstonePush {
            price_feed_account: ORACLE,
            feed_id: FEED_ID,
            max_age_secs,
        }
    }

    fn redstone_fixture(
        price: u64,
        timestamp_ms: u64,
        decimals: u8,
        write_timestamp: Option<u64>,
    ) -> Vec<u8> {
        let decimals_offset = if write_timestamp.is_some() { 97 } else { 89 };
        let mut data = vec![0; decimals_offset + 1];
        data[8..40].copy_from_slice(&FEED_ID);
        data[64..72].copy_from_slice(&price.to_be_bytes());
        data[72..80].copy_from_slice(&timestamp_ms.to_le_bytes());
        let slot_offset = if let Some(timestamp) = write_timestamp {
            data[80] = 1;
            data[81..89].copy_from_slice(&timestamp.to_le_bytes());
            89
        } else {
            81
        };
        data[slot_offset..slot_offset + 8].copy_from_slice(&200_u64.to_le_bytes());
        data[decimals_offset] = decimals;
        data
    }

    fn evaluate(item: NavData, data: Vec<u8>, now: Option<i64>) -> Result<u64> {
        calculate_nav(&[item], &HashMap::from([(ORACLE, data)]), 100, now)
    }

    #[test]
    fn readers_preserve_endianness_sign_and_slice_offsets() {
        let mut data = vec![0xff; 24];
        data[1..9].copy_from_slice(&u64::MAX.to_le_bytes());
        data[9..17].copy_from_slice(&(-7_i64).to_le_bytes());
        data[17..21].copy_from_slice(&(-9_i32).to_le_bytes());
        assert_eq!(read_u64_le(&data[1..], 0).unwrap(), u64::MAX);
        assert_eq!(read_i64_le(&data[1..], 8).unwrap(), -7);
        assert_eq!(read_i32_le(&data[1..], 16).unwrap(), -9);
        for length in 0..8 {
            assert!(read_u64_le(&data[..length], 0).is_err());
            assert!(read_i64_le(&data[..length], 0).is_err());
        }
        for length in 0..4 {
            assert!(read_i32_le(&data[..length], 0).is_err());
        }
        assert!(read_u64_le(&data, usize::MAX).is_err());
        assert!(read_i64_le(&data, usize::MAX).is_err());
        assert!(read_i32_le(&data, usize::MAX).is_err());
    }

    #[test]
    fn fixed_and_hardcoded_prices_scale_without_a_clock() {
        let item = NavData::U64FixedAddress {
            nav_account_address: ORACLE,
            nav_price_offset: 4,
            price_decimals: 6,
        };
        let mut data = vec![0; 12];
        data[4..].copy_from_slice(&123_u64.to_le_bytes());
        assert_eq!(evaluate(item.clone(), data.clone(), None).unwrap(), 123_000);
        data.truncate(11);
        assert!(evaluate(item, data, None).is_err());
        assert_eq!(
            calculate_nav(&[hardcoded(2_400_000, 6)], &HashMap::new(), 100, None).unwrap(),
            2_400_000_000
        );
        for item in [hardcoded(0, 9), hardcoded(1, 10)] {
            assert!(matches!(
                calculate_nav(&[item], &HashMap::new(), 100, None),
                Err(SdkError::Oracle(_))
            ));
        }
        assert!(matches!(
            calculate_nav(
                &[hardcoded(u64::MAX / 10 + 1, 8)],
                &HashMap::new(),
                100,
                None
            ),
            Err(SdkError::MathOverflow)
        ));
    }

    #[test]
    fn pyth_requires_full_verification_and_matching_feed_and_discriminator() {
        let full = pyth_fixture(2_500_000, 0, -6, PUBLISH_TIME, 1);
        assert_eq!(
            evaluate(pyth(60, 0), full.clone(), Some(PUBLISH_TIME + 60)).unwrap(),
            2_500_000_000
        );
        for verification in [0, 2] {
            let data = pyth_fixture(2_500_000, 0, -6, PUBLISH_TIME, verification);
            assert!(matches!(
                evaluate(pyth(60, 0), data, Some(PUBLISH_TIME + 60)),
                Err(SdkError::Oracle(_))
            ));
        }
        for offset in [0, 41] {
            let mut data = full.clone();
            data[offset] ^= 0xff;
            assert!(evaluate(pyth(60, 0), data, Some(PUBLISH_TIME + 60)).is_err());
        }
        for length in 0..125 {
            assert!(evaluate(
                pyth(60, 0),
                full[..length].to_vec(),
                Some(PUBLISH_TIME + 60)
            )
            .is_err());
        }
        assert_eq!(
            evaluate(pyth(60, 0), full[..125].to_vec(), Some(PUBLISH_TIME + 60)).unwrap(),
            2_500_000_000
        );
    }

    #[test]
    fn pyth_freshness_requires_a_clock_and_preserves_inclusive_boundary() {
        let data = pyth_fixture(1_000_000_000, 0, -9, PUBLISH_TIME, 1);
        assert!(evaluate(pyth(60, 0), data.clone(), None).is_err());
        assert!(evaluate(pyth(59, 0), data.clone(), Some(PUBLISH_TIME + 60)).is_err());
        assert_eq!(
            evaluate(pyth(60, 0), data.clone(), Some(PUBLISH_TIME + 60)).unwrap(),
            1_000_000_000
        );
        assert_eq!(
            evaluate(pyth(0, 0), data, Some(PUBLISH_TIME - 1)).unwrap(),
            1_000_000_000
        );
        let data = pyth_fixture(1_000_000_000, 0, -9, i64::MIN, 1);
        assert_eq!(
            evaluate(pyth(u64::MAX, 0), data, Some(i64::MAX)).unwrap(),
            1_000_000_000
        );
    }

    #[test]
    fn pyth_confidence_uses_integer_basis_points_and_zero_disables_limit() {
        let evaluate_confidence = |confidence, max_conf_bps| {
            evaluate(
                pyth(60, max_conf_bps),
                pyth_fixture(1_000_000_000, confidence, -9, PUBLISH_TIME, 1),
                Some(PUBLISH_TIME),
            )
        };
        assert_eq!(evaluate_confidence(10_099_999, 100).unwrap(), 1_000_000_000);
        assert!(evaluate_confidence(10_100_000, 100).is_err());
        assert_eq!(evaluate_confidence(u64::MAX, 0).unwrap(), 1_000_000_000);
        assert!(evaluate_confidence(u64::MAX, u16::MAX).is_err());
    }

    #[test]
    fn pyth_normalization_handles_signed_exponents_truncation_and_overflow() {
        for (price, exponent, expected) in [
            (42, 2, 4_200_000_000_000),
            (10_907_689_470_009, -10, 1_090_768_947_000),
            (1_234_567_890, -9, 1_234_567_890),
        ] {
            assert_eq!(
                evaluate(
                    pyth(60, 0),
                    pyth_fixture(price, 0, exponent, PUBLISH_TIME, 1),
                    Some(PUBLISH_TIME)
                )
                .unwrap(),
                expected
            );
        }
        for (price, exponent) in [(0, -9), (-1, -9), (1, -47)] {
            assert!(matches!(
                evaluate(
                    pyth(60, 0),
                    pyth_fixture(price, 0, exponent, PUBLISH_TIME, 1),
                    Some(PUBLISH_TIME)
                ),
                Err(SdkError::Oracle(_))
            ));
        }
        for (price, exponent) in [
            (1, i32::MAX),
            (1, i32::MIN),
            ((u64::MAX / 10 + 1) as i64, -8),
            (1, 29),
        ] {
            assert!(matches!(
                evaluate(
                    pyth(60, 0),
                    pyth_fixture(price, 0, exponent, PUBLISH_TIME, 1),
                    Some(PUBLISH_TIME)
                ),
                Err(SdkError::MathOverflow)
            ));
        }
    }

    #[test]
    fn redstone_reads_big_endian_value_and_both_option_layouts() {
        for write_timestamp in [None, Some(u64::MAX)] {
            let data =
                redstone_fixture(0x01020304, PUBLISH_TIME as u64 * 1_000, 6, write_timestamp);
            assert_eq!(
                evaluate(redstone(60), data.clone(), Some(PUBLISH_TIME)).unwrap(),
                0x01020304 * 1_000
            );
            for length in 0..data.len() {
                assert!(
                    evaluate(redstone(60), data[..length].to_vec(), Some(PUBLISH_TIME)).is_err()
                );
            }
        }
        let mut data = redstone_fixture(1, PUBLISH_TIME as u64 * 1_000, 9, None);
        data[80] = 2;
        assert!(evaluate(redstone(60), data, Some(PUBLISH_TIME)).is_err());
    }

    #[test]
    fn redstone_freshness_uses_whole_seconds_and_rejects_future_prices() {
        let now_ms = PUBLISH_TIME as u64 * 1_000;
        let boundary = redstone_fixture(1_000_000_000, now_ms - 1_000, 9, None);
        assert!(evaluate(redstone(1), boundary, None).is_err());
        for age_ms in [0, 999, 1_000, 1_001, 1_999] {
            let data = redstone_fixture(1_000_000_000, now_ms - age_ms, 9, None);
            assert_eq!(
                evaluate(redstone(1), data, Some(PUBLISH_TIME)).unwrap(),
                1_000_000_000
            );
        }
        for timestamp in [
            now_ms - 2_000,
            now_ms - 2_001,
            now_ms + 1,
            now_ms + 999,
            now_ms + 1_000,
        ] {
            let data = redstone_fixture(1_000_000_000, timestamp, 9, None);
            assert!(evaluate(redstone(1), data, Some(PUBLISH_TIME)).is_err());
        }
        let data = redstone_fixture(1_000_000_000, u64::MAX, 9, None);
        assert_eq!(
            evaluate(redstone(u64::MAX), data, Some(i64::MAX)).unwrap(),
            1_000_000_000
        );
    }

    #[test]
    fn redstone_rejects_wrong_feed_wide_values_and_invalid_prices() {
        let data = redstone_fixture(1_000_000_000, PUBLISH_TIME as u64 * 1_000, 9, None);
        for offset in [8, 40, 63] {
            let mut invalid = data.clone();
            invalid[offset] ^= 1;
            assert!(evaluate(redstone(60), invalid, Some(PUBLISH_TIME)).is_err());
        }
        for (price, decimals) in [(0, 9), (1, 10)] {
            let data = redstone_fixture(price, PUBLISH_TIME as u64 * 1_000, decimals, None);
            assert!(evaluate(redstone(60), data, Some(PUBLISH_TIME)).is_err());
        }
        let data = redstone_fixture(u64::MAX / 10 + 1, PUBLISH_TIME as u64 * 1_000, 8, None);
        assert!(matches!(
            evaluate(redstone(60), data, Some(PUBLISH_TIME)),
            Err(SdkError::MathOverflow)
        ));
    }

    #[test]
    fn aggregation_averages_with_flooring_and_enforces_divergence_boundary() {
        let accounts = HashMap::new();
        assert_eq!(calculate_nav(&[], &accounts, 100, None).unwrap(), 0);
        let feeds = [hardcoded(1_000_000_001, 9), hardcoded(990_000_000, 9)];
        assert_eq!(
            calculate_nav(&feeds, &accounts, 100, None).unwrap(),
            995_000_000
        );
        let feeds = [hardcoded(1_000_000_001, 9), hardcoded(989_999_999, 9)];
        assert_eq!(calculate_nav(&feeds, &accounts, 100, None).unwrap(), 0);
        let feeds = [hardcoded(1, 9), hardcoded(1_000_000_000, 9)];
        assert_eq!(
            calculate_nav(&feeds, &accounts, 10_000, None).unwrap(),
            500_000_000
        );
        assert!(matches!(
            calculate_nav(&feeds, &accounts, 10_001, None),
            Err(SdkError::MathOverflow)
        ));
    }

    #[test]
    fn aggregation_uses_u128_intermediates_and_preserves_maximum_prices() {
        let accounts = HashMap::new();
        for nav in [u64::MAX / 9_900, u64::MAX / 9_900 + 1, u64::MAX] {
            assert_eq!(
                calculate_nav(&[hardcoded(nav, 9)], &accounts, 100, None).unwrap(),
                nav
            );
        }
        let feeds = [hardcoded(u64::MAX, 9), hardcoded(1, 9)];
        assert_eq!(
            calculate_nav(&feeds, &accounts, 10_000, None).unwrap(),
            9_223_372_036_854_775_808
        );
        assert_eq!(calculate_nav(&feeds, &accounts, 100, None).unwrap(), 0);
        for tolerance in [0, 100, 10_000] {
            for feeds in [
                vec![hardcoded(u64::MAX, 9)],
                vec![hardcoded(u64::MAX, 9), hardcoded(u64::MAX, 9)],
            ] {
                assert_eq!(
                    calculate_nav(&feeds, &accounts, tolerance, None).unwrap(),
                    u64::MAX
                );
            }
        }
        let feeds = [hardcoded(u64::MAX, 9), hardcoded(u64::MAX - 1, 9)];
        assert_eq!(
            calculate_nav(&feeds, &accounts, 100, None).unwrap(),
            u64::MAX - 1
        );
    }

    #[test]
    fn missing_accounts_are_errors_for_every_external_source() {
        for item in [
            NavData::U64FixedAddress {
                nav_account_address: ORACLE,
                nav_price_offset: 0,
                price_decimals: 9,
            },
            pyth(60, 0),
            redstone(60),
        ] {
            assert!(calculate_nav(&[item], &HashMap::new(), 100, Some(PUBLISH_TIME)).is_err());
        }
    }

    #[test]
    fn account_resolution_deduplicates_across_kinds_in_first_appearance_order() {
        let second = Pubkey::new_from_array([2; 32]);
        let third = Pubkey::new_from_array([3; 32]);
        let first_config = AssetConfigAccount {
            mint_address: Pubkey::new_from_array([4; 32]),
            nav_data: vec![
                hardcoded(1, 9),
                NavData::U64FixedAddress {
                    nav_account_address: ORACLE,
                    nav_price_offset: 0,
                    price_decimals: 9,
                },
                NavData::RedstonePush {
                    price_feed_account: second,
                    feed_id: FEED_ID,
                    max_age_secs: 60,
                },
            ],
            price_difference_bps: 100,
            paused: false,
            version: 0,
            asset_type: AssetType::Rwa,
            used_in_pairs_count: 0,
            bump: 0,
            padding: vec![],
        };
        let mut second_config = first_config.clone();
        second_config.nav_data = vec![
            pyth(60, 0),
            NavData::U64FixedAddress {
                nav_account_address: third,
                nav_price_offset: 0,
                price_decimals: 9,
            },
            NavData::PythPush {
                pyth_push_account_address: second,
                feed_id: FEED_ID,
                max_age_secs: 60,
                max_conf_bps: 0,
            },
        ];
        assert_eq!(
            resolve_oracle_accounts(&[&first_config, &second_config]),
            vec![
                AccountMeta::new_readonly(ORACLE, false),
                AccountMeta::new_readonly(second, false),
                AccountMeta::new_readonly(third, false),
            ]
        );
        assert_eq!(
            resolve_pyth_oracle_accounts(&[&first_config, &second_config, &second_config]),
            vec![ORACLE, second]
        );
        assert!(resolve_pyth_oracle_accounts(&[&first_config]).is_empty());
        second_config.nav_data = vec![hardcoded(1, 9)];
        assert!(resolve_oracle_accounts(&[&second_config]).is_empty());
    }

    #[tokio::test]
    async fn rpc_pyth_owner_is_authenticated_without_changing_raw_nav_evaluation() {
        use crate::{
            constants::PYTH_RECEIVER_PROGRAM_ADDRESS,
            quote_core::{compute_swap_quote, test_support::Fixture},
        };

        let mut fixture = Fixture::new();
        fixture.fee.nav_data = vec![pyth(60, 0)];
        let bytes = pyth_fixture(2_500_000, 0, -6, PUBLISH_TIME, 1);
        fixture.oracles.insert(ORACLE, bytes.clone());
        let mut rpc = fixture.rpc();
        rpc.block_times.insert(50, PUBLISH_TIME);
        rpc.accounts.get_mut(&ORACLE).unwrap().owner = fixture.program;
        assert!(matches!(
            compute_swap_quote(&rpc, &fixture.params, &fixture.program).await,
            Err(SdkError::Oracle(message)) if message.contains("Invalid Pyth account owner")
        ));
        rpc.accounts.get_mut(&ORACLE).unwrap().owner = PYTH_RECEIVER_PROGRAM_ADDRESS;
        let quote = compute_swap_quote(&rpc, &fixture.params, &fixture.program)
            .await
            .unwrap();
        assert_eq!(quote.fee_token_nav, 2_500_000_000);
        assert_eq!(
            evaluate(pyth(60, 0), bytes, Some(PUBLISH_TIME)).unwrap(),
            2_500_000_000
        );
    }

    #[tokio::test]
    async fn rpc_redstone_and_fixed_address_feeds_accept_arbitrary_owners() {
        use crate::quote_core::{fetch_oracle_account_data_map, test_support::Fixture};

        let fixed = Pubkey::new_from_array([17; 32]);
        let mut fixture = Fixture::new();
        fixture.input.nav_data = vec![
            redstone(60),
            NavData::U64FixedAddress {
                nav_account_address: fixed,
                nav_price_offset: 0,
                price_decimals: 9,
            },
        ];
        fixture.oracles.insert(
            ORACLE,
            redstone_fixture(1_000_000_000, PUBLISH_TIME as u64 * 1_000, 9, None),
        );
        fixture
            .oracles
            .insert(fixed, 1_000_000_000_u64.to_le_bytes().to_vec());
        let mut rpc = fixture.rpc();
        rpc.accounts.get_mut(&ORACLE).unwrap().owner = Pubkey::new_from_array([18; 32]);
        rpc.accounts.get_mut(&fixed).unwrap().owner = Pubkey::new_from_array([19; 32]);
        let configs = [&fixture.input];
        let addresses: Vec<_> = resolve_oracle_accounts(&configs)
            .into_iter()
            .map(|account| account.pubkey)
            .collect();
        let data = fetch_oracle_account_data_map(
            &rpc,
            &addresses,
            &resolve_pyth_oracle_accounts(&configs),
        )
        .await
        .unwrap();
        for source in &fixture.input.nav_data {
            assert_eq!(
                calculate_nav(std::slice::from_ref(source), &data, 100, Some(PUBLISH_TIME))
                    .unwrap(),
                1_000_000_000
            );
        }
    }
}