evm-amm-state 0.1.0

EVM-backed AMM state loading, cache synchronization, and pool simulation models
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
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
//! Adapter cold-start adoption over [`EvmCache::run_cold_start`].
//!
//! This module bridges the crate-owned [`AmmAdapter`](super::AmmAdapter)
//! cold-start contract onto the upstream protocol-neutral
//! [`evm_fork_cache::cold_start`] driver. Each adapter builds an
//! [`AdapterColdStartPlanner`] (via
//! [`AmmAdapter::cold_start_planner`](super::AmmAdapter::cold_start_planner)),
//! [`AdapterRegistry::cold_start`] drives it through the bounded multi-round
//! loop, and the planner finalizes the pool's metadata/status into a
//! [`ColdStartOutcome`].
//!
//! `evm_fork_cache::cold_start` is available unconditionally here: the dependency
//! is declared with its default features (which enable the upstream `reactive`
//! feature that gates `cold_start`), so this module is always compiled rather
//! than behind a protocol flag.
//!
//! # Archive-miss classification
//!
//! The per-slot [`SlotFetch`](evm_fork_cache::cold_start::SlotFetch) replaces the
//! former `cached_storage(..).is_none()` proxy: a planner's `on_results` decides
//! a mandatory slot's verdict from `Value` / `Zero` / `FetchFailed`, so a genuine
//! on-chain zero and a transient archive miss become *distinguishable* repairs.

use alloy_primitives::{Address, B256, Bytes, U256};
use evm_fork_cache::CacheError as UpstreamCacheError;
use evm_fork_cache::bulk_storage::{StorageProgram, run_storage_programs};
use evm_fork_cache::cache::{CodeSeedState, EvmCache};
use evm_fork_cache::cold_start::ColdStartConfig;

use super::bytecode::AdapterCodeSeed;
use super::state::UpstreamStateView;
use super::storage_sync::{StorageSyncSpec, decode_storage_sync, storage_sync_spec_for_pool};
use super::{
    AdapterRegistry, CallOutcome, ColdStartOutcome, ColdStartPolicy, ColdStartReport,
    PoolRegistration, PoolStatus, SlotChange, StateView, UnsupportedReason,
};

#[cfg(feature = "uniswap-v3")]
use super::v3_sync::{V3SyncError, V3SyncSpec, decode_full_sync, full_sync_program};

// ---------------------------------------------------------------------------
// Crate-owned mirrors of the `evm_fork_cache::cold_start` vocabulary.
//
// Each mirror keeps upstream's variant / field NAMES so planner call-sites read
// the same; the `From` conversions bridge to/from upstream at the driver seam.
// ---------------------------------------------------------------------------

/// Verified-code-seed results surfaced through a [`ColdStartReport`].
///
/// Crate-owned mirror of [`evm_fork_cache::cache::CodeVerifyReport`], so the
/// public surface does not leak the upstream report. `verified` seeds are
/// confirmed against chain code; `mismatched` / `not_deployed` / `codeless`
/// seeds were contradicted and purged by upstream; `unverifiable` seeds could
/// not be checked (transport error / no sample) — the facade purges those too,
/// so the pool falls back to lazily fetching its real code.
///
/// [`ColdStartReport`]: super::ColdStartReport
///
/// `#[non_exhaustive]`: Construct via `Default` and field assignment.
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CodeSeedReport {
    /// Seeds confirmed against on-chain code (`CodeSeedState::Verified`).
    pub verified: Vec<Address>,
    /// Seeds contradicted by a differing on-chain code hash (purged upstream).
    pub mismatched: Vec<CodeSeedMismatch>,
    /// Seeded addresses with no code at the pinned block (purged upstream).
    pub not_deployed: Vec<Address>,
    /// Seeded addresses that exist but hold no code / are EOAs (purged upstream).
    pub codeless: Vec<Address>,
    /// Seeds whose verification could not complete, with the reason (purged by
    /// the facade so the pool never simulates over unverified code).
    pub unverifiable: Vec<(Address, String)>,
}

impl From<evm_fork_cache::cache::CodeVerifyReport> for CodeSeedReport {
    fn from(report: evm_fork_cache::cache::CodeVerifyReport) -> Self {
        Self {
            verified: report.verified,
            mismatched: report.mismatched.into_iter().map(Into::into).collect(),
            not_deployed: report.not_deployed,
            codeless: report.codeless,
            unverifiable: report.unverifiable,
        }
    }
}

/// One contradicted code-seed claim from verification.
///
/// Crate-owned mirror of [`evm_fork_cache::cache::CodeMismatch`].
///
/// `#[non_exhaustive]`: Construct via [`CodeSeedMismatch::new`].
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CodeSeedMismatch {
    /// The seeded address.
    pub address: Address,
    /// The hash the seed claimed (keccak256 of the seeded bytes).
    pub expected: B256,
    /// The on-chain `EXTCODEHASH` observed at the pinned block.
    pub actual: B256,
}

impl CodeSeedMismatch {
    /// A mismatch record: `address` claimed `expected`, the chain holds `actual`.
    pub fn new(address: Address, expected: B256, actual: B256) -> Self {
        Self {
            address,
            expected,
            actual,
        }
    }
}

impl From<evm_fork_cache::cache::CodeMismatch> for CodeSeedMismatch {
    fn from(mismatch: evm_fork_cache::cache::CodeMismatch) -> Self {
        Self {
            address: mismatch.address,
            expected: mismatch.expected,
            actual: mismatch.actual,
        }
    }
}

/// A single round of cold-start work, declared by an
/// [`AdapterColdStartPlanner`].
///
/// Crate-owned mirror of [`evm_fork_cache::cold_start::ColdStartPlan`]. All four
/// phases are optional; an empty plan is a valid no-op round.
///
/// `#[non_exhaustive]`: Construct via `Default` and field assignment, so future phases (e.g. the
/// upstream root-probe baseline) can land without breaking planner authors.
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct ColdStartPlan {
    /// Slots to authoritatively re-fetch, classify, and inject when changed.
    pub verify: Vec<(Address, U256)>,
    /// Slots to classify at the pinned block without injecting.
    pub probe: Vec<(Address, U256)>,
    /// Accounts to pre-seed into the cache before discovery.
    pub accounts: Vec<Address>,
    /// View-calls whose touched slots and accounts are captured.
    pub discover: Vec<ColdStartCall>,
}

impl From<ColdStartPlan> for evm_fork_cache::cold_start::ColdStartPlan {
    fn from(plan: ColdStartPlan) -> Self {
        evm_fork_cache::cold_start::ColdStartPlan {
            verify: plan.verify,
            probe: plan.probe,
            accounts: plan.accounts,
            discover: plan.discover.into_iter().map(Into::into).collect(),
            // Root-only account probes (0.2.0, Phase-8 root baseline) are not
            // yet part of the adapter planner vocabulary.
            probe_roots: Vec::new(),
        }
    }
}

