evm-oracle-state 0.2.0

EVM-backed Chainlink-style oracle state tracking over evm-fork-cache
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
use std::{
    cell::RefCell,
    collections::{BTreeMap, BTreeSet},
    time::{SystemTime, UNIX_EPOCH},
};

#[cfg(feature = "aave")]
use alloy_primitives::I256;
use alloy_primitives::{Address, Bytes, U256};
use alloy_sol_types::{SolCall, sol};
use evm_fork_cache::{
    cache::EvmCache,
    multicall::{IMulticall3, MULTICALL3_ADDRESS, execute_batched, try_decode_result},
};

use crate::{
    AggregatorLayoutEvidence, ChainlinkFeedProvider, Feed, FeedConfig, FeedId, FeedMetadata,
    FeedRegistration, FeedSource, OracleError, OracleFeedStatus, OracleRegistry, OracleTracker,
    ProviderFuture, RoundData, registry::derive_feed_id,
};

sol! {
    interface AggregatorProxyInterface {
        function latestRoundData() external view returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
        function decimals() external view returns (uint8);
        function description() external view returns (string);
        function version() external view returns (uint256);
        function aggregator() external view returns (address);
        function typeAndVersion() external view returns (string);
    }
}

use AggregatorProxyInterface::{
    aggregatorCall, decimalsCall, descriptionCall, latestRoundDataCall, typeAndVersionCall,
    versionCall,
};

#[derive(Debug)]
struct ChainlinkCoreRead {
    decimals: u8,
    description: String,
    version: U256,
    round: RoundData,
    aggregator: Option<Address>,
}

#[cfg(feature = "aave")]
sol! {
    interface AaveOracleInterface {
        function getSourceOfAsset(address asset) external view returns (address);
    }

    interface AavePriceCapAdapterStableInterface {
        function ASSET_TO_USD_AGGREGATOR() external view returns (address);
        function getPriceCap() external view returns (int256);
        function decimals() external view returns (uint8);
        function description() external view returns (string);
        function latestAnswer() external view returns (int256);
    }

    interface AaveRatioCapAdapterInterface {
        function BASE_TO_USD_AGGREGATOR() external view returns (address);
        function RATIO_PROVIDER() external view returns (address);
        function RATIO_DECIMALS() external view returns (uint8);
        function getRatio() external view returns (int256);
        function isCapped() external view returns (bool);
        function decimals() external view returns (uint8);
        function description() external view returns (string);
        function latestAnswer() external view returns (int256);
    }

    interface AaveSynchronicityPegToBaseInterface {
        function ASSET_TO_PEG() external view returns (address);
        function PEG_TO_BASE() external view returns (address);
        function decimals() external view returns (uint8);
        function description() external view returns (string);
        function latestAnswer() external view returns (int256);
    }

    interface AaveFixedPriceSourceInterface {
        function price() external view returns (int256);
        function decimals() external view returns (uint8);
        function description() external view returns (string);
        function latestAnswer() external view returns (int256);
    }

    interface AaveConstantPriceSourceInterface {
        function PRICE() external view returns (int256);
    }

    interface AaveBaseToPegProbeInterface {
        function BASE_TO_PEG() external view returns (address);
    }

    interface AaveDynamicSourceProbeInterface {
        function REFERENCE_FEED() external view returns (address);
        function DISCOUNT_RATE() external view returns (uint256);
        function discount() external view returns (uint256);
        function EXCHANGE_RATE() external view returns (uint256);
        function PENDLE_PRINCIPAL_TOKEN() external view returns (address);
        function PENDLE_ORACLE() external view returns (address);
    }
}

#[cfg(feature = "aave")]
use AaveBaseToPegProbeInterface::BASE_TO_PEGCall;
#[cfg(feature = "aave")]
use AaveConstantPriceSourceInterface::PRICECall;
#[cfg(feature = "aave")]
use AaveDynamicSourceProbeInterface::{
    DISCOUNT_RATECall, EXCHANGE_RATECall, PENDLE_ORACLECall, PENDLE_PRINCIPAL_TOKENCall,
    REFERENCE_FEEDCall, discountCall,
};
#[cfg(feature = "aave")]
use AaveFixedPriceSourceInterface::{
    decimalsCall as aaveFixedDecimalsCall, descriptionCall as aaveFixedDescriptionCall,
    latestAnswerCall as aaveFixedLatestAnswerCall, priceCall as aaveFixedPriceCall,
};
#[cfg(feature = "aave")]
use AaveOracleInterface::getSourceOfAssetCall;
#[cfg(feature = "aave")]
use AavePriceCapAdapterStableInterface::{
    ASSET_TO_USD_AGGREGATORCall, decimalsCall as aaveDecimalsCall,
    descriptionCall as aaveDescriptionCall, getPriceCapCall, latestAnswerCall,
};
#[cfg(feature = "aave")]
use AaveRatioCapAdapterInterface::{
    BASE_TO_USD_AGGREGATORCall, RATIO_DECIMALSCall, RATIO_PROVIDERCall,
    decimalsCall as aaveRatioDecimalsCall, descriptionCall as aaveRatioDescriptionCall,
    getRatioCall, isCappedCall, latestAnswerCall as aaveRatioLatestAnswerCall,
};
#[cfg(feature = "aave")]
use AaveSynchronicityPegToBaseInterface::{
    ASSET_TO_PEGCall, PEG_TO_BASECall, decimalsCall as aaveSynchronicityDecimalsCall,
    descriptionCall as aaveSynchronicityDescriptionCall,
    latestAnswerCall as aaveSynchronicityLatestAnswerCall,
};

