evm-fork-cache 0.2.1

Forked EVM state cache, snapshots, overlays, and simulation utilities for EVM search
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
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
//! Simulation error types and revert-reason decoding.
//!
//! Every EVM revert is either one of the two Solidity built-ins —
//! `Error(string)` (from `require`/`revert("msg")`) and `Panic(uint256)` (from
//! overflow, division-by-zero, etc.) — or a contract-defined *custom error*
//! identified by a 4-byte selector. This module decodes the two built-ins
//! natively and lets callers register any number of their own custom Solidity
//! errors with a [`RevertDecoder`].
//!
//! Application-specific selectors therefore live in the application, not in this
//! generic layer: define them with `sol!` and register them once.
//!
//! Note that [`Panic(uint256)`](RevertReason::Panic) codes that exceed
//! `u64::MAX` are dropped to `None` during decoding (and so surface as
//! [`RevertReason::Unknown`]). This is benign: real compiler-emitted panic
//! codes are single-byte constants (e.g. `0x11`, `0x32`).
//!
//! ```
//! use alloy_sol_types::{SolError, sol};
//! use evm_fork_cache::errors::{RevertDecoder, RevertReason};
//!
//! sol! {
//!     #[derive(Debug)]
//!     error Unauthorized(address caller);
//! }
//!
//! let decoder = RevertDecoder::new().with_error::<Unauthorized>();
//!
//! // 4-byte selector of `Unauthorized`, with no parameter bytes.
//! let raw = alloy_primitives::Bytes::from(Unauthorized::SELECTOR.to_vec());
//! match decoder.decode(&raw) {
//!     RevertReason::Custom(err) => assert_eq!(err.name, "Unauthorized(address)"),
//!     other => panic!("expected a custom error, got {other}"),
//! }
//! ```

use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use std::{borrow::Cow, io};

use alloy_primitives::{Address, B256, Bytes, FixedBytes, U256};
use alloy_sol_types::SolError;
use tracing::warn;

/// 4-byte selector of the standard Solidity `Error(string)` revert
/// (`0x08c379a0`), emitted by `require`/`revert("msg")`.
pub const ERROR_SELECTOR: [u8; 4] = [0x08, 0xc3, 0x79, 0xa0];

/// 4-byte selector of the standard Solidity `Panic(uint256)` revert
/// (`0x4e487b71`), emitted on overflow, division-by-zero, etc.
pub const PANIC_SELECTOR: [u8; 4] = [0x4e, 0x48, 0x7b, 0x71];

/// A decoded contract-defined custom error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CustomRevert {
    /// Human-readable signature, e.g. `"Unauthorized(address)"`.
    pub name: Cow<'static, str>,
    /// The error's 4-byte selector (the first 4 bytes of [`data`](Self::data)),
    /// the `keccak256` prefix of [`name`](Self::name).
    pub selector: FixedBytes<4>,
    /// Debug-formatted decoded parameters, when the body decoded successfully.
    ///
    /// `None` if only the selector matched but the ABI-encoded parameters could
    /// not be decoded (e.g. truncated revert data).
    pub params: Option<String>,
    /// Raw revert bytes (selector followed by ABI-encoded parameters).
    pub data: Bytes,
}

impl fmt::Display for CustomRevert {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.params {
            Some(params) => write!(f, "{params}"),
            None => write!(f, "{}", self.name),
        }
    }
}

/// A decoded EVM revert reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RevertReason {
    /// The call reverted with no return data (e.g. a bare `revert()` or `assert`
    /// in older Solidity, or an empty `require`).
    Empty,
    /// Standard Solidity `Error(string)` revert (e.g. `require(cond, "msg")`).
    Error(String),
    /// Standard Solidity `Panic(uint256)` revert (e.g. arithmetic overflow).
    Panic(u64),
    /// A contract-defined custom error whose selector was registered on the
    /// decoder via [`RevertDecoder::with_error`], [`RevertDecoder::register`],
    /// or [`RevertDecoder::register_raw`].
    Custom(CustomRevert),
    /// A selector that matched no built-in or registered custom error.
    Unknown {
        /// The 4-byte selector (right-padded with zeros if fewer than 4 bytes
        /// of revert data were returned).
        selector: FixedBytes<4>,
        /// Raw revert bytes.
        data: Bytes,
    },
}

impl fmt::Display for RevertReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RevertReason::Empty => write!(f, "<empty revert>"),
            RevertReason::Error(msg) => write!(f, "Error({msg:?})"),
            RevertReason::Panic(code) => write!(f, "Panic({code:#x})"),
            RevertReason::Custom(custom) => write!(f, "{custom}"),
            RevertReason::Unknown { selector, data } => {
                write!(f, "Unknown(selector={selector}, data_len={})", data.len())
            }
        }
    }
}

type DecodeFn = Arc<dyn Fn(&Bytes) -> Option<String> + Send + Sync>;

#[derive(Clone)]
struct CustomErrorDecoder {
    name: Cow<'static, str>,
    decode: DecodeFn,
}

/// Error returned when registering a custom error selector that already exists.
///
/// A [`RevertDecoder`] keeps the first decoder registered for a selector so a
/// later registration cannot silently change how existing revert data decodes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DuplicateSelectorError {
    /// The 4-byte selector that was already registered.
    pub selector: FixedBytes<4>,
    /// Signature/name of the existing registration that will be kept.
    pub existing: Cow<'static, str>,
    /// Signature/name of the attempted duplicate registration.
    pub attempted: Cow<'static, str>,
}

impl fmt::Display for DuplicateSelectorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "duplicate custom error selector {}: keeping {}, ignoring {}",
            self.selector, self.existing, self.attempted
        )
    }
}

impl std::error::Error for DuplicateSelectorError {}

/// Decodes raw EVM revert data into a [`RevertReason`].
///
/// The two standard Solidity built-ins — `Error(string)` and `Panic(uint256)` —
/// are always recognized. Register additional contract-defined custom errors
/// with [`with_error`](RevertDecoder::with_error),
/// [`register`](RevertDecoder::register), or
/// [`register_raw`](RevertDecoder::register_raw). Duplicate custom-error
/// selectors keep the first registration; use
/// [`try_register`](RevertDecoder::try_register) or
/// [`try_register_raw`](RevertDecoder::try_register_raw) when collisions should
/// be handled as errors instead of warnings.
///
/// The decoder is cheap to [`Clone`] and is `Send + Sync`, so a configured
/// decoder can be shared across parallel simulations.
#[derive(Clone, Default)]
pub struct RevertDecoder {
    custom: HashMap<[u8; 4], CustomErrorDecoder>,
}