/// A read-only view-call whose touched storage and accounts are captured during
/// the discover phase.
///
/// Crate-owned mirror of [`evm_fork_cache::cold_start::ColdStartCall`].
///
/// `#[non_exhaustive]`: Construct via [`ColdStartCall::new`].
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct ColdStartCall {
    /// Transaction sender.
    pub from: Address,
    /// Call target.
    pub to: Address,
    /// Calldata.
    pub calldata: Bytes,
    /// When set, filters captured slots and accounts to these addresses.
    pub restrict_to: Option<Vec<Address>>,
}

impl ColdStartCall {
    /// A discover view-call from `from` to `to` with `calldata`, capturing every
    /// touched slot and account (no `restrict_to` filter).
    pub fn new(from: Address, to: Address, calldata: impl Into<Bytes>) -> Self {
        Self {
            from,
            to,
            calldata: calldata.into(),
            restrict_to: None,
        }
    }

    /// Filter the captured slots and accounts to `addresses`.
    pub fn with_restrict_to(mut self, addresses: impl IntoIterator<Item = Address>) -> Self {
        self.restrict_to = Some(addresses.into_iter().collect());
        self
    }
}

impl From<ColdStartCall> for evm_fork_cache::cold_start::ColdStartCall {
    fn from(call: ColdStartCall) -> Self {
        evm_fork_cache::cold_start::ColdStartCall {
            from: call.from,
            to: call.to,
            calldata: call.calldata,
            restrict_to: call.restrict_to,
        }
    }
}

/// The outcome of executing one [`ColdStartPlan`] round.
///
/// Crate-owned mirror of [`evm_fork_cache::cold_start::ColdStartResults`].
/// `fetched` / `probed` carry one [`SlotOutcome`] per declared verify / probe
/// slot; `verified` carries only the slots whose value changed; `discovered`
/// carries one [`ColdStartCallResult`] per discover call.
///
/// `#[non_exhaustive]`: Construct via `Default` and field assignment.
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct ColdStartResults {
    /// Slots whose value changed and were injected (one per change).
    pub verified: Vec<SlotChange>,
    /// One outcome per declared verify slot (`Value` / `Zero` / `FetchFailed`).
    pub fetched: Vec<SlotOutcome>,
    /// One outcome per declared probe slot (classified, not injected).
    pub probed: Vec<SlotOutcome>,
    /// One result per discover call.
    pub discovered: Vec<ColdStartCallResult>,
}

impl From<evm_fork_cache::cold_start::ColdStartResults> for ColdStartResults {
    fn from(results: evm_fork_cache::cold_start::ColdStartResults) -> Self {
        Self {
            verified: results.verified.into_iter().map(SlotChange::from).collect(),
            fetched: results.fetched.into_iter().map(SlotOutcome::from).collect(),
            probed: results.probed.into_iter().map(SlotOutcome::from).collect(),
            discovered: results
                .discovered
                .into_iter()
                .map(ColdStartCallResult::from)
                .collect(),
        }
    }
}

/// The result of one discover view-call: the classified EVM execution outcome and
/// the storage/account access list it touched.
///
/// Crate-owned mirror of [`evm_fork_cache::cold_start::ColdStartCallResult`].
///
/// `#[non_exhaustive]`: Construct via [`ColdStartCallResult::new`].
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct ColdStartCallResult {
    /// The classified outcome of the view-call.
    pub result: CallOutcome,
    /// The storage slots and accounts the call touched (after `restrict_to`).
    pub access: StorageAccessList,
}

impl ColdStartCallResult {
    /// A discover-call result from its classified outcome and access list.
    pub fn new(result: CallOutcome, access: StorageAccessList) -> Self {
        Self { result, access }
    }
}

impl From<evm_fork_cache::cold_start::ColdStartCallResult> for ColdStartCallResult {
    fn from(call: evm_fork_cache::cold_start::ColdStartCallResult) -> Self {
        Self {
            result: CallOutcome::from(call.result),
            access: StorageAccessList::from(call.access),
        }
    }
}

/// The storage slots and accounts a discover view-call touched.
///
/// Crate-owned mirror of `evm_fork_cache`'s `StorageAccessList` (the access-set
/// surface a discover call captures).
///
/// `#[non_exhaustive]`: Construct via `Default` and field assignment.
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct StorageAccessList {
    /// Accounts the call touched.
    pub accounts: Vec<Address>,
    /// Storage `(address, slot)` pairs the call touched.
    pub slots: Vec<(Address, U256)>,
}

impl From<evm_fork_cache::access_set::StorageAccessList> for StorageAccessList {
    fn from(access: evm_fork_cache::access_set::StorageAccessList) -> Self {
        Self {
            accounts: access.accounts.into_iter().collect(),
            slots: access.slots.into_iter().collect(),
        }
    }
}

/// The classified result of an individual slot fetch.
///
/// Crate-owned mirror of [`evm_fork_cache::cold_start::SlotFetch`].
/// `#[non_exhaustive]` — an open classification vocabulary.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SlotFetch {
    /// The slot was fetched and holds a non-zero value.
    Value(U256),
    /// The slot was fetched and holds a genuine on-chain zero.
    Zero,
    /// The fetcher returned an error for this slot; `reason` is its description.
    FetchFailed {
        /// Human-readable description of why the fetch failed.
        reason: String,
    },
    /// The slot was declared but never reached because the round short-circuited.
    NotAttempted,
}

impl From<evm_fork_cache::cold_start::SlotFetch> for SlotFetch {
    fn from(fetch: evm_fork_cache::cold_start::SlotFetch) -> Self {
        use evm_fork_cache::cold_start::SlotFetch as Upstream;
        match fetch {
            Upstream::Value(value) => SlotFetch::Value(value),
            Upstream::Zero => SlotFetch::Zero,
            Upstream::FetchFailed { reason } => SlotFetch::FetchFailed { reason },
            Upstream::NotAttempted => SlotFetch::NotAttempted,
        }
    }
}

/// The classified outcome of fetching a single storage slot.
///
/// Crate-owned mirror of `evm_fork_cache`'s `SlotOutcome`: produced for **every**
/// requested verify / probe slot (unlike [`SlotChange`], which records only
/// changed slots).
///
/// `#[non_exhaustive]`: Construct via [`SlotOutcome::new`].
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SlotOutcome {
    /// Contract whose storage slot was fetched.
    pub address: Address,
    /// Storage slot key.
    pub slot: U256,
    /// The classified result of fetching this slot.
    pub fetch: SlotFetch,
}

impl SlotOutcome {
    /// The classified outcome of fetching `slot` on `address`.
    pub fn new(address: Address, slot: U256, fetch: SlotFetch) -> Self {
        Self {
            address,
            slot,
            fetch,
        }
    }
}

impl From<evm_fork_cache::cold_start::SlotOutcome> for SlotOutcome {
    fn from(outcome: evm_fork_cache::cold_start::SlotOutcome) -> Self {
        Self {
            address: outcome.address,
            slot: outcome.slot,
            fetch: outcome.fetch.into(),
        }
    }
}