#[cfg(feature = "aave")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AavePriceCapStableSource {
    pub(crate) underlying_proxy: Address,
    pub(crate) price_cap: I256,
    pub(crate) decimals: u8,
    pub(crate) description: String,
    pub(crate) latest_answer: I256,
}

#[cfg(feature = "aave")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AaveRatioCapSource {
    pub(crate) base_to_usd_proxy: Address,
    pub(crate) ratio_provider: Address,
    pub(crate) current_ratio: I256,
    pub(crate) is_capped: bool,
    pub(crate) ratio_decimals: u8,
    pub(crate) decimals: u8,
    pub(crate) description: String,
    pub(crate) latest_answer: I256,
}

#[cfg(feature = "aave")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AaveSynchronicityPegToBaseSource {
    pub(crate) asset_to_peg_proxy: Address,
    pub(crate) peg_to_base_proxy: Address,
    pub(crate) decimals: u8,
    pub(crate) description: String,
    pub(crate) latest_answer: I256,
}

#[cfg(feature = "aave")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AaveFixedPriceSource {
    pub(crate) decimals: u8,
    pub(crate) description: String,
    pub(crate) latest_answer: I256,
}

/// Chainlink view reader backed by an `evm-fork-cache` fork cache.
pub struct EvmCacheChainlinkReader<'a> {
    cache: RefCell<&'a mut EvmCache>,
    multicall_reads: bool,
}

impl<'a> EvmCacheChainlinkReader<'a> {
    /// Create a reader around an existing mutable EVM cache.
    pub fn new(cache: &'a mut EvmCache) -> Self {
        Self {
            cache: RefCell::new(cache),
            multicall_reads: true,
        }
    }

    /// Create a reader with direct/fork Multicall3 view batching disabled.
    pub fn without_multicall(cache: &'a mut EvmCache) -> Self {
        Self {
            cache: RefCell::new(cache),
            multicall_reads: false,
        }
    }

    /// Enable or disable direct/fork Multicall3 view batching.
    pub fn with_multicall_reads(mut self, enabled: bool) -> Self {
        self.multicall_reads = enabled;
        self
    }

    /// Register a typed feed into an existing oracle registry.
    pub async fn register_feed(
        &self,
        registry: &mut OracleRegistry,
        feed: Feed,
    ) -> Result<FeedId, OracleError> {
        let config = FeedConfig::try_from(feed)?;
        self.register_config(registry, config).await
    }