impl fmt::Debug for RevertDecoder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut names: Vec<&str> = self.custom.values().map(|d| d.name.as_ref()).collect();
        names.sort_unstable();
        f.debug_struct("RevertDecoder")
            .field("custom_errors", &names)
            .finish()
    }
}

impl RevertDecoder {
    /// Create a decoder that recognizes only the standard Solidity built-ins
    /// (`Error(string)` and `Panic(uint256)`) and no custom errors.
    ///
    /// ```
    /// use evm_fork_cache::errors::RevertDecoder;
    ///
    /// let decoder = RevertDecoder::new();
    /// assert!(decoder.is_empty());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a `sol!`-generated custom error type for decoding, consuming and
    /// returning `self` for builder-style chaining.
    ///
    /// If the selector is already registered, the first registration is kept
    /// and a warning is emitted. Use [`try_register`](Self::try_register) when
    /// duplicate selectors should fail configuration.
    ///
    /// ```
    /// use alloy_sol_types::sol;
    /// use evm_fork_cache::errors::RevertDecoder;
    ///
    /// sol! {
    ///     #[derive(Debug)]
    ///     error SlippageExceeded(uint256 wanted, uint256 got);
    ///     #[derive(Debug)]
    ///     error Paused();
    /// }
    ///
    /// let decoder = RevertDecoder::new()
    ///     .with_error::<SlippageExceeded>()
    ///     .with_error::<Paused>();
    /// assert_eq!(decoder.len(), 2);
    /// ```
    pub fn with_error<E>(mut self) -> Self
    where
        E: SolError + fmt::Debug + 'static,
    {
        self.register::<E>();
        self
    }

    /// Register a `sol!`-generated custom error type for decoding.
    ///
    /// If an error with the same selector is already registered, the first
    /// registration is kept and a warning is emitted. Use
    /// [`try_register`](Self::try_register) to surface duplicates as errors.
    pub fn register<E>(&mut self) -> &mut Self
    where
        E: SolError + fmt::Debug + 'static,
    {
        if let Err(err) = self.try_register::<E>() {
            warn_duplicate_selector(&err);
        }
        self
    }

    /// Register a `sol!`-generated custom error type for decoding, returning an
    /// error when another custom error already owns the same selector.
    pub fn try_register<E>(&mut self) -> Result<&mut Self, DuplicateSelectorError>
    where
        E: SolError + fmt::Debug + 'static,
    {
        let decode: DecodeFn =
            Arc::new(|data: &Bytes| E::abi_decode(data).ok().map(|err| format!("{err:?}")));
        self.insert_custom_error(
            E::SELECTOR,
            CustomErrorDecoder {
                name: Cow::Borrowed(E::SIGNATURE),
                decode,
            },
        )
    }

    /// Register a custom error by raw selector, name, and parameter decoder.
    ///
    /// Use this when there is no `sol!`-generated type to hand — for example
    /// when the selector and signature come from an ABI loaded at runtime. The
    /// `decode` closure receives the full revert bytes (selector included) and
    /// returns the formatted parameters, or `None` if it cannot decode them.
    ///
    /// If the closure returns `None`, the selector still matches: the decode
    /// yields a [`RevertReason::Custom`] whose
    /// [`params`](CustomRevert::params) is `None`. If an error with the same
    /// selector is already registered, the first registration is kept and a
    /// warning is emitted. Use [`try_register_raw`](Self::try_register_raw) to
    /// surface duplicates as errors.
    ///
    /// ```
    /// use alloy_primitives::Bytes;
    /// use evm_fork_cache::errors::{RevertDecoder, RevertReason};
    ///
    /// let mut decoder = RevertDecoder::new();
    /// // A closure that decodes the parameters when there is a payload byte,
    /// // and otherwise reports a decode failure by returning `None`.
    /// decoder.register_raw([0xde, 0xad, 0xbe, 0xef], "MyError(uint256)", |data| {
    ///     (data.len() > 4).then(|| format!("payload {} bytes", data.len() - 4))
    /// });
    ///
    /// // Selector plus a payload byte: the closure decodes the parameters.
    /// let with_params = Bytes::from(vec![0xde, 0xad, 0xbe, 0xef, 0x00]);
    /// match decoder.decode(&with_params) {
    ///     RevertReason::Custom(custom) => {
    ///         assert_eq!(custom.name, "MyError(uint256)");
    ///         assert_eq!(custom.params.as_deref(), Some("payload 1 bytes"));
    ///     }
    ///     other => panic!("expected Custom, got {other}"),
    /// }
    ///
    /// // Bare selector: the closure returns `None`, but the selector still
    /// // matches, so the result is a `Custom` with `params == None`.
    /// let bare = Bytes::from(vec![0xde, 0xad, 0xbe, 0xef]);
    /// match decoder.decode(&bare) {
    ///     RevertReason::Custom(custom) => assert!(custom.params.is_none()),
    ///     other => panic!("expected Custom, got {other}"),
    /// }
    /// ```
    pub fn register_raw(
        &mut self,
        selector: [u8; 4],
        name: impl Into<Cow<'static, str>>,
        decode: impl Fn(&Bytes) -> Option<String> + Send + Sync + 'static,
    ) -> &mut Self {
        if let Err(err) = self.try_register_raw(selector, name, decode) {
            warn_duplicate_selector(&err);
        }
        self
    }

    /// Register a custom error by raw selector, name, and parameter decoder,
    /// returning an error when another custom error already owns the selector.
    ///
    /// The `decode` closure receives the full revert bytes (selector included)
    /// and returns formatted parameters, or `None` if the selector matched but
    /// the parameter payload could not be decoded.
    pub fn try_register_raw(
        &mut self,
        selector: [u8; 4],
        name: impl Into<Cow<'static, str>>,
        decode: impl Fn(&Bytes) -> Option<String> + Send + Sync + 'static,
    ) -> Result<&mut Self, DuplicateSelectorError> {
        self.insert_custom_error(
            selector,
            CustomErrorDecoder {
                name: name.into(),
                decode: Arc::new(decode),
            },
        )
    }

    /// Number of registered custom errors. The two Solidity built-ins are
    /// always recognized and are not counted, so a freshly
    /// [`new`](RevertDecoder::new) decoder reports `0`.
    pub fn len(&self) -> usize {
        self.custom.len()
    }

    /// Returns `true` if no custom errors are registered. The built-ins are
    /// always recognized regardless, so this is `true` for a freshly
    /// [`new`](RevertDecoder::new) decoder.
    pub fn is_empty(&self) -> bool {
        self.custom.is_empty()
    }