/// The planner's decision after a round completes.
///
/// Crate-owned mirror of [`evm_fork_cache::cold_start::ColdStartStep`].
/// `#[non_exhaustive]` — an open control vocabulary.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ColdStartStep {
    /// Stop the cold-start loop; the run succeeds.
    Done,
    /// Execute the carried plan as the next round.
    Continue(ColdStartPlan),
}

impl From<ColdStartStep> for evm_fork_cache::cold_start::ColdStartStep {
    fn from(step: ColdStartStep) -> Self {
        match step {
            ColdStartStep::Done => evm_fork_cache::cold_start::ColdStartStep::Done,
            ColdStartStep::Continue(plan) => {
                evm_fork_cache::cold_start::ColdStartStep::Continue(plan.into())
            }
        }
    }
}

/// Summary of a completed cold-start run.
///
/// Crate-owned mirror of [`evm_fork_cache::cold_start::ColdStartRunReport`],
/// carrying the accumulated per-run counters.
///
/// `#[non_exhaustive]`: Construct via `Default` and field assignment.
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct ColdStartRunReport {
    /// Number of rounds executed.
    pub rounds: usize,
    /// Total verify slots requested across all rounds.
    pub verified_slots: usize,
    /// Total slots that changed and were injected.
    pub changed_slots: usize,
    /// Total accounts touched by discover calls, summed across calls and rounds.
    pub discovered_accounts: usize,
    /// Total slots touched by discover calls, summed across calls and rounds.
    pub discovered_slots: usize,
    /// Total verify + probe slots whose fetch failed.
    pub failed_slots: usize,
}

impl From<evm_fork_cache::cold_start::ColdStartRunReport> for ColdStartRunReport {
    fn from(report: evm_fork_cache::cold_start::ColdStartRunReport) -> Self {
        Self {
            rounds: report.rounds,
            verified_slots: report.verified_slots,
            changed_slots: report.changed_slots,
            discovered_accounts: report.discovered_accounts,
            discovered_slots: report.discovered_slots,
            failed_slots: report.failed_slots,
        }
    }
}

/// A hard error that aborts a cold-start round or run.
///
/// Crate-owned mirror of [`evm_fork_cache::cold_start::ColdStartError`], so the
/// public surface does not leak the upstream error. `#[non_exhaustive]` — an open
/// error vocabulary.
#[derive(Debug)]
#[non_exhaustive]
pub enum ColdStartError {
    /// A round declared verify/probe slots but the cache has no storage batch
    /// fetcher configured.
    NoBatchFetcher,
    /// A round declared probe-roots accounts but the cache has no account
    /// proof fetcher configured.
    NoAccountProofFetcher,
    /// The cache holds pending code seeds but has no account-fields fetcher
    /// to verify them with (fires only for pending-bearing rounds).
    NoAccountFieldsFetcher,
    /// The planner kept returning `Continue` past `max_rounds` executed rounds.
    RoundBudgetExceeded {
        /// The configured maximum number of executed rounds.
        max_rounds: usize,
    },
    /// A composed fetch/call error, carrying the un-flattened cause. Downcast
    /// the payload (or walk [`source`](std::error::Error::source)) — e.g. to
    /// [`evm_fork_cache::CacheError`] — for typed handling.
    Fetch(Box<dyn std::error::Error + Send + Sync + 'static>),
}

impl std::fmt::Display for ColdStartError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoBatchFetcher => write!(f, "cold-start requires a storage batch fetcher"),
            Self::NoAccountProofFetcher => {
                write!(f, "cold-start requires an account proof fetcher")
            }
            Self::NoAccountFieldsFetcher => {
                write!(
                    f,
                    "cold-start code-seed verification requires an account fields fetcher"
                )
            }
            Self::RoundBudgetExceeded { max_rounds } => {
                write!(f, "cold-start round budget exceeded ({max_rounds})")
            }
            Self::Fetch(err) => write!(f, "cold-start fetch error: {err}"),
        }
    }
}

impl std::error::Error for ColdStartError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Fetch(err) => Some(&**err as &(dyn std::error::Error + 'static)),
            _ => None,
        }
    }
}

impl From<evm_fork_cache::cold_start::ColdStartError> for ColdStartError {
    fn from(err: evm_fork_cache::cold_start::ColdStartError) -> Self {
        use evm_fork_cache::cold_start::ColdStartError as Upstream;
        match err {
            Upstream::NoBatchFetcher => ColdStartError::NoBatchFetcher,
            Upstream::NoAccountProofFetcher => ColdStartError::NoAccountProofFetcher,
            Upstream::NoAccountFieldsFetcher => ColdStartError::NoAccountFieldsFetcher,
            Upstream::RoundBudgetExceeded { max_rounds } => {
                ColdStartError::RoundBudgetExceeded { max_rounds }
            }
            Upstream::Fetch(cause) => ColdStartError::Fetch(Box::new(cause)),
        }
    }
}

/// An adapter cold-start planner.
///
/// Extends the upstream [`ColdStartPlanner`](evm_fork_cache::cold_start::ColdStartPlanner)
/// surface with a [`finish`](Self::finish) hook that, after the run, mutates the
/// pool (metadata + status) and maps the accumulated state into a
/// [`ColdStartOutcome`].
///
/// Implementations are `'static`: a planner owns its address/layout/policy and
/// any state accumulated across rounds, so it does not borrow the pool or cache
/// for the lifetime of the run.
pub trait AdapterColdStartPlanner {
    /// The first plan to execute, derived from the current cached `state`.
    fn initial_plan(&mut self, state: &dyn StateView) -> ColdStartPlan;

    /// Decide whether to continue (with a next plan) or finish, given the
    /// just-completed round's `results` and the post-injection `state` view.
    fn on_results(&mut self, results: &ColdStartResults, state: &dyn StateView) -> ColdStartStep;

    /// Finalize after the run: mutate `pool` (metadata + status) and return the
    /// outcome built from the planner's accumulated state and the run `report`.
    fn finish(
        &mut self,
        pool: &mut PoolRegistration,
        report: &ColdStartRunReport,
    ) -> ColdStartOutcome;
}

/// Forwards an [`AdapterColdStartPlanner`] to the upstream
/// [`ColdStartPlanner`](evm_fork_cache::cold_start::ColdStartPlanner) trait.
///
/// A newtype rather than a blanket impl so the upstream trait is implemented
/// without trait-upcasting `Box<dyn AdapterColdStartPlanner>` and without leaking
/// the upstream trait into the public adapter surface.
struct Bridge<'a>(&'a mut dyn AdapterColdStartPlanner);

impl evm_fork_cache::cold_start::ColdStartPlanner for Bridge<'_> {
    fn initial_plan(
        &mut self,
        state: &dyn evm_fork_cache::StateView,
    ) -> evm_fork_cache::cold_start::ColdStartPlan {
        self.0.initial_plan(&UpstreamStateView(state)).into()
    }

    fn on_results(
        &mut self,
        results: &evm_fork_cache::cold_start::ColdStartResults,
        state: &dyn evm_fork_cache::StateView,
    ) -> evm_fork_cache::cold_start::ColdStartStep {
        let results = ColdStartResults::from(results.clone());
        self.0
            .on_results(&results, &UpstreamStateView(state))
            .into()
    }
}