    /// Register multiple Chainlink-compatible feeds, batching proxy reads when possible.
    pub async fn register_feeds(
        &self,
        registry: &mut OracleRegistry,
        feeds: Vec<Feed>,
    ) -> Result<Vec<OracleAdapterFeedSkip>, OracleError> {
        let mut prepared = Vec::with_capacity(feeds.len());
        for feed in feeds {
            let proxy = feed.proxy().unwrap_or_default();
            let config = FeedConfig::try_from(feed.clone())?;
            let read_proxy = FeedSource::Chainlink.read_proxy(config.proxy);
            prepared.push((feed, config, proxy, read_proxy));
        }

        let read_proxies = prepared
            .iter()
            .map(|(_, _, _, read_proxy)| *read_proxy)
            .collect::<Vec<_>>();
        let mut cores = self
            .read_chainlink_cores_multicall(&read_proxies)
            .unwrap_or_default();
        let mut layouts = self.layout_evidence_for_cores(&cores);

        let mut skipped = Vec::new();
        for (index, (feed, config, proxy, read_proxy)) in prepared.into_iter().enumerate() {
            let mut from_batched_core = false;
            let core = match cores.get_mut(index).and_then(Option::take) {
                Some(Ok(core)) => {
                    from_batched_core = true;
                    Ok(core)
                }
                Some(Err(error)) => Err(error),
                None => self.read_chainlink_core(read_proxy),
            };

            match core {
                Ok(core) => {
                    if from_batched_core {
                        if let Some(layouts) = layouts.as_mut() {
                            let layout = layouts.get_mut(index).and_then(Option::take);
                            self.insert_config_core_with_layout(registry, config, core, layout)?;
                        } else {
                            self.insert_config_core(registry, config, core).await?;
                        }
                    } else {
                        self.insert_config_core(registry, config, core).await?;
                    }
                }
                Err(OracleError::Provider(error)) => {
                    skipped.push(OracleAdapterFeedSkip {
                        feed,
                        proxy,
                        reason: OracleAdapterSkipReason::NotChainlinkCompatible { error },
                    });
                }
                // A proxy whose reads decode but whose values do not fit the
                // crate's typed round representation is equally not usable as
                // a Chainlink-compatible feed: classify it as a skip instead
                // of failing the whole best-effort registration batch.
                Err(error @ OracleError::Decode(_)) => {
                    skipped.push(OracleAdapterFeedSkip {
                        feed,
                        proxy,
                        reason: OracleAdapterSkipReason::NotChainlinkCompatible {
                            error: error.to_string(),
                        },
                    });
                }
                Err(error) => return Err(error),
            }
        }

        Ok(skipped)
    }

    /// Register a Chainlink-compatible feed config into an existing registry.
    pub async fn register_config(
        &self,
        registry: &mut OracleRegistry,
        config: FeedConfig,
    ) -> Result<FeedId, OracleError> {
        let source = FeedSource::Chainlink;
        let read_proxy = source.read_proxy(config.proxy);
        let core = self.read_chainlink_core(read_proxy)?;
        self.insert_config_core(registry, config, core).await
    }

    fn layout_evidence_for_cores(
        &self,
        cores: &[Option<Result<ChainlinkCoreRead, OracleError>>],
    ) -> Option<Vec<Option<AggregatorLayoutEvidence>>> {
        let mut aggregators = Vec::new();
        let mut seen_aggregators = BTreeSet::new();
        for core in cores.iter().filter_map(|core| match core {
            Some(Ok(core)) => core.aggregator,
            _ => None,
        }) {
            if seen_aggregators.insert(core) {
                aggregators.push(core);
            }
        }
        if aggregators.is_empty() {
            return Some(vec![None; cores.len()]);
        }

        let mut type_and_versions = self.read_type_and_versions_multicall(&aggregators)?;
        let mut evidence_by_aggregator = BTreeMap::new();
        for (index, aggregator) in aggregators.iter().copied().enumerate() {
            let evidence = type_and_versions
                .get_mut(index)
                .and_then(Option::take)
                .map(|type_and_version| {
                    AggregatorLayoutEvidence::from_type_and_version(
                        aggregator,
                        type_and_version,
                        None,
                    )
                })
                .unwrap_or_else(|| AggregatorLayoutEvidence::unknown(aggregator, None));
            evidence_by_aggregator.insert(aggregator, evidence);
        }

        Some(
            cores
                .iter()
                .map(|core| {
                    let aggregator = match core {
                        Some(Ok(core)) => core.aggregator?,
                        _ => return None,
                    };
                    evidence_by_aggregator.get(&aggregator).cloned()
                })
                .collect(),
        )
    }

    async fn insert_config_core(
        &self,
        registry: &mut OracleRegistry,
        config: FeedConfig,
        core: ChainlinkCoreRead,
    ) -> Result<FeedId, OracleError> {
        let aggregator_layout = registry
            .detect_aggregator_layout(self, core.aggregator, None)
            .await;
        self.insert_config_core_with_layout(registry, config, core, aggregator_layout)
    }

    fn insert_config_core_with_layout(
        &self,
        registry: &mut OracleRegistry,
        config: FeedConfig,
        core: ChainlinkCoreRead,
        aggregator_layout: Option<AggregatorLayoutEvidence>,
    ) -> Result<FeedId, OracleError> {
        let id = config
            .id
            .unwrap_or_else(|| derive_feed_id(config.label.as_deref(), config.proxy));
        let source = FeedSource::Chainlink;
        let registration = FeedRegistration {
            id: id.clone(),
            proxy: config.proxy,
            label: config.label,
            base: config.base,
            quote: config.quote,
            staleness: config.staleness,
            current_aggregator: core.aggregator,
            aggregator_layout,
            metadata: FeedMetadata {
                decimals: core.decimals,
                description: core.description,
                version: core.version,
            },
            source,
            status: OracleFeedStatus::Ready,
        };
        registry.insert_seeded_registration(registration, core.round)?;
        Ok(id)
    }