    /// Decode raw EVM revert data into a [`RevertReason`].
    ///
    /// Resolution order: the two Solidity built-ins (`Error(string)` and
    /// `Panic(uint256)`), then registered custom errors by selector, then
    /// [`RevertReason::Unknown`] for anything else. Empty input decodes to
    /// [`RevertReason::Empty`], and data shorter than 4 bytes decodes to
    /// [`RevertReason::Unknown`] with the selector right-padded with zeros.
    ///
    /// ```
    /// use alloy_primitives::{Bytes, U256};
    /// use alloy_sol_types::{Panic, SolError, sol};
    /// use evm_fork_cache::errors::{RevertDecoder, RevertReason, ERROR_SELECTOR};
    ///
    /// sol! {
    ///     #[derive(Debug)]
    ///     error Custom();
    /// }
    ///
    /// let decoder = RevertDecoder::new().with_error::<Custom>();
    ///
    /// // Built-in `Error(string)` decodes natively, without registration.
    /// // Layout: selector | offset(0x20) | length | utf8 bytes (padded).
    /// let mut bytes = ERROR_SELECTOR.to_vec();
    /// bytes.extend_from_slice(&{ let mut o = [0u8; 32]; o[31] = 0x20; o }); // offset
    /// bytes.extend_from_slice(&{ let mut l = [0u8; 32]; l[31] = 2; l });    // length 2
    /// bytes.extend_from_slice(b"hi");
    /// bytes.extend_from_slice(&[0u8; 30]);                                  // pad to 32
    /// assert_eq!(decoder.decode(&Bytes::from(bytes)), RevertReason::Error("hi".into()));
    ///
    /// // Built-in `Panic(uint256)` decodes natively too.
    /// let panic = Bytes::from(Panic { code: U256::from(0x11) }.abi_encode());
    /// assert_eq!(decoder.decode(&panic), RevertReason::Panic(0x11));
    ///
    /// // A registered selector resolves to `Custom`.
    /// let raw = Bytes::from(Custom::SELECTOR.to_vec());
    /// match decoder.decode(&raw) {
    ///     RevertReason::Custom(err) => assert_eq!(err.name, "Custom()"),
    ///     other => panic!("expected Custom, got {other}"),
    /// }
    ///
    /// // An unregistered selector falls through to `Unknown`.
    /// let unknown = Bytes::from(vec![0xde, 0xad, 0xbe, 0xef]);
    /// assert!(matches!(decoder.decode(&unknown), RevertReason::Unknown { .. }));
    /// ```
    pub fn decode(&self, data: &Bytes) -> RevertReason {
        if data.is_empty() {
            return RevertReason::Empty;
        }
        if data.len() < 4 {
            // Too short for a selector; surface the raw bytes as Unknown with a
            // right-padded selector so nothing is silently discarded.
            let mut selector = [0u8; 4];
            selector[..data.len()].copy_from_slice(&data[..]);
            return RevertReason::Unknown {
                selector: FixedBytes::from(selector),
                data: data.clone(),
            };
        }

        let selector: [u8; 4] = data[..4].try_into().expect("length checked >= 4");

        if selector == ERROR_SELECTOR
            && let Some(message) = decode_solidity_error_string(data)
        {
            return RevertReason::Error(message);
        }
        if selector == PANIC_SELECTOR
            && let Some(code) = decode_solidity_panic(data)
        {
            return RevertReason::Panic(code);
        }
        if let Some(entry) = self.custom.get(&selector) {
            return RevertReason::Custom(CustomRevert {
                name: entry.name.clone(),
                selector: FixedBytes::from(selector),
                params: (entry.decode)(data),
                data: data.clone(),
            });
        }

        RevertReason::Unknown {
            selector: FixedBytes::from(selector),
            data: data.clone(),
        }
    }

    fn insert_custom_error(
        &mut self,
        selector: [u8; 4],
        decoder: CustomErrorDecoder,
    ) -> Result<&mut Self, DuplicateSelectorError> {
        if let Some(existing) = self.custom.get(&selector) {
            return Err(DuplicateSelectorError {
                selector: FixedBytes::from(selector),
                existing: existing.name.clone(),
                attempted: decoder.name,
            });
        }

        self.custom.insert(selector, decoder);
        Ok(self)
    }
}

fn warn_duplicate_selector(err: &DuplicateSelectorError) {
    warn!(
        selector = %err.selector,
        existing = err.existing.as_ref(),
        attempted = err.attempted.as_ref(),
        "duplicate custom error selector registration ignored; keeping first registration"
    );
}

/// Decode revert data using only the standard Solidity built-ins.
///
/// For application-specific custom errors, build a [`RevertDecoder`] and call
/// [`RevertDecoder::decode`].
pub fn decode_revert_reason(data: &Bytes) -> RevertReason {
    static STANDARD: OnceLock<RevertDecoder> = OnceLock::new();
    STANDARD.get_or_init(RevertDecoder::new).decode(data)
}

/// Decode the `uint256` payload of a standard `Panic(uint256)` revert.
///
/// Delegates to alloy's built-in decoder (which validates the ABI encoding) and
/// returns `None` for codes that do not fit in a `u64`. Real compiler-emitted
/// panic codes are single-byte constants (e.g. `0x11` for arithmetic overflow,
/// `0x32` for out-of-bounds array access).
fn decode_solidity_panic(data: &Bytes) -> Option<u64> {
    alloy_sol_types::Panic::abi_decode(data)
        .ok()
        .and_then(|panic| u64::try_from(panic.code).ok())
}

/// Decode the string payload of a standard `Error(string)` revert.
///
/// Delegates to alloy's built-in decoder, which follows the ABI offset and
/// validates the length rather than assuming a fixed in-memory layout — so it
/// stays correct on non-standard or adversarial revert data.
fn decode_solidity_error_string(data: &Bytes) -> Option<String> {
    alloy_sol_types::Revert::abi_decode(data)
        .ok()
        .map(|revert| revert.reason)
}

/// A structured simulation revert with its decoded reason.
#[derive(Debug, Clone)]
pub struct SimulationError {
    /// Gas consumed before the revert.
    pub gas_used: u64,
    /// Raw revert data returned by the EVM (the bytes that were decoded into
    /// [`reason`](Self::reason)).
    pub revert_data: Bytes,
    /// The revert reason decoded from [`revert_data`](Self::revert_data).
    pub reason: RevertReason,
}

impl SimulationError {
    /// Create a simulation error from raw revert data, decoding with the
    /// standard Solidity built-ins only.
    pub fn from_revert(gas_used: u64, output: Bytes) -> Self {
        let reason = decode_revert_reason(&output);
        Self {
            gas_used,
            revert_data: output,
            reason,
        }
    }