// ---------------------------------------------------------------------------
// One-shot bulk hydration (the fast multi-pool bootstrap default).
// ---------------------------------------------------------------------------

/// How to hydrate one pool's whole hot state in a **single** storage program
/// (`eth_call` with a code override), used by
/// [`cold_start_many`](AdapterRegistry::cold_start_many).
///
/// Two shapes cover every fast-eligible pool:
///
/// - `V3` — a concentrated-liquidity full sync ([`v3_sync`](super::v3_sync)),
///   which walks the entire tick bitmap in-program (only under the
///   `uniswap-v3` feature).
/// - `Flat` — a fixed / discovered flat read-set
///   ([`storage_sync`](super::storage_sync)) for V2, Solidly, and (once
///   discovered) Balancer/Curve.
enum HydrationKind {
    /// Concentrated-liquidity one-shot full sync for a V3-family pool.
    #[cfg(feature = "uniswap-v3")]
    V3 {
        /// The pool whose storage the program reads.
        pool: Address,
        /// The full-sync spec derived from the pool's storage layout.
        spec: V3SyncSpec,
    },
    /// Flat-slot one-shot sync for a pool with a known read-set.
    Flat {
        /// The flat read-set spec for the pool.
        spec: StorageSyncSpec,
    },
}

impl HydrationKind {
    /// The single storage program that hydrates the pool's whole hot state.
    fn program(&self) -> StorageProgram {
        match self {
            #[cfg(feature = "uniswap-v3")]
            HydrationKind::V3 { pool, spec } => full_sync_program(*pool, spec),
            HydrationKind::Flat { spec } => spec.program(),
        }
    }

    /// Decode `output`, inject the hydrated state into `cache`, and record what
    /// was loaded/changed for the pool's cold-start report. A decode failure is
    /// surfaced (un-flattened) so the caller can fall the pool back to the
    /// multi-round cold-start.
    fn apply(&self, cache: &mut EvmCache, output: &Bytes) -> Result<Hydrated, HydrationError> {
        let entries: Vec<(Address, U256, U256)> = match self {
            #[cfg(feature = "uniswap-v3")]
            HydrationKind::V3 { pool, spec } => {
                let snapshot = decode_full_sync(spec, output).map_err(HydrationError::V3)?;
                snapshot
                    .storage_entries(spec)
                    .into_iter()
                    .map(|(slot, value)| (*pool, slot, value))
                    .collect()
            }
            HydrationKind::Flat { spec } => {
                let snapshot = decode_storage_sync(spec, output).map_err(HydrationError::Flat)?;
                snapshot.storage_entries()
            }
        };
        Ok(inject_and_record(cache, entries))
    }
}

/// What a one-shot `HydrationKind::apply` wrote, surfaced into the fast
/// `cold_start_many` report.
struct Hydrated {
    /// Every `(address, slot)` the program loaded, in program order.
    verified: Vec<(Address, U256)>,
    /// The subset whose injected value differs from the prior cached value.
    changed: Vec<SlotChange>,
}

/// Peek prior values, inject the batch (layer-2 cold-prefetch, matching
/// `StorageSyncSnapshot::inject`), and record what was loaded/changed. Priors
/// are read through the non-faulting `EvmCache::cached_storage_value`, so the
/// bulk bootstrap path stays offline.
fn inject_and_record(cache: &mut EvmCache, entries: Vec<(Address, U256, U256)>) -> Hydrated {
    let verified: Vec<(Address, U256)> = entries.iter().map(|(a, s, _)| (*a, *s)).collect();
    let changed: Vec<SlotChange> = entries
        .iter()
        .filter_map(|(address, slot, value)| {
            let prior = cache
                .cached_storage_value(*address, *slot)
                .unwrap_or(U256::ZERO);
            (prior != *value).then(|| SlotChange::new(*address, *slot, prior, *value))
        })
        .collect();
    cache.inject_storage_batch(&entries);
    Hydrated { verified, changed }
}

/// Classify how — if at all — `pool` can be hydrated by a single one-shot
/// storage program.
///
/// - No pool address → `None`.
/// - A V3-family pool (`UniswapV3`/`PancakeV3`/`Slipstream`) that carries a
///   `storage_layout` → a [`HydrationKind::V3`] full sync (only when the
///   `uniswap-v3` feature is enabled).
/// - Otherwise, any pool whose flat read-set resolves via
///   [`storage_sync_spec_for_pool`] → a [`HydrationKind::Flat`] sync.
/// - Everything else → `None`.
///
/// [`supports_one_shot_hydration`] is exactly `hydration_kind(pool).is_some()`,
/// so classification and execution can never disagree.
fn hydration_kind(pool: &PoolRegistration) -> Option<HydrationKind> {
    let address = pool.key.address()?;

    #[cfg(feature = "uniswap-v3")]
    if let Some(spec) = v3_sync_spec(pool) {
        return Some(HydrationKind::V3 {
            pool: address,
            spec,
        });
    }
    // Without the `uniswap-v3` feature the V3 full-sync path is uncompiled, so
    // `storage_sync_spec_for_pool` (which rejects V3-family protocols) is the
    // only classifier; the address is validated above regardless.
    let _ = address;

    storage_sync_spec_for_pool(pool)
        .ok()
        .map(|spec| HydrationKind::Flat { spec })
}

/// Build the one-shot V3 full-sync spec for a V3-family pool, if it is eligible.
///
/// Eligibility (all required):
/// - the pool registered as a V3-family variant carrying an **explicit**
///   `storage_layout` (unlike [`layout_for`](super::storage::layout_for), this
///   does not derive a layout from `tick_spacing` alone), and
/// - that layout has a **positive** `tick_spacing` — `full_word_range` /
///   `v3_word_position` require it, so a non-positive spacing returns `None`
///   here and falls to the single-pool `cold_start` (which reports
///   `Unsupported`) rather than panicking in the fast path.
///
/// The **canonical Uniswap** spec (which bakes in Uniswap's fee-growth,
/// protocol-fees, and observation slot positions) is used only for genuine
/// Uniswap V3 pools. Other V3-family forks (PancakeSwap V3, Slipstream) use the
/// layout-only [`V3SyncSpec::core`] (slot0 + liquidity + the ticks/bitmap the
/// layout locates) so hydration never injects auxiliary state from unverified
/// slot positions. Extend a fork to the full spec once its layout is confirmed.
#[cfg(feature = "uniswap-v3")]
fn v3_sync_spec(pool: &PoolRegistration) -> Option<V3SyncSpec> {
    use super::ProtocolMetadata;
    let (metadata, canonical_uniswap) = match &pool.metadata {
        ProtocolMetadata::UniswapV3(metadata) => (metadata, true),
        ProtocolMetadata::PancakeV3(metadata) | ProtocolMetadata::Slipstream(metadata) => {
            (metadata, false)
        }
        _ => return None,
    };
    let layout = metadata.storage_layout.filter(|l| l.tick_spacing > 0)?;
    Some(if canonical_uniswap {
        V3SyncSpec::uniswap(layout)
    } else {
        V3SyncSpec::core(layout)
    })
}