    /// Read `decimals()` from a Chainlink-compatible proxy.
    pub fn read_decimals(&self, proxy: Address) -> Result<u8, OracleError> {
        self.cache
            .borrow_mut()
            .call_sol(proxy, decimalsCall {})
            .map_err(provider_error)
    }

    /// Read `description()` from a Chainlink-compatible proxy.
    pub fn read_description(&self, proxy: Address) -> Result<String, OracleError> {
        self.cache
            .borrow_mut()
            .call_sol(proxy, descriptionCall {})
            .map_err(provider_error)
    }

    /// Read `version()` from a Chainlink-compatible proxy.
    pub fn read_version(&self, proxy: Address) -> Result<U256, OracleError> {
        self.cache
            .borrow_mut()
            .call_sol(proxy, versionCall {})
            .map_err(provider_error)
    }

    /// Read `latestRoundData()` from a Chainlink-compatible proxy.
    pub fn read_latest_round_data(&self, proxy: Address) -> Result<RoundData, OracleError> {
        let round = self
            .cache
            .borrow_mut()
            .call_sol(proxy, latestRoundDataCall {})
            .map_err(provider_error)?;
        round_from_raw(round)
    }

    /// Best-effort read of the proxy's current aggregator.
    pub fn read_aggregator(&self, proxy: Address) -> Result<Option<Address>, OracleError> {
        let aggregator = self
            .cache
            .borrow_mut()
            .call_sol(proxy, aggregatorCall {})
            .map_err(provider_error)?;
        Ok(Some(aggregator))
    }

    /// Best-effort read of an aggregator implementation `typeAndVersion()`.
    pub fn read_type_and_version(
        &self,
        aggregator: Address,
    ) -> Result<Option<String>, OracleError> {
        let type_and_version = self
            .cache
            .borrow_mut()
            .call_sol(aggregator, typeAndVersionCall {})
            .map_err(provider_error)?;
        Ok(Some(type_and_version))
    }

    fn read_chainlink_core(&self, proxy: Address) -> Result<ChainlinkCoreRead, OracleError> {
        if let Some(read) = self.read_chainlink_core_multicall(proxy) {
            return read;
        }

        Ok(ChainlinkCoreRead {
            decimals: self.read_decimals(proxy)?,
            description: self.read_description(proxy)?,
            version: self.read_version(proxy)?,
            round: self.read_latest_round_data(proxy)?,
            aggregator: self.read_aggregator(proxy)?,
        })
    }

    fn read_chainlink_core_multicall(
        &self,
        proxy: Address,
    ) -> Option<Result<ChainlinkCoreRead, OracleError>> {
        let results = self.execute_multicall([
            multicall_call(proxy, decimalsCall {}, true),
            multicall_call(proxy, descriptionCall {}, true),
            multicall_call(proxy, versionCall {}, true),
            multicall_call(proxy, latestRoundDataCall {}, true),
            multicall_call(proxy, aggregatorCall {}, true),
        ])?;
        if results.len() != 5 {
            return None;
        }

        let decimals = try_decode_result::<decimalsCall>(&results[0])?;
        let description = try_decode_result::<descriptionCall>(&results[1])?;
        let version = try_decode_result::<versionCall>(&results[2])?;
        let raw_round = try_decode_result::<latestRoundDataCall>(&results[3])?;
        let aggregator = try_decode_result::<aggregatorCall>(&results[4]);
        let round = match round_from_raw(raw_round) {
            Ok(round) => round,
            Err(error) => return Some(Err(error)),
        };
        Some(Ok(ChainlinkCoreRead {
            decimals,
            description,
            version,
            round,
            aggregator,
        }))
    }

    fn read_chainlink_cores_multicall(
        &self,
        proxies: &[Address],
    ) -> Option<Vec<Option<Result<ChainlinkCoreRead, OracleError>>>> {
        let calls = proxies
            .iter()
            .flat_map(|proxy| {
                [
                    multicall_call(*proxy, decimalsCall {}, true),
                    multicall_call(*proxy, descriptionCall {}, true),
                    multicall_call(*proxy, versionCall {}, true),
                    multicall_call(*proxy, latestRoundDataCall {}, true),
                    multicall_call(*proxy, aggregatorCall {}, true),
                ]
            })
            .collect::<Vec<_>>();
        let results = self.execute_multicall(calls)?;
        if results.len() != proxies.len() * 5 {
            return None;
        }

        let mut cores = Vec::with_capacity(proxies.len());
        for chunk in results.chunks_exact(5) {
            let decimals = try_decode_result::<decimalsCall>(&chunk[0]);
            let description = try_decode_result::<descriptionCall>(&chunk[1]);
            let version = try_decode_result::<versionCall>(&chunk[2]);
            let raw_round = try_decode_result::<latestRoundDataCall>(&chunk[3]);
            let aggregator = try_decode_result::<aggregatorCall>(&chunk[4]);
            let Some((decimals, description, version, raw_round)) =
                decimals.zip(description).zip(version).zip(raw_round).map(
                    |(((decimals, description), version), raw_round)| {
                        (decimals, description, version, raw_round)
                    },
                )
            else {
                cores.push(None);
                continue;
            };

            let round = match round_from_raw(raw_round) {
                Ok(round) => round,
                Err(error) => {
                    cores.push(Some(Err(error)));
                    continue;
                }
            };
            cores.push(Some(Ok(ChainlinkCoreRead {
                decimals,
                description,
                version,
                round,
                aggregator,
            })));
        }
        Some(cores)
    }