    /// Create a simulation error from raw revert data, decoding custom errors
    /// with the supplied [`RevertDecoder`].
    pub fn from_revert_with(gas_used: u64, output: Bytes, decoder: &RevertDecoder) -> Self {
        let reason = decoder.decode(&output);
        Self {
            gas_used,
            revert_data: output,
            reason,
        }
    }

    /// The decoded revert reason. Equivalent to borrowing the public
    /// [`reason`](Self::reason) field.
    pub fn reason(&self) -> &RevertReason {
        &self.reason
    }

    /// The `Error(string)` message, if this was a standard string revert.
    pub fn revert_message(&self) -> Option<&str> {
        match &self.reason {
            RevertReason::Error(message) => Some(message.as_str()),
            _ => None,
        }
    }

    /// The panic code, if this was a standard `Panic(uint256)` revert.
    pub fn panic_code(&self) -> Option<u64> {
        match self.reason {
            RevertReason::Panic(code) => Some(code),
            _ => None,
        }
    }

    /// The decoded custom error, if a registered custom error matched.
    pub fn custom_error(&self) -> Option<&CustomRevert> {
        match &self.reason {
            RevertReason::Custom(custom) => Some(custom),
            _ => None,
        }
    }

    /// The 4-byte selector of the revert, if any (custom or unknown).
    pub fn selector(&self) -> Option<FixedBytes<4>> {
        match &self.reason {
            RevertReason::Custom(custom) => Some(custom.selector),
            RevertReason::Unknown { selector, .. } => Some(*selector),
            _ => None,
        }
    }

    /// `true` if the call reverted with no return data, i.e. the reason is
    /// [`RevertReason::Empty`].
    pub fn is_empty_revert(&self) -> bool {
        matches!(self.reason, RevertReason::Empty)
    }
}

impl fmt::Display for SimulationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "SimulationError(gas_used={}, reason={})",
            self.gas_used, self.reason
        )
    }
}

impl std::error::Error for SimulationError {}

/// Error raised when validating or refreshing the block-execution context
/// (`NUMBER` / `BASEFEE` / `COINBASE` / `PREVRANDAO` / `GASLIMIT` opcodes).
///
/// Under strict [`BlockContextRequirements`](crate::cache::BlockContextRequirements)
/// a missing header field surfaces loudly as one of these variants instead of
/// silently defaulting the corresponding EVM block-env field.
#[derive(Debug, thiserror::Error)]
pub enum BlockContextError {
    /// The block header could not be fetched (the provider errored or returned
    /// no block) while strict requirements demanded one at construction.
    #[error("block-context header fetch failed: {0}")]
    FetchFailed(String),
    /// A header was available but a required block-context field was absent.
    ///
    /// `field` is the lowercased field token (e.g. `"basefee"`, `"prevrandao"`).
    #[error("required block-context field missing: {field}")]
    MissingField {
        /// The lowercased name of the missing field.
        field: &'static str,
    },
}

/// Error returned when crate-managed synchronous RPC bridges cannot enter the
/// required tokio runtime context.
#[derive(Debug, Clone, thiserror::Error)]
pub enum RuntimeError {
    /// A current-thread runtime was active, but the crate needs
    /// `tokio::task::block_in_place`, which is available only on multi-thread
    /// runtimes.
    #[error(
        "evm-fork-cache RPC operations require a multi-thread tokio runtime; \
         found a current-thread runtime (block_in_place is not supported there). \
         Build the runtime with `tokio::runtime::Builder::new_multi_thread()` \
         or annotate with `#[tokio::main(flavor = \"multi_thread\")]`"
    )]
    CurrentThreadRuntime,
    /// No usable runtime handle was available.
    #[error(
        "evm-fork-cache RPC operations require a running multi-thread tokio runtime: {details}"
    )]
    MissingRuntime {
        /// The runtime lookup error rendered by tokio.
        details: String,
    },
}

/// Error returned by direct RPC call callbacks installed on [`EvmCache`].
///
/// [`EvmCache`]: crate::cache::EvmCache
#[derive(Debug, thiserror::Error)]
pub enum RpcError {
    /// Runtime precondition failure before the RPC call could be made.
    #[error(transparent)]
    Runtime(#[from] RuntimeError),
    /// The provider rejected or failed the RPC request.
    #[error("RPC provider call {operation} failed: {details}")]
    Provider {
        /// JSON-RPC method or high-level operation name.
        operation: &'static str,
        /// Provider/transport error text. Alloy's provider error type is generic
        /// over the transport, so this boundary preserves it as display text.
        details: String,
    },
    /// Caller-provided callback failure.
    #[error("custom RPC callback failed: {message}")]
    Custom {
        /// Caller-provided error text.
        message: String,
    },
}

impl RpcError {
    /// Build a provider-failure error from any displayable provider error.
    pub fn provider(operation: &'static str, source: impl fmt::Display) -> Self {
        Self::Provider {
            operation,
            details: source.to_string(),
        }
    }

    /// Build a custom-callback error.
    pub fn custom(message: impl Into<String>) -> Self {
        Self::Custom {
            message: message.into(),
        }
    }
}

/// Error returned by storage/proof batch callbacks.
///
/// `Clone` lets a batch-level failure (one `eth_call` or one JSON-RPC batch)
/// be reported once per affected slot without re-stringifying the source.
#[derive(Debug, Clone, thiserror::Error)]
pub enum StorageFetchError {
    /// Runtime precondition failure before a fetch could be made.
    #[error(transparent)]
    Runtime(#[from] RuntimeError),
    /// The provider rejected or failed an RPC request.
    #[error("storage/provider request {operation} failed: {details}")]
    Provider {
        /// JSON-RPC method or high-level operation name.
        operation: &'static str,
        /// Provider/transport error text. Alloy's provider error type is generic
        /// over the transport, so this boundary preserves it as display text.
        details: String,
    },
    /// JSON-RPC batch serialization failed before sending.
    #[error("failed to serialize storage batch request: {details}")]
    Serialization {
        /// Serialization error text.
        details: String,
    },
    /// Sending the JSON-RPC batch failed before per-call waiters could resolve.
    #[error("failed to send storage batch request: {details}")]
    BatchSend {
        /// Send error text.
        details: String,
    },
    /// Caller-provided callback failure.
    #[error("custom storage/proof fetcher failed: {message}")]
    Custom {
        /// Caller-provided error text.
        message: String,
    },
}

impl StorageFetchError {
    /// Build a provider-failure error from any displayable provider error.
    pub fn provider(operation: &'static str, source: impl fmt::Display) -> Self {
        Self::Provider {
            operation,
            details: source.to_string(),
        }
    }