/// Whether `pool` can be hydrated by a single one-shot storage program (the fast
/// multi-pool bootstrap path used by
/// [`cold_start_many`](AdapterRegistry::cold_start_many)).
///
/// Uniswap V2 (and any flat-read-set protocol) and V3-family pools that carry a
/// `storage_layout` qualify; a V3 pool without a layout, an addressless pool, or
/// a protocol with no persisted read-set (e.g. Curve before discovery) do not.
///
/// Defined as `hydration_kind(pool).is_some()`, so it always agrees with what
/// `cold_start_many` will actually attempt.
pub fn supports_one_shot_hydration(pool: &PoolRegistration) -> bool {
    hydration_kind(pool).is_some()
}

/// Whether `pool`'s registration metadata is already complete enough for the
/// one-shot fast path to finalize it `Ready` *without* the adapter planner's
/// [`finish`](AdapterColdStartPlanner::finish) (metadata merge + status
/// validation).
///
/// The fast path only warms the cache; a registration still missing identity
/// metadata — e.g. a Uniswap V2 pool without its `token0`/`token1`, which the
/// normal cold-start decodes from storage and merges — must fall back to the
/// multi-round [`cold_start`](AdapterRegistry::cold_start) so `finish` runs.
/// Registrations produced by factory discovery are already complete and stay on
/// the fast path.
///
/// For a V3-family pool `finish` *preserves* (never merges) metadata, so
/// completeness here means the fields a later `simulate_swap` needs (`fee`) plus
/// the layout the fast path already requires. A V3 fork with no fee tier (e.g. a
/// discovered Slipstream pool, whose `fee` is deliberately unset) therefore
/// forgoes the fast path and takes the normal `cold_start` — acceptable, since it
/// is discovery-only for quoting anyway. Balancer/Curve flat hydration only
/// applies once a discovered read-set exists, which itself is produced by a
/// prior discover→verify `cold_start` that already ran `finish`.
fn fast_metadata_complete(pool: &PoolRegistration) -> bool {
    use super::ProtocolMetadata;
    match &pool.metadata {
        ProtocolMetadata::UniswapV2(m) => m.token0.is_some() && m.token1.is_some(),
        ProtocolMetadata::UniswapV3(m)
        | ProtocolMetadata::PancakeV3(m)
        | ProtocolMetadata::Slipstream(m) => m.fee.is_some() && m.storage_layout.is_some(),
        // Solidly `finish` decodes+merges token0/token1 like V2, so require them
        // here too — otherwise the fast path would leave metadata tokens `None`
        // while the fallback populates them (an inconsistency for consumers that
        // read `PoolRegistration.metadata`).
        ProtocolMetadata::SolidlyV2(m) => {
            m.token0.is_some()
                && m.token1.is_some()
                && m.stable.is_some()
                && m.storage_layout.is_some()
        }
        ProtocolMetadata::BalancerV2(m) => m.vault.is_some() && !m.balance_slots.is_empty(),
        ProtocolMetadata::Curve(m) => !m.coins.is_empty() && !m.discovered_slots.is_empty(),
        // No known completeness contract → let the normal cold_start finalize it.
        ProtocolMetadata::Unknown | ProtocolMetadata::Custom(_) => false,
    }
}

/// A failure hydrating one pool from a one-shot storage program's output.
///
/// Used only to decide per-pool fallback inside
/// [`cold_start_many`](AdapterRegistry::cold_start_many); it is never returned
/// to the caller in this cycle. Keeps the upstream cause reachable through
/// [`source`](std::error::Error::source) — the cause is not stringified.
/// `#[non_exhaustive]` — an open error vocabulary.
#[derive(Debug)]
#[non_exhaustive]
pub enum HydrationError {
    /// Decoding a V3 full-sync program's output failed.
    #[cfg(feature = "uniswap-v3")]
    V3(V3SyncError),
    /// Decoding a flat-slot sync program's output failed.
    Flat(super::storage_sync::StorageSyncError),
}

impl std::fmt::Display for HydrationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "uniswap-v3")]
            Self::V3(_) => write!(f, "one-shot V3 hydration failed"),
            Self::Flat(_) => write!(f, "one-shot flat-slot hydration failed"),
        }
    }
}