    fn read_type_and_versions_multicall(
        &self,
        aggregators: &[Address],
    ) -> Option<Vec<Option<String>>> {
        let calls = aggregators
            .iter()
            .map(|aggregator| multicall_call(*aggregator, typeAndVersionCall {}, true))
            .collect::<Vec<_>>();
        let results = self.execute_multicall(calls)?;
        if results.len() != aggregators.len() {
            return None;
        }
        Some(
            results
                .iter()
                .map(try_decode_result::<typeAndVersionCall>)
                .collect(),
        )
    }

    fn execute_multicall<I>(&self, calls: I) -> Option<Vec<IMulticall3::Result>>
    where
        I: IntoIterator<Item = (Address, Bytes, bool)>,
    {
        if !self.multicall_reads {
            return None;
        }
        let calls = calls.into_iter().collect::<Vec<_>>();
        if calls.is_empty() {
            return Some(Vec::new());
        }
        if let Some(results) = self.execute_direct_rpc_multicall(&calls) {
            return Some(results);
        }
        let mut cache = self.cache.borrow_mut();
        execute_batched(&mut cache, calls).ok()
    }

    fn execute_direct_rpc_multicall(
        &self,
        calls: &[(Address, Bytes, bool)],
    ) -> Option<Vec<IMulticall3::Result>> {
        let calls = calls
            .iter()
            .map(|(target, call_data, allow_failure)| IMulticall3::Call3 {
                target: *target,
                allowFailure: *allow_failure,
                callData: call_data.clone(),
            })
            .collect::<Vec<_>>();
        let call = IMulticall3::aggregate3Call { calls };
        let cache = self.cache.borrow();
        let bytes = cache
            .rpc_call(MULTICALL3_ADDRESS, Bytes::from(call.abi_encode()))
            .and_then(Result::ok)?;
        IMulticall3::aggregate3Call::abi_decode_returns(&bytes).ok()
    }

    #[cfg(feature = "aave")]
    pub(crate) fn read_aave_source(
        &self,
        oracle: Address,
        asset: Address,
    ) -> Result<Address, OracleError> {
        self.cache
            .borrow_mut()
            .call_sol(oracle, getSourceOfAssetCall { asset })
            .map_err(provider_error)
    }