    /// Build a batch-send error.
    pub fn batch_send(source: impl fmt::Display) -> Self {
        Self::BatchSend {
            details: source.to_string(),
        }
    }

    /// Build a serialization error.
    pub fn serialization(source: impl fmt::Display) -> Self {
        Self::Serialization {
            details: source.to_string(),
        }
    }

    /// Build a custom-callback error.
    pub fn custom(message: impl Into<String>) -> Self {
        Self::Custom {
            message: message.into(),
        }
    }
}

/// Result type returned by storage/proof batch callbacks.
pub type StorageFetchResult<T> = Result<T, StorageFetchError>;

/// Persistence failure for crate-owned on-disk cache files.
#[derive(Debug, thiserror::Error)]
pub enum PersistenceError {
    /// bincode serialization failed.
    #[error("failed to serialize {label}: {source}")]
    Serialize {
        /// Human-readable cache payload label.
        label: &'static str,
        /// bincode serialization failure.
        #[source]
        source: bincode::Error,
    },
    /// A parent directory could not be created.
    #[error("failed to create directory {path:?}: {source}")]
    CreateDir {
        /// Directory path.
        path: PathBuf,
        /// Filesystem error.
        #[source]
        source: io::Error,
    },
    /// A file write failed.
    #[error("failed to write {path:?}: {source}")]
    Write {
        /// File path.
        path: PathBuf,
        /// Filesystem error.
        #[source]
        source: io::Error,
    },
}

impl PersistenceError {
    /// Build a bincode serialization error.
    pub(crate) fn serialize(label: &'static str, source: bincode::Error) -> Self {
        Self::Serialize { label, source }
    }

    /// Build a directory creation error.
    pub(crate) fn create_dir(path: impl Into<PathBuf>, source: io::Error) -> Self {
        Self::CreateDir {
            path: path.into(),
            source,
        }
    }

    /// Build a file write error.
    pub(crate) fn write(path: impl Into<PathBuf>, source: io::Error) -> Self {
        Self::Write {
            path: path.into(),
            source,
        }
    }
}

/// General cache-operation error for APIs that execute or mutate local fork
/// state but do not classify EVM reverts as [`SimError`].
#[derive(Debug, thiserror::Error)]
pub enum CacheError {
    /// Runtime precondition failure.
    #[error(transparent)]
    Runtime(#[from] RuntimeError),
    /// Direct RPC callback failure.
    #[error(transparent)]
    Rpc(#[from] RpcError),
    /// On-disk persistence failure.
    #[error(transparent)]
    Persistence(#[from] PersistenceError),
    /// A storage verification/reconciliation path had no batch fetcher.
    #[error("storage verification requires a storage batch fetcher")]
    MissingStorageBatchFetcher,
    /// Code-seed verification had pending seeds but no account-fields fetcher.
    #[error("code-seed verification requires an account fields fetcher")]
    MissingAccountFieldsFetcher,
    /// Reconciliation could not fetch any requested slot, so it cannot prove the
    /// local state fresh.
    #[error(
        "reconcile could not fetch any of the {requested} requested slot(s) \
         (no usable storage fetcher / provider unreachable)"
    )]
    ReconcileFetchFailed {
        /// Number of requested slots.
        requested: usize,
    },
    /// Account fetch failed.
    #[error("failed to fetch account {address}: {details}")]
    AccountFetch {
        /// Account address.
        address: Address,
        /// Backend/provider error text.
        details: String,
    },
    /// A canonical code seed contradicts code already fetched from the chain.
    ///
    /// Chain-fetched state is authoritative over templates: the seed is
    /// rejected and the cached code is left untouched. If the caller believes
    /// the chain has moved (e.g. a redeploy), purge the account first and
    /// re-seed.
    #[error(
        "code seed for {address} conflicts with chain-fetched code \
         (cached hash {cached}, seeded hash {seeded})"
    )]
    CodeSeedConflict {
        /// Account address.
        address: Address,
        /// Code hash of the RPC-origin code already in the cache.
        cached: B256,
        /// Code hash of the rejected seed.
        seeded: B256,
    },
    /// A code seed/etch was given empty bytes; claiming an address is
    /// code-less is not a supported seed (that is what verification's
    /// `codeless` classification reports).
    #[error("cannot seed/etch empty code at {address}")]
    CodeSeedEmpty {
        /// Account address.
        address: Address,
    },
    /// Storage read failed.
    #[error("storage read failed for {address} slot {slot}: {details}")]
    StorageRead {
        /// Contract address.
        address: Address,
        /// Storage slot.
        slot: U256,
        /// Backend/provider error text.
        details: String,
    },
    /// Storage insert failed.
    #[error("storage insert failed for {address} slot {slot}: {details}")]
    StorageInsert {
        /// Contract address.
        address: Address,
        /// Storage slot.
        slot: U256,
        /// Backend error text.
        details: String,
    },
    /// Transaction environment construction failed.
    #[error("failed to build transaction environment: {details}")]
    TxEnv {
        /// Builder error text.
        details: String,
    },
    /// revm returned a host/database transaction error.
    #[error("failed to transact: {details}")]
    Transact {
        /// revm/database error text.
        details: String,
    },
    /// A helper that requires a successful EVM call observed a revert or halt.
    #[error("EVM call did not succeed: {result}")]
    CallNotSuccessful {
        /// Debug rendering of the execution result.
        result: String,
    },
    /// A debug/trace RPC response could not be parsed into the cache's typed
    /// block state-diff representation.
    #[error("failed to parse block state trace: {details}")]
    TraceParse {
        /// Parser error text.
        details: String,
    },
    /// ABI or helper-specific decode failure.
    #[error("failed to decode {what}: {details}")]
    Decode {
        /// Human-readable decode target.
        what: &'static str,
        /// Decoder error text.
        details: String,
    },
    /// A typed Solidity call executed but did not succeed.
    #[error("Solidity call {signature} from {from:?} to {to:?} did not succeed: {result}")]
    SolCallFailed {
        /// Solidity function signature.
        signature: &'static str,
        /// Call sender.
        from: Address,
        /// Call target.
        to: Address,
        /// Debug rendering of the execution result.
        result: String,
    },
    /// A typed Solidity call returned malformed data.
    #[error(
        "failed to decode Solidity call {signature} return data from {from:?} to {to:?}: \
         output_len={output_len}, error: {details}"
    )]
    SolCallDecode {
        /// Solidity function signature.
        signature: &'static str,
        /// Call sender.
        from: Address,
        /// Call target.
        to: Address,
        /// Return-data length in bytes.
        output_len: usize,
        /// Decoder error text.
        details: String,
    },
    /// Deployment succeeded without a created address.
    #[error("contract deployment succeeded but no address returned")]
    DeploymentMissingAddress,
    /// Deployment reverted.
    #[error("contract deployment reverted: 0x{output_hex}")]
    DeploymentReverted {
        /// Hex-encoded revert output.
        output_hex: String,
    },
    /// Deployment halted.
    #[error("contract deployment halted: {reason}")]
    DeploymentHalted {
        /// Debug rendering of the halt reason.
        reason: String,
    },
    /// Source account did not contain bytecode for an override.
    #[error("no bytecode found at source address {source_address}")]
    MissingSourceBytecode {
        /// Source address.
        source_address: Address,
    },
    /// Runtime bytecode was required but absent or empty.
    #[error("{role} account {address} has no runtime bytecode")]
    MissingRuntimeCode {
        /// Account role in the operation.
        role: &'static str,
        /// Account address.
        address: Address,
    },
    /// Target account was required but absent.
    #[error(
        "target account {target} not found; use override_or_create_account_code for synthetic targets"
    )]
    MissingTargetAccount {
        /// Target address.
        target: Address,
    },
    /// Target account fetch failed while validating an override target.
    #[error("failed to fetch target account {target}: {details}")]
    TargetAccountFetch {
        /// Target address.
        target: Address,
        /// Backend/provider error text.
        details: String,
    },
}