impl std::error::Error for HydrationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            #[cfg(feature = "uniswap-v3")]
            Self::V3(err) => Some(err as &(dyn std::error::Error + 'static)),
            Self::Flat(err) => Some(err as &(dyn std::error::Error + 'static)),
        }
    }
}

impl AdapterRegistry {
    /// Cold-start `pool` through its adapter's planner.
    ///
    /// Resolves the adapter for `pool.protocol()`, builds its
    /// [`AdapterColdStartPlanner`], and drives it through
    /// [`EvmCache::run_cold_start`] with [`ColdStartConfig::default`]. The planner
    /// then [`finish`](AdapterColdStartPlanner::finish)es into a
    /// [`ColdStartOutcome`], mutating `pool`'s metadata and status.
    ///
    /// A missing adapter or an unsupported pool maps to
    /// `Ok(ColdStartOutcome::Unsupported(..))`; an upstream
    /// [`ColdStartError`] (e.g. a missing batch fetcher) propagates as `Err`. A
    /// per-slot fetch failure is *not* a run error — it is classified as
    /// [`SlotFetch::FetchFailed`](evm_fork_cache::cold_start::SlotFetch::FetchFailed)
    /// and handled by the planner's `on_results`.
    pub fn cold_start(
        &self,
        pool: &mut PoolRegistration,
        cache: &mut EvmCache,
        policy: ColdStartPolicy,
    ) -> Result<ColdStartOutcome, ColdStartError> {
        let Some(adapter) = self.adapter(pool.protocol()) else {
            return Ok(ColdStartOutcome::Unsupported(UnsupportedReason::Protocol(
                pool.protocol(),
            )));
        };

        let mut planner = match adapter.cold_start_planner(pool, policy) {
            Ok(planner) => planner,
            Err(reason) => return Ok(ColdStartOutcome::Unsupported(reason)),
        };

        // Seeding is a pure optimization over the lazy real-code fetch at first
        // simulate (see `sim.rs`), so an adapter render error is a safe skip
        // (no seeding for this pool), never a failure. `code_seeds` stays `None`
        // when nothing was seeded.
        let code_seed_report = if self.code_seeding && cache.account_fields_fetcher().is_some() {
            match adapter.code_seeds(pool) {
                Ok(seeds) if !seeds.is_empty() => Some(seed_and_verify(cache, seeds)),
                _ => None,
            }
        } else {
            None
        };

        let report = {
            let mut bridge = Bridge(planner.as_mut());
            cache
                .run_cold_start(&mut bridge, ColdStartConfig::default())
                .map_err(ColdStartError::from)?
        };
        let report = ColdStartRunReport::from(report);

        let outcome = planner.finish(pool, &report);
        Ok(attach_code_seeds(outcome, code_seed_report))
    }

    /// Cold-start many pools at once, making the high-performance one-shot
    /// storage load the **default** for multi-pool bootstrap.
    ///
    /// Where the per-pool [`cold_start`](Self::cold_start) runs a bounded
    /// multi-round planner for every pool — so requests scale with pool count —
    /// this path collapses the fast-eligible pools into a fixed number of
    /// phases:
    ///
    /// 1. **Classify.** A pool is `fast` when its adapter is registered,
    ///    [`supports_one_shot_hydration`] holds, **and** its registration is
    ///    already metadata-complete for its protocol (the fast path warms the
    ///    cache and marks `Ready` without running the planner's `finish`, so a
    ///    pool whose identity metadata still needs decoding/merging — e.g. a
    ///    bare Uniswap V2 registration without `token0`/`token1` — is left to
    ///    `fallback`). Everything else is `fallback`.
    /// 2. **Batched seed + verify.** Every fast pool's [`code_seeds`] are seeded
    ///    together (same skip rules as the single-pool path) and, if any are
    ///    pending, verified in **one** account-fields call — unverifiable seeds
    ///    are purged so no address is left `Pending`.
    /// 3. **Bundled hydration.** One [`run_storage_programs`] call hydrates all
    ///    fast pools (distinct targets bundle into a single multicall
    ///    `eth_call`). A pool whose program errored or failed to decode is moved
    ///    to the fallback set.
    /// 4. **Fallback.** Every fallback pool (originally classified plus any
    ///    fast-hydration failure) is finalized through the normal
    ///    [`cold_start`](Self::cold_start); its seeding is a no-op for anything
    ///    already `Verified` in step 2.
    /// 5. **Quote-target warming** (`Strict`/`Eager` only). The distinct
    ///    canonical quote entrypoints across all pools — the QuoterV2 / Router02
    ///    / Balancer vault each pool's [`quote_code_targets`] resolves against the
    ///    registry's [`sim_config`](Self::with_sim_config) — have their bytecode
    ///    fetched once so the first [`simulate_swap`] runs offline instead of a
    ///    lazy `eth_getCode`. Best-effort (an offline backend leaves the lazy
    ///    fetch in place) and typically a handful of fetches for the whole batch,
    ///    since one quoter/router serves an entire protocol family.
    ///
    /// Returns one [`ColdStartOutcome`] per input pool, in **input order**. An
    /// empty slice returns `Ok(vec![])` without touching `provider`.
    ///
    /// Fast hydration needs a live provider; over an empty/offline provider
    /// every `eth_call` errors and every fast pool gracefully falls back — never
    /// a panic. An upstream cold-start error from the fallback path (e.g. a
    /// missing batch fetcher) still propagates as `Err`.
    ///
    /// **Report detail.** A pool finalized on the fast (bundled) path returns a
    /// [`ColdStartReport`] carrying its `verified_slots` (every slot the bundled
    /// program loaded) and `changed_slots` (those whose value differed from the
    /// prior cache). Two fields the single-pool path fills stay empty: `applied`
    /// (the bundled path injects straight into the cache without materializing a
    /// `StateDiff`) and `code_seeds` (seed verification is batched across all
    /// fast pools, not attributed per pool). A pool that falls back to
    /// [`cold_start`](Self::cold_start) carries that method's full report. The
    /// step-5 quote-target warming is likewise batch-level (one fetch per
    /// distinct entrypoint, shared across pools) and so is not surfaced in any
    /// per-pool report.
    ///
    /// [`code_seeds`]: super::AmmAdapter::code_seeds
    /// [`quote_code_targets`]: PoolRegistration::quote_code_targets
    /// [`simulate_swap`]: super::AmmAdapter::simulate_swap
    pub async fn cold_start_many<P>(
        &self,
        pools: &mut [PoolRegistration],
        cache: &mut EvmCache,
        provider: &P,
        policy: ColdStartPolicy,
    ) -> Result<Vec<ColdStartOutcome>, ColdStartError>
    where
        P: alloy_provider::Provider<alloy_network::AnyNetwork>,
    {
        if pools.is_empty() {
            return Ok(Vec::new());
        }

        // Step 1: partition into fast (adapter present AND one-shot-eligible)
        // and fallback. `fast` carries the pool index and its hydration kind;
        // `is_fallback` marks every index not (yet) on the fast path.
        let mut fast: Vec<(usize, HydrationKind)> = Vec::new();
        let mut is_fallback = vec![true; pools.len()];
        for (index, pool) in pools.iter().enumerate() {
            if self.adapter(pool.protocol()).is_none() {
                continue;
            }
            // Fast-path only registrations that are already metadata-complete for
            // their protocol. The fast path warms the cache and finalizes `Ready`
            // WITHOUT running the adapter planner's `finish()` (metadata merge +
            // status validation), so a pool still missing identity metadata must
            // take the normal multi-round `cold_start` to be finalized correctly.
            if let Some(kind) = hydration_kind(pool)
                && fast_metadata_complete(pool)
            {
                is_fallback[index] = false;
                fast.push((index, kind));
            }
        }

        // Step 2: seed + verify every fast pool's code claims in one batch,
        // then a single verify pass. Mirrors the single-pool gating exactly.
        if self.code_seeding && cache.account_fields_fetcher().is_some() {
            let mut any_pending = false;
            for (index, _) in &fast {
                let pool = &pools[*index];
                if let Some(adapter) = self.adapter(pool.protocol()) {
                    // An adapter render error is a safe skip (no seeds for this
                    // pool), never a failure — matching the single-pool path.
                    if let Ok(seeds) = adapter.code_seeds(pool) {
                        any_pending |= seed_batch(cache, seeds);
                    }
                }
            }
            if any_pending {
                // The report is not surfaced here (fast outcomes leave
                // `code_seeds = None`); this call's job is to leave no address
                // `Pending`, purging any it cannot verify.
                let _ = verify_pending_seeds(cache);
            }
        }

        // Step 3: build one program per fast pool (stable order) and hydrate
        // them all in a single bundled call.
        let mut outcomes: Vec<Option<ColdStartOutcome>> = (0..pools.len()).map(|_| None).collect();
        if !fast.is_empty() {
            let programs: Vec<StorageProgram> =
                fast.iter().map(|(_, kind)| kind.program()).collect();
            let results = run_storage_programs(provider, cache.block(), &programs).await;

            for ((index, kind), result) in fast.iter().zip(results) {
                match result.map(|output| kind.apply(cache, &output)) {
                    Ok(Ok(hydrated)) => {
                        let pool = &mut pools[*index];
                        pool.status = PoolStatus::Ready;
                        let mut report = ColdStartReport::new(pool.key.clone(), policy);
                        report.status = PoolStatus::Ready;
                        report.verified_slots = hydrated.verified;
                        report.changed_slots = hydrated.changed;
                        outcomes[*index] = Some(ColdStartOutcome::Ready(report));
                    }
                    // Either the program call errored (offline / gas / transport)
                    // or its output failed to decode: fall this pool back.
                    _ => is_fallback[*index] = true,
                }
            }
        }

        // Step 4: finalize every fallback pool through the normal cold-start.
        for (index, pool) in pools.iter_mut().enumerate() {
            if is_fallback[index] {
                outcomes[index] = Some(self.cold_start(pool, cache, policy)?);
            }
        }

        // Step 5: under an eager policy, pre-warm the canonical quote
        // entrypoints' bytecode (QuoterV2 / Router02 / vault) so the first
        // `simulate_swap` against each pool runs offline instead of paying a lazy
        // `eth_getCode` on the hot path. Runs after fallback finalization so every
        // pool's metadata — and thus its resolved quote target — is final.
        // Best-effort: an offline backend or a target that carries no code simply
        // leaves the lazy first-quote fetch in place, never a cold-start failure
        // (mirroring code-seeding). `ensure_account` is idempotent and cached, so
        // this is one fetch per *distinct* address, shared across a whole family.
        if matches!(policy, ColdStartPolicy::Strict | ColdStartPolicy::Eager) {
            for target in self.collect_quote_code_targets(pools) {
                let _ = cache.ensure_account(target).await;
            }
        }

        // Step 6: every slot is now populated (fast success or fallback).
        Ok(outcomes
            .into_iter()
            .map(|outcome| outcome.expect("every pool is fast-hydrated or fell back"))
            .collect())
    }

    /// The distinct quote-target code addresses to pre-warm for `pools`, in
    /// first-seen order. Folds each pool's
    /// [`quote_code_targets`](PoolRegistration::quote_code_targets) (resolved
    /// against the registry's [`sim_config`](Self::with_sim_config)) and
    /// de-duplicates — one QuoterV2 / Router02 / vault typically serves many
    /// pools, so the returned set is a small constant regardless of pool count.
    /// Pools with no registered adapter are skipped (they cannot be quoted, so
    /// warming their target would be wasted).
    fn collect_quote_code_targets(&self, pools: &[PoolRegistration]) -> Vec<Address> {
        let mut targets: Vec<Address> = Vec::new();
        for pool in pools {
            if self.adapter(pool.protocol()).is_none() {
                continue;
            }
            for target in pool.quote_code_targets(&self.sim_config) {
                if !targets.contains(&target) {
                    targets.push(target);
                }
            }
        }
        targets
    }
}

/// Attach the verified-code-seed results to the [`ColdStartReport`] carried by a
/// report-bearing outcome. `Unsupported` carries no report, so it is unchanged.
///
/// [`ColdStartReport`]: super::ColdStartReport
fn attach_code_seeds(
    outcome: ColdStartOutcome,
    code_seed_report: Option<CodeSeedReport>,
) -> ColdStartOutcome {
    match outcome {
        ColdStartOutcome::Ready(mut report) => {
            report.code_seeds = code_seed_report;
            ColdStartOutcome::Ready(report)
        }
        ColdStartOutcome::ReadyWithDeferred(mut report, deferred) => {
            report.code_seeds = code_seed_report;
            ColdStartOutcome::ReadyWithDeferred(report, deferred)
        }
        ColdStartOutcome::NeedsRepair(mut report, repair) => {
            report.code_seeds = code_seed_report;
            ColdStartOutcome::NeedsRepair(report, repair)
        }
        ColdStartOutcome::Unsupported(reason) => ColdStartOutcome::Unsupported(reason),
    }
}

/// Seed each adapter code claim, then verify — leaving every seeded address
/// either `Verified` or unmarked (never `Pending`).
///
/// Infallible: seeding is an optimization over the lazy real-code fetch, so a
/// conflict, an empty seed, an unverifiable seed, or a verify error all degrade
/// to "purge / skip and fall back to lazy real code" rather than an error.
///
/// The two phases are factored into [`seed_batch`] and [`verify_pending_seeds`]
/// so the batched [`cold_start_many`](AdapterRegistry::cold_start_many) path can
/// seed many pools' claims and then verify them all in **one** call.
fn seed_and_verify(cache: &mut EvmCache, seeds: Vec<AdapterCodeSeed>) -> CodeSeedReport {
    let any_pending = seed_batch(cache, seeds);
    if !any_pending {
        return CodeSeedReport::default();
    }
    verify_pending_seeds(cache)
}

/// Seed a batch of adapter code claims into `cache`, applying the same skip
/// rules the single-pool path uses (skip a `Verified` same-hash claim, never
/// overwrite an `Etched` claim, treat an identical `Pending` claim as already
/// queued; catch `CodeSeedConflict`/`CodeSeedEmpty`/any other seed error as a
/// safe skip). Returns whether any address is now `Pending` and so needs a
/// [`verify_pending_seeds`] pass.
fn seed_batch(cache: &mut EvmCache, seeds: impl IntoIterator<Item = AdapterCodeSeed>) -> bool {
    let mut any_pending = false;
    for seed in seeds {
        match cache.code_seed_state(&seed.address) {
            // Already confirmed with the same hash: never re-seed / re-verify.
            Some(CodeSeedState::Verified { code_hash, .. }) if *code_hash == seed.code_hash => {
                continue;
            }
            // A deliberate local etch is authoritative: never overwrite it.
            Some(CodeSeedState::Etched { .. }) => continue,
            // Idempotent: an identical pending claim is already queued to verify.
            Some(CodeSeedState::Pending { code_hash }) if *code_hash == seed.code_hash => {
                any_pending = true;
                continue;
            }
            _ => {}
        }

        match cache.seed_account_code(seed.address, seed.runtime_bytecode) {
            Ok(_) => {
                // A warm-cache same-hash match marks `Verified` immediately; only
                // a genuinely new claim lands `Pending` and needs verification.
                if matches!(
                    cache.code_seed_state(&seed.address),
                    Some(CodeSeedState::Pending { .. })
                ) {
                    any_pending = true;
                }
            }
            // The cache already holds authoritative RPC-origin code with a
            // different hash, or the seed was empty: skip (existing code wins).
            Err(UpstreamCacheError::CodeSeedConflict { .. })
            | Err(UpstreamCacheError::CodeSeedEmpty { .. }) => {}
            // Any other seeding error is non-fatal too: skip, fall back to lazy.
            Err(_) => {}
        }
    }
    any_pending
}

/// Verify every pending code seed in `cache` in one call, purging any address
/// that could not be confirmed so no unverified bytes are left behind, and
/// return the resulting [`CodeSeedReport`].
///
/// Call only when [`seed_batch`] reported at least one pending seed.
fn verify_pending_seeds(cache: &mut EvmCache) -> CodeSeedReport {
    match cache.verify_code_seeds() {
        Ok(report) => {
            // Upstream leaves an unverifiable seed `Pending`; purging it prevents
            // simulating over unverified code (it falls back to lazy real code).
            for (address, _reason) in &report.unverifiable {
                cache.purge_account(*address);
            }
            CodeSeedReport::from(report)
        }
        Err(_) => {
            // Verification could not run: purge every still-pending seed so no
            // unverified bytes remain, and report nothing.
            for address in cache.pending_code_seeds() {
                cache.purge_account(address);
            }
            CodeSeedReport::default()
        }
    }
}

#[cfg(all(test, feature = "uniswap-v3"))]
mod tests {
    use super::*;
    use crate::adapters::ConcentratedLiquidityAdapter;
    use crate::adapters::storage::V3StorageLayout;
    use crate::adapters::types::{
        PoolKey, PoolRegistration, ProtocolMetadata, UniswapV2Metadata, V3Metadata,
    };
    use crate::adapters::v3_sync::V3SyncSpec;
    use alloy_primitives::Address;
    use std::sync::Arc;

    /// A genuine Uniswap V3 pool takes the canonical full spec (fee-growth,
    /// protocol-fees, and observation slots baked in).
    #[test]
    fn uniswap_v3_uses_the_canonical_full_spec() {
        let layout = V3StorageLayout::uniswap(10);
        let pool = PoolRegistration::new(PoolKey::UniswapV3(Address::repeat_byte(0x11)))
            .with_metadata(ProtocolMetadata::UniswapV3(
                V3Metadata::default()
                    .with_fee(500)
                    .with_storage_layout(layout),
            ));
        assert_eq!(v3_sync_spec(&pool), Some(V3SyncSpec::uniswap(layout)));
    }

    /// PancakeSwap V3 and Slipstream use the layout-only `core` spec (slot0 +
    /// liquidity + ticks) — their extra static/observation slots are not verified,
    /// so hydration must not inject Uniswap's positions for them.
    #[test]
    fn pancake_and_slipstream_use_the_core_spec_until_verified() {
        let pancake_layout = V3StorageLayout::pancake(10);
        let pancake = PoolRegistration::new(PoolKey::PancakeV3(Address::repeat_byte(0x22)))
            .with_metadata(ProtocolMetadata::PancakeV3(
                V3Metadata::default()
                    .with_fee(2500)
                    .with_storage_layout(pancake_layout),
            ));
        assert_eq!(
            v3_sync_spec(&pancake),
            Some(V3SyncSpec::core(pancake_layout))
        );

        let slip_layout = V3StorageLayout::slipstream(100);
        let slip = PoolRegistration::new(PoolKey::Slipstream(Address::repeat_byte(0x33)))
            .with_metadata(ProtocolMetadata::Slipstream(
                V3Metadata::default().with_storage_layout(slip_layout),
            ));
        assert_eq!(v3_sync_spec(&slip), Some(V3SyncSpec::core(slip_layout)));
    }

    /// A non-positive tick spacing would panic in `full_word_range` /
    /// `v3_word_position`; `v3_sync_spec` must return `None` so the pool falls
    /// back to the single-pool `cold_start` (Unsupported) instead of panicking in
    /// the `cold_start_many` fast path.
    #[test]
    fn non_positive_tick_spacing_is_not_fast_eligible() {
        let layout = V3StorageLayout::uniswap(0);
        let pool = PoolRegistration::new(PoolKey::UniswapV3(Address::repeat_byte(0x44)))
            .with_metadata(ProtocolMetadata::UniswapV3(
                V3Metadata::default()
                    .with_fee(500)
                    .with_storage_layout(layout),
            ));
        assert_eq!(v3_sync_spec(&pool), None);
        assert!(!supports_one_shot_hydration(&pool));
    }

    /// The eager warm step's target collection: the distinct quote-code targets
    /// across the pools, resolved via each pool's metadata. A quoter shared by two
    /// V3 pools collapses to one entry, a distinct quoter adds a second
    /// (order-stable), and a pool whose protocol has no registered adapter
    /// contributes nothing (it cannot be quoted, so warming its target is wasted).
    #[test]
    fn collect_quote_code_targets_dedupes_and_skips_unadaptered_pools() {
        let (q1, q2) = (Address::repeat_byte(0xd1), Address::repeat_byte(0xd2));
        let mut registry = AdapterRegistry::new();
        registry
            .register_adapter(Arc::new(ConcentratedLiquidityAdapter::default()))
            .expect("register the V3-family adapter");

        let v3 = |tag: u8, quoter: Address| {
            PoolRegistration::new(PoolKey::UniswapV3(Address::repeat_byte(tag))).with_metadata(
                ProtocolMetadata::UniswapV3(V3Metadata::default().with_quoter(quoter)),
            )
        };
        let pools = vec![
            v3(0x01, q1),
            v3(0x02, q1), // same quoter -> deduped away
            v3(0x03, q2), // distinct quoter -> a second, later entry
            // A V2 pool with real metadata but NO registered V2 adapter: skipped.
            PoolRegistration::new(PoolKey::UniswapV2(Address::repeat_byte(0x04)))
                .with_metadata(ProtocolMetadata::UniswapV2(UniswapV2Metadata::default())),
        ];

        assert_eq!(registry.collect_quote_code_targets(&pools), vec![q1, q2]);
    }
}

#[cfg(test)]
mod hydration_tests {
    use super::*;
    use alloy_primitives::Address;
    use alloy_provider::RootProvider;
    use alloy_provider::network::AnyNetwork;
    use alloy_rpc_client::RpcClient;
    use alloy_transport::mock::Asserter;
    use std::sync::Arc;

    async fn mock_cache() -> EvmCache {
        let provider = RootProvider::<AnyNetwork>::new(RpcClient::mocked(Asserter::new()));
        EvmCache::new(Arc::new(provider)).await
    }

    /// `inject_and_record` (the fast `cold_start_many` hydration path) reports
    /// every loaded slot in `verified`, only the slots whose value actually
    /// differs from the prior cache in `changed`, and injects the values.
    #[tokio::test(flavor = "multi_thread")]
    async fn inject_and_record_reports_loaded_and_changed_slots() {
        let pool = Address::repeat_byte(0x51);
        let unchanged = U256::from(1);
        let changed = U256::from(2);
        let fresh = U256::from(3);
        let value = U256::from(0xabc_u64);

        let mut cache = mock_cache().await;
        // Pre-seed two slots: one re-injected with the SAME value (no change),
        // one overwritten with a different value (a change).
        cache.inject_storage_batch(&[
            (pool, unchanged, value),
            (pool, changed, U256::from(10_u64)),
        ]);

        let entries = vec![
            (pool, unchanged, value),            // equals prior -> not "changed"
            (pool, changed, U256::from(20_u64)), // differs from prior -> "changed"
            (pool, fresh, value),                // cold prior (0) -> "changed"
        ];
        let hydrated = inject_and_record(&mut cache, entries);

        // Every loaded slot is verified, in program order.
        assert_eq!(
            hydrated.verified,
            vec![(pool, unchanged), (pool, changed), (pool, fresh)]
        );
        // Only the two that differ from their prior value are recorded as changed.
        assert_eq!(hydrated.changed.len(), 2);
        assert!(hydrated.changed.iter().any(|c| c.slot == changed
            && c.old == U256::from(10_u64)
            && c.new == U256::from(20_u64)));
        assert!(
            hydrated
                .changed
                .iter()
                .any(|c| c.slot == fresh && c.old == U256::ZERO && c.new == value)
        );
        // The fresh values landed in the cache.
        assert_eq!(
            cache.cached_storage_value(pool, changed),
            Some(U256::from(20_u64))
        );
        assert_eq!(cache.cached_storage_value(pool, fresh), Some(value));
    }
}