    #[cfg(feature = "aave")]
    pub(crate) fn read_aave_price_cap_stable(
        &self,
        source: Address,
    ) -> Result<AavePriceCapStableSource, OracleError> {
        let underlying_proxy = self
            .cache
            .borrow_mut()
            .call_sol(source, ASSET_TO_USD_AGGREGATORCall {})
            .map_err(provider_error)?;
        let price_cap = self
            .cache
            .borrow_mut()
            .call_sol(source, getPriceCapCall {})
            .map_err(provider_error)?;
        let decimals = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveDecimalsCall {})
            .map_err(provider_error)?;
        let description = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveDescriptionCall {})
            .map_err(provider_error)?;
        let latest_answer = self
            .cache
            .borrow_mut()
            .call_sol(source, latestAnswerCall {})
            .map_err(provider_error)?;

        Ok(AavePriceCapStableSource {
            underlying_proxy,
            price_cap,
            decimals,
            description,
            latest_answer,
        })
    }

    #[cfg(feature = "aave")]
    pub(crate) fn read_aave_ratio_cap(
        &self,
        source: Address,
    ) -> Result<AaveRatioCapSource, OracleError> {
        let base_to_usd_proxy = self
            .cache
            .borrow_mut()
            .call_sol(source, BASE_TO_USD_AGGREGATORCall {})
            .map_err(provider_error)?;
        let ratio_provider = self
            .cache
            .borrow_mut()
            .call_sol(source, RATIO_PROVIDERCall {})
            .map_err(provider_error)?;
        let current_ratio = self
            .cache
            .borrow_mut()
            .call_sol(source, getRatioCall {})
            .map_err(provider_error)?;
        let is_capped = self
            .cache
            .borrow_mut()
            .call_sol(source, isCappedCall {})
            .map_err(provider_error)?;
        let ratio_decimals = self
            .cache
            .borrow_mut()
            .call_sol(source, RATIO_DECIMALSCall {})
            .map_err(provider_error)?;
        let decimals = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveRatioDecimalsCall {})
            .map_err(provider_error)?;
        let description = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveRatioDescriptionCall {})
            .map_err(provider_error)?;
        let latest_answer = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveRatioLatestAnswerCall {})
            .map_err(provider_error)?;

        Ok(AaveRatioCapSource {
            base_to_usd_proxy,
            ratio_provider,
            current_ratio,
            is_capped,
            ratio_decimals,
            decimals,
            description,
            latest_answer,
        })
    }

    #[cfg(feature = "aave")]
    pub(crate) fn read_aave_synchronicity_peg_to_base(
        &self,
        source: Address,
    ) -> Result<AaveSynchronicityPegToBaseSource, OracleError> {
        let asset_to_peg_proxy = self
            .cache
            .borrow_mut()
            .call_sol(source, ASSET_TO_PEGCall {})
            .map_err(provider_error)?;
        let peg_to_base_proxy = self
            .cache
            .borrow_mut()
            .call_sol(source, PEG_TO_BASECall {})
            .map_err(provider_error)?;
        let decimals = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveSynchronicityDecimalsCall {})
            .map_err(provider_error)?;
        let description = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveSynchronicityDescriptionCall {})
            .map_err(provider_error)?;
        let latest_answer = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveSynchronicityLatestAnswerCall {})
            .map_err(provider_error)?;

        Ok(AaveSynchronicityPegToBaseSource {
            asset_to_peg_proxy,
            peg_to_base_proxy,
            decimals,
            description,
            latest_answer,
        })
    }

    #[cfg(feature = "aave")]
    pub(crate) fn read_aave_fixed_price(
        &self,
        source: Address,
    ) -> Result<AaveFixedPriceSource, OracleError> {
        if self.has_known_aave_dependency_or_config(source) {
            return Err(OracleError::Unsupported(
                "source exposes dependency/config view(s); not fixed-price".to_string(),
            ));
        }
        let fixed_price = self.read_fixed_price_value(source)?;
        let decimals = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveFixedDecimalsCall {})
            .map_err(provider_error)?;
        let description = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveFixedDescriptionCall {})
            .map_err(provider_error)?;
        let latest_answer = self
            .cache
            .borrow_mut()
            .call_sol(source, aaveFixedLatestAnswerCall {})
            .map_err(provider_error)?;
        if latest_answer != fixed_price {
            return Err(OracleError::Unsupported(
                "latestAnswer() does not match fixed price getter".to_string(),
            ));
        }

        Ok(AaveFixedPriceSource {
            decimals,
            description,
            latest_answer,
        })
    }

    #[cfg(feature = "aave")]
    fn read_fixed_price_value(&self, source: Address) -> Result<I256, OracleError> {
        match self
            .cache
            .borrow_mut()
            .call_sol(source, aaveFixedPriceCall {})
        {
            Ok(price) => Ok(price),
            Err(price_error) => match self.cache.borrow_mut().call_sol(source, PRICECall {}) {
                Ok(price) => Ok(price),
                Err(constant_error) => Err(OracleError::Unsupported(format!(
                    "missing fixed-price getter price() ({price_error:?}) or PRICE() ({constant_error:?})"
                ))),
            },
        }
    }

    #[cfg(feature = "aave")]
    fn has_known_aave_dependency_or_config(&self, source: Address) -> bool {
        self.cache
            .borrow_mut()
            .call_sol(source, ASSET_TO_USD_AGGREGATORCall {})
            .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, BASE_TO_USD_AGGREGATORCall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, ASSET_TO_PEGCall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, PEG_TO_BASECall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, BASE_TO_PEGCall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, REFERENCE_FEEDCall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, DISCOUNT_RATECall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, discountCall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, EXCHANGE_RATECall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, PENDLE_PRINCIPAL_TOKENCall {})
                .is_ok()
            || self
                .cache
                .borrow_mut()
                .call_sol(source, PENDLE_ORACLECall {})
                .is_ok()
    }
}