impl CacheError {
    /// Convert a transaction-builder error into [`CacheError::TxEnv`].
    pub fn tx_env(source: impl fmt::Debug) -> Self {
        Self::TxEnv {
            details: format!("{source:?}"),
        }
    }

    /// Convert a revm host/database transaction error into
    /// [`CacheError::Transact`].
    pub fn transact(source: impl fmt::Debug) -> Self {
        Self::Transact {
            details: format!("{source:?}"),
        }
    }
}

/// Result type returned by cache APIs.
pub type CacheResult<T, E = CacheError> = Result<T, E>;

/// Error for immutable snapshot-overlay execution helpers that do not classify
/// reverts as [`SimError`].
#[derive(Debug, thiserror::Error)]
pub enum OverlayError {
    /// Transaction environment construction failed.
    #[error("failed to build transaction environment: {details}")]
    TxEnv {
        /// Builder error text.
        details: String,
    },
    /// revm returned a host/database transaction error.
    #[error("failed to transact: {details}")]
    Transact {
        /// revm/database error text.
        details: String,
    },
    /// A typed Solidity call ([`EvmOverlay::call_sol`](crate::cache::EvmOverlay::call_sol))
    /// did not `Success` (it reverted or halted).
    #[error("Solidity call {signature} from {from:?} to {to:?} did not succeed: {result}")]
    SolCallFailed {
        /// The call's Solidity signature.
        signature: &'static str,
        /// Caller address.
        from: Address,
        /// Callee address.
        to: Address,
        /// Debug rendering of the non-`Success` result.
        result: String,
    },
    /// A typed Solidity call succeeded but its return data could not be decoded.
    #[error(
        "failed to decode return of {signature} from {from:?} to {to:?} ({output_len} bytes): {details}"
    )]
    SolCallDecode {
        /// The call's Solidity signature.
        signature: &'static str,
        /// Caller address.
        from: Address,
        /// Callee address.
        to: Address,
        /// Length of the undecodable return data.
        output_len: usize,
        /// Decoder error text.
        details: String,
    },
}

impl OverlayError {
    /// Convert a transaction-builder error into [`OverlayError::TxEnv`].
    pub fn tx_env(source: impl fmt::Debug) -> Self {
        Self::TxEnv {
            details: format!("{source:?}"),
        }
    }

    /// Convert a revm host/database transaction error into
    /// [`OverlayError::Transact`].
    pub fn transact(source: impl fmt::Debug) -> Self {
        Self::Transact {
            details: format!("{source:?}"),
        }
    }
}

/// Result type returned by overlay APIs that return raw [`ExecutionResult`]
/// values instead of classifying reverts.
///
/// [`ExecutionResult`]: revm::context::result::ExecutionResult
pub type OverlayResult<T, E = OverlayError> = Result<T, E>;