impl ChainlinkFeedProvider for EvmCacheChainlinkReader<'_> {
    fn decimals(&self, proxy: Address) -> ProviderFuture<'_, u8> {
        let result = self.read_decimals(proxy);
        Box::pin(async move { result })
    }

    fn description(&self, proxy: Address) -> ProviderFuture<'_, String> {
        let result = self.read_description(proxy);
        Box::pin(async move { result })
    }

    fn version(&self, proxy: Address) -> ProviderFuture<'_, U256> {
        let result = self.read_version(proxy);
        Box::pin(async move { result })
    }

    fn latest_round_data(&self, proxy: Address) -> ProviderFuture<'_, RoundData> {
        let result = self.read_latest_round_data(proxy);
        Box::pin(async move { result })
    }

    fn aggregator(&self, proxy: Address) -> ProviderFuture<'_, Option<Address>> {
        let result = self.read_aggregator(proxy).or(Ok(None));
        Box::pin(async move { result })
    }

    fn aggregator_type_and_version(
        &self,
        aggregator: Address,
    ) -> ProviderFuture<'_, Option<String>> {
        let result = self.read_type_and_version(aggregator).or(Ok(None));
        Box::pin(async move { result })
    }
}

/// Cache-native oracle adapter entry point.
pub struct OracleAdapter;

impl OracleAdapter {
    /// Start building a cache-backed oracle tracker.
    pub fn builder() -> OracleAdapterBuilder {
        OracleAdapterBuilder::default()
    }
}

/// Builder for cache-backed oracle tracker registration.
#[derive(Clone, Debug)]
pub struct OracleAdapterBuilder {
    feeds: Vec<Feed>,
    now_timestamp: Option<u64>,
    multicall_reads: bool,
}

impl Default for OracleAdapterBuilder {
    fn default() -> Self {
        Self {
            feeds: Vec::new(),
            now_timestamp: None,
            multicall_reads: true,
        }
    }
}

/// Best-effort cache-native oracle registration report.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct OracleAdapterBuildReport {
    /// Tracker containing every successfully registered feed.
    pub tracker: OracleTracker,
    /// Feeds that were skipped because the source could not be registered.
    pub skipped: Vec<OracleAdapterFeedSkip>,
}

/// Feed skipped during best-effort cache-native registration.
#[derive(Clone, Debug)]
pub struct OracleAdapterFeedSkip {
    /// Feed definition supplied by the caller.
    pub feed: Feed,
    /// Proxy/source address that failed registration.
    pub proxy: Address,
    /// Classified skip reason.
    pub reason: OracleAdapterSkipReason,
}

/// Complete description of one adapter feed skip, carried by
/// [`OracleError::FeedSkipped`] when a fail-fast `build` surfaces a skip as an
/// error. Use the `build_report` methods to receive skips as data instead.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OracleFeedSkip {
    /// Stable feed id, when the caller supplied one.
    pub feed_id: Option<FeedId>,
    /// Human-readable feed label, when the caller supplied one.
    pub label: Option<String>,
    /// Proxy/source address that failed registration.
    pub proxy: Address,
    /// Classified skip reason.
    pub reason: OracleAdapterSkipReason,
}

impl OracleFeedSkip {
    pub(crate) fn from_adapter_skip(skipped: &OracleAdapterFeedSkip) -> Self {
        Self {
            feed_id: skipped.feed.id(),
            label: skipped.feed.label().map(str::to_string),
            proxy: skipped.proxy,
            reason: skipped.reason.clone(),
        }
    }

    fn display_name(&self) -> &str {
        self.label
            .as_deref()
            .or_else(|| self.feed_id.as_ref().map(|id| id.as_str()))
            .unwrap_or("unknown")
    }
}

impl std::fmt::Display for OracleFeedSkip {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "adapter feed `{}` (proxy {:?}) was skipped: {}",
            self.display_name(),
            self.proxy,
            self.reason
        )
    }
}

/// Classified reason for skipping a feed in best-effort registration.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OracleAdapterSkipReason {
    /// The source did not expose the Chainlink proxy methods required by this crate.
    NotChainlinkCompatible {
        /// Underlying read/decode error.
        error: String,
    },
    /// The Aave oracle source variant is not supported by this MVP.
    UnsupportedAaveSource {
        /// Classified discovery or compatibility error.
        error: String,
    },
    /// The Morpho oracle source variant is not supported by this adapter.
    UnsupportedMorphoSource {
        /// Classified discovery or compatibility error.
        error: String,
    },
    /// The Euler oracle source variant is not supported by this adapter.
    UnsupportedEulerSource {
        /// Classified discovery or compatibility error.
        error: String,
    },
    /// The RedStone push source variant is not supported by this adapter.
    #[cfg(feature = "redstone")]
    UnsupportedRedstoneSource {
        /// Classified discovery or compatibility error.
        error: String,
    },
}

impl OracleAdapterBuilder {
    /// Add one typed feed registration.
    pub fn feed(mut self, feed: Feed) -> Self {
        self.feeds.push(feed);
        self
    }