/// Host-side failure for simulation entry points.
#[derive(Debug, thiserror::Error)]
pub enum SimHostError {
    /// Transaction environment construction failed.
    #[error("failed to build transaction environment: {details}")]
    TxEnv {
        /// Builder error text.
        details: String,
    },
    /// revm returned a host/database transaction error.
    #[error("failed to transact: {details}")]
    Transact {
        /// revm/database error text.
        details: String,
    },
    /// Database read failed outside a transaction execution.
    #[error("database operation failed: {details}")]
    Database {
        /// Database error text.
        details: String,
    },
    /// Cache helper failed.
    #[error(transparent)]
    Cache(#[from] CacheError),
    /// Overlay helper failed.
    #[error(transparent)]
    Overlay(#[from] OverlayError),
}

impl SimHostError {
    /// Convert a transaction-builder error into [`SimHostError::TxEnv`].
    pub fn tx_env(source: impl fmt::Debug) -> Self {
        Self::TxEnv {
            details: format!("{source:?}"),
        }
    }

    /// Convert a revm host/database transaction error into
    /// [`SimHostError::Transact`].
    pub fn transact(source: impl fmt::Debug) -> Self {
        Self::Transact {
            details: format!("{source:?}"),
        }
    }

    /// Convert a database error into [`SimHostError::Database`].
    pub fn database(source: impl fmt::Debug) -> Self {
        Self::Database {
            details: format!("{source:?}"),
        }
    }
}

/// Multicall3 helper failure.
#[derive(Debug, thiserror::Error)]
pub enum MulticallError {
    /// Underlying EVM cache call failed.
    #[error(transparent)]
    Cache(#[from] CacheError),
    /// The aggregate3 call reverted or halted.
    #[error("Multicall3 aggregate call failed: {result}")]
    AggregateFailed {
        /// Debug rendering of the execution result.
        result: String,
    },
    /// A per-call result marked `success = false`.
    #[error("multicall result indicates the call failed")]
    CallFailed,
    /// ABI decode failure.
    #[error("failed to decode multicall result: {details}")]
    Decode {
        /// Decoder error text.
        details: String,
    },
}

/// Result type returned by Multicall3 helpers.
pub type MulticallResult<T> = Result<T, MulticallError>;

/// Deployment and Foundry-artifact loading failure.
#[derive(Debug, thiserror::Error)]
pub enum DeployError {
    /// Artifact file could not be read.
    #[error("failed to read Foundry artifact at {path}: {source}")]
    ReadArtifact {
        /// Artifact path.
        path: PathBuf,
        /// Filesystem error.
        #[source]
        source: io::Error,
    },
    /// Artifact JSON was invalid.
    #[error("failed to parse Foundry artifact JSON at {path}: {source}")]
    ParseArtifact {
        /// Artifact path.
        path: PathBuf,
        /// JSON parse error.
        #[source]
        source: serde_json::Error,
    },
    /// Artifact had no bytecode field.
    #[error("artifact {path} has no `bytecode` field")]
    MissingBytecodeField {
        /// Artifact path.
        path: PathBuf,
    },
    /// Artifact bytecode was not a supported string shape.
    #[error("artifact {path} has no `bytecode.object` string")]
    MissingBytecodeObject {
        /// Artifact path.
        path: PathBuf,
    },
    /// Bytecode was empty.
    #[error("empty bytecode")]
    EmptyBytecode,
    /// Bytecode still contains unresolved Foundry library placeholders.
    #[error("bytecode contains unresolved library placeholders")]
    UnresolvedLibraryPlaceholders,
    /// Hex bytecode could not be decoded.
    #[error("invalid hex bytecode: {details}")]
    InvalidHex {
        /// Hex decoder error text.
        details: String,
    },
    /// Underlying cache operation failed.
    #[error(transparent)]
    Cache(#[from] CacheError),
    /// Artifact deployment failed, with path context.
    #[error("deploying Foundry artifact {path} failed: {source}")]
    ArtifactDeploy {
        /// Artifact path.
        path: PathBuf,
        /// Cache operation failure.
        #[source]
        source: CacheError,
    },
    /// Target validation failed before etching.
    #[error("validating target contract {target} failed: {source}")]
    TargetValidation {
        /// Target address.
        target: Address,
        /// Cache operation failure.
        #[source]
        source: CacheError,
    },
    /// Runtime bytecode etch failed.
    #[error("etching runtime bytecode at {target} failed: {source}")]
    EtchRuntime {
        /// Target address.
        target: Address,
        /// Cache operation failure.
        #[source]
        source: CacheError,
    },
}

/// Result type returned by deployment helpers.
pub type DeployResult<T> = Result<T, DeployError>;

/// Access-list pricing query failure.
#[derive(Debug, thiserror::Error)]
pub enum AccessListError {
    /// Provider/oracle query failed.
    #[error("failed to query {operation}: {details}")]
    Query {
        /// Operation being queried.
        operation: &'static str,
        /// Provider/transport error text.
        details: String,
    },
}

impl AccessListError {
    /// Build a query error from any displayable provider error.
    pub fn query(operation: &'static str, source: impl fmt::Display) -> Self {
        Self::Query {
            operation,
            details: source.to_string(),
        }
    }
}

/// Result type returned by access-list pricing helpers.
pub type AccessListResult<T> = Result<T, AccessListError>;

/// Error returned by speculative freshness orchestration.
#[derive(Debug, thiserror::Error)]
pub enum FreshnessError {
    /// The validation handle was already consumed.
    #[error("validation handle already consumed")]
    ValidationHandleConsumed,
    /// The background validation task failed to join.
    #[error("validation task failed: {source}")]
    ValidationTaskFailed {
        /// Tokio join failure.
        #[source]
        source: tokio::task::JoinError,
    },
    /// An optimistic simulation failed before validation was spawned.
    #[error(transparent)]
    Overlay(#[from] OverlayError),
}

/// Result type returned by freshness APIs.
pub type FreshnessResult<T> = Result<T, FreshnessError>;

/// Result type returned by simulation entry points: `Ok(T)` on success, or a
/// [`SimError`] distinguishing a transaction-level revert, an EVM halt, and a
/// host-side failure.
pub type SimulationResult<T> = Result<T, SimError>;

/// Error returned by simulation entry points.
///
/// Distinguishes the three outcomes a caller must branch on: a transaction-level
/// [`Revert`](SimError::Revert) (with a decoded reason), an EVM
/// [`Halt`](SimError::Halt) (e.g. out of gas), and a host-side
/// [`Other`](SimError::Other) failure (RPC, database, ABI encoding).
///
/// Note that when a revert decodes to [`RevertReason::Panic`], panic codes
/// exceeding `u64::MAX` are dropped to `None` and so surface as
/// [`RevertReason::Unknown`] rather than `Panic`. This is benign: real
/// compiler-emitted panic codes are single-byte constants.
#[derive(Debug, thiserror::Error)]
pub enum SimError {
    /// The transaction reverted; carries the decoded revert.
    #[error("transaction reverted: {0}")]
    Revert(#[source] Box<SimulationError>),
    /// The EVM halted without returning revert data (e.g. out of gas, stack
    /// overflow). `reason` is the debug rendering of revm's halt reason.
    #[error("transaction halted: {reason} (gas used {gas_used})")]
    Halt {
        /// Debug rendering of the EVM halt reason.
        reason: String,
        /// Gas consumed before the halt.
        gas_used: u64,
    },
    /// An unexpected host-side error (RPC, database, ABI encoding).
    #[error("{0}")]
    Other(#[source] SimHostError),
}

impl SimError {
    /// `true` if this is a transaction-level revert, i.e. the
    /// [`Revert`](SimError::Revert) variant.
    pub fn is_revert(&self) -> bool {
        matches!(self, SimError::Revert(_))
    }

    /// `true` if the EVM halted without returning revert data (e.g. out of
    /// gas), i.e. the [`Halt`](SimError::Halt) variant.
    pub fn is_halt(&self) -> bool {
        matches!(self, SimError::Halt { .. })
    }

    /// The decoded [`SimulationError`] if this is a
    /// [`Revert`](SimError::Revert), or `None` for a
    /// [`Halt`](SimError::Halt) or [`Other`](SimError::Other) error.
    pub fn as_revert(&self) -> Option<&SimulationError> {
        match self {
            SimError::Revert(e) => Some(e),
            _ => None,
        }
    }
}

impl From<SimHostError> for SimError {
    fn from(e: SimHostError) -> Self {
        SimError::Other(e)
    }
}

impl From<CacheError> for SimError {
    fn from(e: CacheError) -> Self {
        SimError::Other(e.into())
    }
}

impl From<OverlayError> for SimError {
    fn from(e: OverlayError) -> Self {
        SimError::Other(e.into())
    }
}

impl From<SimulationError> for SimError {
    fn from(e: SimulationError) -> Self {
        SimError::Revert(Box::new(e))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy_primitives::{Address, U256};
    use alloy_sol_types::sol;

    sol! {
        #[derive(Debug)]
        error Unauthorized(address caller);
        #[derive(Debug)]
        error Paused();
        #[derive(Debug)]
        error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
    }

    /// Build ABI-encoded revert data for a standard `Error(string)` revert.
    /// Layout: selector(4) | offset(32) | length(32) | utf8 bytes (padded).
    fn encode_solidity_error(message: &str) -> Bytes {
        let bytes = message.as_bytes();
        let mut out = Vec::new();
        out.extend_from_slice(&ERROR_SELECTOR);

        // Offset to the string data (always 0x20 from the start of args).
        let mut offset = [0u8; 32];
        offset[31] = 0x20;
        out.extend_from_slice(&offset);

        // String length (assumed < 256 for these test fixtures).
        let mut length = [0u8; 32];
        length[31] = bytes.len() as u8;
        out.extend_from_slice(&length);

        // String bytes, right-padded to a 32-byte boundary.
        out.extend_from_slice(bytes);
        let pad = (32 - (bytes.len() % 32)) % 32;
        out.extend(std::iter::repeat_n(0u8, pad));

        Bytes::from(out)
    }

    #[test]
    fn decodes_solidity_error_string() {
        let data = encode_solidity_error("transfer amount exceeds balance");
        let reason = decode_revert_reason(&data);
        assert_eq!(
            reason,
            RevertReason::Error("transfer amount exceeds balance".to_string())
        );

        let err = SimulationError::from_revert(21_000, data);
        assert_eq!(
            err.revert_message(),
            Some("transfer amount exceeds balance")
        );
        assert!(err.panic_code().is_none());
        assert!(err.custom_error().is_none());
    }

    #[test]
    fn decodes_panic_uint256() {
        // selector(4) | uint256 panic code (0x11 = arithmetic overflow).
        let mut data = PANIC_SELECTOR.to_vec();
        let mut code = [0u8; 32];
        code[31] = 0x11;
        data.extend_from_slice(&code);
        let data = Bytes::from(data);

        let reason = decode_revert_reason(&data);
        assert_eq!(reason, RevertReason::Panic(0x11));

        let err = SimulationError::from_revert(0, data);
        assert_eq!(err.panic_code(), Some(0x11));
        assert!(err.revert_message().is_none());
    }

    #[test]
    fn standard_decoder_does_not_recognize_custom_errors() {
        // A registered-only selector is Unknown to the standard decoder.
        let data = Bytes::from(Paused::SELECTOR.to_vec());
        match decode_revert_reason(&data) {
            RevertReason::Unknown { selector, .. } => {
                assert_eq!(selector.as_slice(), &Paused::SELECTOR);
            }
            other => panic!("expected Unknown, got {other}"),
        }
    }

    #[test]
    fn decodes_registered_custom_error_without_params() {
        let decoder = RevertDecoder::new().with_error::<Paused>();
        let data = Bytes::from(Paused::SELECTOR.to_vec());

        match decoder.decode(&data) {
            RevertReason::Custom(custom) => {
                assert_eq!(custom.name, "Paused()");
                assert_eq!(custom.selector.as_slice(), &Paused::SELECTOR);
                assert_eq!(custom.params.as_deref(), Some("Paused"));
            }
            other => panic!("expected Custom, got {other}"),
        }
    }

    #[test]
    fn decodes_registered_custom_error_with_params() {
        let decoder = RevertDecoder::new()
            .with_error::<Unauthorized>()
            .with_error::<ERC20InsufficientBalance>();

        let caller = Address::repeat_byte(0xAB);
        let data = Bytes::from(Unauthorized { caller }.abi_encode());
        let custom = match decoder.decode(&data) {
            RevertReason::Custom(custom) => custom,
            other => panic!("expected Custom, got {other}"),
        };
        assert_eq!(custom.name, "Unauthorized(address)");
        let params = custom.params.expect("params should decode");
        // The Debug rendering of the decoded struct includes the address.
        assert!(params.contains(&format!("{caller:?}")), "got {params}");

        // The IERC6093 standard error decodes through the same mechanism.
        let data = Bytes::from(
            ERC20InsufficientBalance {
                sender: caller,
                balance: U256::from(1u64),
                needed: U256::from(2u64),
            }
            .abi_encode(),
        );
        match decoder.decode(&data) {
            RevertReason::Custom(custom) => {
                assert_eq!(
                    custom.name,
                    "ERC20InsufficientBalance(address,uint256,uint256)"
                );
            }
            other => panic!("expected Custom, got {other}"),
        }
    }

    #[test]
    fn register_raw_decodes_by_selector() {
        let mut decoder = RevertDecoder::new();
        decoder.register_raw([0xde, 0xad, 0xbe, 0xef], "MyError(uint256)", |data| {
            Some(format!("raw {} bytes", data.len()))
        });

        let data = Bytes::from(vec![0xde, 0xad, 0xbe, 0xef, 0x00]);
        match decoder.decode(&data) {
            RevertReason::Custom(custom) => {
                assert_eq!(custom.name, "MyError(uint256)");
                assert_eq!(custom.params.as_deref(), Some("raw 5 bytes"));
            }
            other => panic!("expected Custom, got {other}"),
        }
    }

    #[test]
    fn unknown_blob_is_classified_as_unknown() {
        let data = Bytes::from(vec![0xde, 0xad, 0xbe, 0xef, 0x00, 0x01, 0x02, 0x03]);
        match decode_revert_reason(&data) {
            RevertReason::Unknown {
                selector,
                data: blob,
            } => {
                assert_eq!(selector.as_slice(), &[0xde, 0xad, 0xbe, 0xef]);
                assert_eq!(blob.len(), 8);
            }
            other => panic!("expected Unknown, got {other}"),
        }

        let err = SimulationError::from_revert(0, data);
        assert_eq!(
            err.selector().map(|s| s.to_vec()),
            Some(vec![0xde, 0xad, 0xbe, 0xef])
        );
        assert!(!err.is_empty_revert());
    }

    #[test]
    fn empty_revert_data_decodes_to_empty() {
        let reason = decode_revert_reason(&Bytes::new());
        assert_eq!(reason, RevertReason::Empty);

        let err = SimulationError::from_revert(0, Bytes::new());
        assert!(err.is_empty_revert());
        assert!(err.selector().is_none());
    }

    #[test]
    fn data_shorter_than_selector_is_unknown_with_padded_selector() {
        let data = Bytes::from(vec![0x01, 0x02, 0x03]);
        match decode_revert_reason(&data) {
            RevertReason::Unknown { selector, .. } => {
                assert_eq!(selector.as_slice(), &[0x01, 0x02, 0x03, 0x00]);
            }
            other => panic!("expected Unknown, got {other}"),
        }
    }
}