    /// Add multiple typed feed registrations.
    pub fn feeds(mut self, feeds: impl IntoIterator<Item = Feed>) -> Self {
        self.feeds.extend(feeds);
        self
    }

    /// Set a fixed timestamp for deterministic registration status classification.
    pub fn now_timestamp(mut self, now_timestamp: u64) -> Self {
        self.now_timestamp = Some(now_timestamp);
        self
    }

    /// Enable or disable direct/fork Multicall3 batching for cache-native Chainlink view reads.
    ///
    /// Enabled by default. When enabled, feed registration first batches proxy
    /// `decimals`, `description`, `version`, `latestRoundData`, `aggregator`,
    /// and aggregator `typeAndVersion` reads through direct RPC Multicall3,
    /// falling back to fork-cache Multicall3 and then sequential cache calls
    /// when direct RPC batching cannot be used.
    pub fn multicall_reads(mut self, enabled: bool) -> Self {
        self.multicall_reads = enabled;
        self
    }

    /// Disable direct/fork Multicall3 view batching for cache-native Chainlink registration.
    pub fn disable_multicall_reads(self) -> Self {
        self.multicall_reads(false)
    }

    /// Register feeds from cache reads and return a typed tracker.
    ///
    /// # Errors
    ///
    /// Returns [`OracleError::FeedSkipped`] when any feed could not be
    /// registered (use [`Self::build_report`] to receive skips as data),
    /// [`OracleError::DuplicateFeedId`]/[`OracleError::DuplicateProxy`] when
    /// two feeds collide, and [`OracleError::Config`] when the system clock
    /// is before the UNIX epoch and no `now_timestamp` was set.
    pub async fn build(self, cache: &mut EvmCache) -> Result<OracleTracker, OracleError> {
        let report = self.build_report(cache).await?;
        if let Some(skipped) = report.skipped.first() {
            return Err(OracleError::FeedSkipped(Box::new(
                OracleFeedSkip::from_adapter_skip(skipped),
            )));
        }
        Ok(report.tracker)
    }

    /// Register every compatible feed and return skipped feeds instead of failing fast.
    pub async fn build_report(
        self,
        cache: &mut EvmCache,
    ) -> Result<OracleAdapterBuildReport, OracleError> {
        let now_timestamp = match self.now_timestamp {
            Some(now_timestamp) => now_timestamp,
            None => SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map_err(crate::error::clock_error)?
                .as_secs(),
        };
        let reader = EvmCacheChainlinkReader::new(cache).with_multicall_reads(self.multicall_reads);
        let mut registry = OracleRegistry::new_at_timestamp(now_timestamp);
        let skipped = reader.register_feeds(&mut registry, self.feeds).await?;
        Ok(OracleAdapterBuildReport {
            tracker: OracleTracker::new(registry),
            skipped,
        })
    }
}

impl std::fmt::Display for OracleAdapterSkipReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotChainlinkCompatible { error } => {
                write!(f, "not Chainlink-compatible ({error})")
            }
            Self::UnsupportedAaveSource { error } => {
                write!(f, "unsupported Aave oracle source ({error})")
            }
            Self::UnsupportedMorphoSource { error } => {
                write!(f, "unsupported Morpho oracle source ({error})")
            }
            Self::UnsupportedEulerSource { error } => {
                write!(f, "unsupported Euler oracle source ({error})")
            }
            #[cfg(feature = "redstone")]
            Self::UnsupportedRedstoneSource { error } => {
                write!(f, "unsupported RedStone oracle source ({error})")
            }
        }
    }
}

fn u64_from_u256(value: U256, field: &'static str) -> Result<u64, OracleError> {
    u64::try_from(value).map_err(|_| {
        OracleError::Decode(crate::ChainlinkEventDecodeError::Uint64Overflow { field, value })
    })
}

fn round_from_raw(
    round: <latestRoundDataCall as SolCall>::Return,
) -> Result<RoundData, OracleError> {
    Ok(RoundData {
        round_id: U256::from(round.roundId),
        answer: round.answer,
        started_at: u64_from_u256(round.startedAt, "startedAt")?,
        updated_at: u64_from_u256(round.updatedAt, "updatedAt")?,
        answered_in_round: U256::from(round.answeredInRound),
    })
}

fn multicall_call<C: SolCall>(
    target: Address,
    call: C,
    allow_failure: bool,
) -> (Address, Bytes, bool) {
    (target, Bytes::from(call.abi_encode()), allow_failure)
}

fn provider_error(error: impl std::fmt::Debug) -> OracleError {
    OracleError::Provider(format!("{error:?}"))
}