kanatoko 29.1.2

Test Soroban contracts against captured Stellar network state
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
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
//! One-scenario automatic capture and strict replay.

use std::{
    cell::RefCell,
    collections::BTreeSet,
    fmt::Write as _,
    fs,
    panic::{catch_unwind, AssertUnwindSafe, Location},
    path::{Path, PathBuf},
    rc::Rc,
};

use sha2::{Digest, Sha256};
use soroban_env_host::{
    xdr::{
        AccountEntry, AccountEntryExt, AccountId, ContractExecutable, ContractId, Hash,
        LedgerEntry, LedgerEntryData, LedgerEntryExt, LedgerKey, LedgerKeyAccount, PublicKey,
        ScAddress, ScSymbol, ScVal, SequenceNumber, String32, Thresholds, Uint256, VecM,
    },
    InvocationResources,
};
use soroban_sdk::{
    testutils::Address as _, Address, ConstructorArgs, Env, IntoVal, MuxedAddress, Symbol,
    TryFromVal, Val, Vec as SorobanVec,
};
use thiserror::Error;

use crate::{
    capture::{
        contract_instance_key, LocalLedger, TrackingSource, MAINNET_PASSPHRASE, TESTNET_PASSPHRASE,
    },
    fixture::{executed_protocol_version, ProtocolPolicy},
    runtime::{fork_env, network_ledger_snapshot, restore_network_protocol, ForkEnvSeed},
    strict::{
        detached_diagnostics, detached_snapshot_evidence, invocation_values, invoke_once,
        invoke_outcome, is_nonce_data, state_diff, strip_new_mock_nonces,
    },
    AppliedAuthMode, AuthorizationTree, CaptureBuilder, CaptureError, CapturedFixture,
    InvocationFailure, InvokeErrorKind, InvokeOutcome, InvokeRequest, Receipt, ReceiptDisposition,
    StateChange, StrictForkError,
};

const DEFAULT_MAINNET_RPC_URL: &str = "https://mainnet.sorobanrpc.com";
const DEFAULT_TESTNET_RPC_URL: &str = "https://soroban-testnet.stellar.org";
const LOCAL_ACCOUNT_DOMAIN: &[u8] = b"kanatoko.local-account.v2";
const LOCAL_CONTRACT_DOMAIN: &[u8] = b"kanatoko.local-contract.v1";
const DEFAULT_CACHE_DOMAIN: &[u8] = b"kanatoko.default-cache.v2";
const DEFAULT_CACHE_NAME_MAX: usize = 80;
const DEFAULT_CACHE_HASH_HEX: usize = 12;

/// Creates an automatic mainnet runner using
/// `https://mainnet.sorobanrpc.com` by default.
///
/// The same scenario closure performs dependency discovery and the final
/// strict replay. Every contract and account enters the scenario explicitly
/// through [`ScenarioFork`]; no address is privileged as a capture root.
/// A default cache path under `.kanatoko/` is derived from the current thread
/// name and this callsite. [`AutoRunner::cache`] remains an explicit override.
///
#[must_use]
#[track_caller]
pub fn mainnet() -> AutoRunner {
    network_runner(
        DEFAULT_MAINNET_RPC_URL,
        MAINNET_PASSPHRASE,
        Location::caller(),
    )
}

/// Creates an automatic public testnet runner using
/// `https://soroban-testnet.stellar.org` by default.
///
/// The runner has the same capture, cache, and strict replay semantics as
/// [`mainnet`], but fixes network identity to Stellar public testnet. Use
/// [`AutoRunner::rpc_url`] to select another testnet RPC provider.
#[must_use]
#[track_caller]
pub fn testnet() -> AutoRunner {
    network_runner(
        DEFAULT_TESTNET_RPC_URL,
        TESTNET_PASSPHRASE,
        Location::caller(),
    )
}

fn network_runner(
    rpc_url: &str,
    network_passphrase: &str,
    caller: &'static Location<'static>,
) -> AutoRunner {
    let thread = std::thread::current();
    let cache = default_cache_path(
        network_passphrase,
        thread.name().unwrap_or("scenario"),
        caller.file(),
        caller.line(),
        caller.column(),
    );
    AutoRunner::with_rpc_url(rpc_url, network_passphrase).cache(cache)
}

fn default_cache_path(
    network_passphrase: &str,
    thread_name: &str,
    caller_file: &str,
    caller_line: u32,
    caller_column: u32,
) -> PathBuf {
    let human = sanitize_cache_name(thread_name);
    let mut digest = Sha256::new();
    digest.update(DEFAULT_CACHE_DOMAIN);
    digest.update((network_passphrase.len() as u64).to_be_bytes());
    digest.update(network_passphrase.as_bytes());
    digest.update((thread_name.len() as u64).to_be_bytes());
    digest.update(thread_name.as_bytes());
    digest.update((caller_file.len() as u64).to_be_bytes());
    digest.update(caller_file.as_bytes());
    digest.update(caller_line.to_be_bytes());
    digest.update(caller_column.to_be_bytes());
    let digest: [u8; 32] = digest.finalize().into();
    let mut short_hash = String::with_capacity(DEFAULT_CACHE_HASH_HEX);
    for byte in &digest[..DEFAULT_CACHE_HASH_HEX / 2] {
        write!(&mut short_hash, "{byte:02x}").expect("String writes are infallible");
    }
    PathBuf::from(".kanatoko").join(format!("{human}-{short_hash}.json"))
}

fn sanitize_cache_name(raw: &str) -> String {
    let mut sanitized = String::with_capacity(raw.len().min(DEFAULT_CACHE_NAME_MAX));
    let mut separator_pending = false;
    for ch in raw.chars() {
        if ch.is_ascii_alphanumeric() || ch == '_' {
            if separator_pending
                && !sanitized.is_empty()
                && sanitized.len() < DEFAULT_CACHE_NAME_MAX
            {
                sanitized.push('-');
            }
            separator_pending = false;
            if sanitized.len() == DEFAULT_CACHE_NAME_MAX {
                break;
            }
            sanitized.push(ch);
        } else {
            separator_pending = true;
        }
    }
    while sanitized.ends_with('-') {
        sanitized.pop();
    }
    if sanitized.is_empty() {
        "scenario".to_string()
    } else {
        sanitized
    }
}

/// Runs one repeatable scenario through automatic discovery and strict replay.
pub struct AutoRunner {
    source: CaptureSource,
    network_passphrase: String,
    rpc_rate_limit: u32,
    protocol_policy: ProtocolPolicy,
    cache: Option<PathBuf>,
    offline: bool,
    refresh: bool,
}

enum CaptureSource {
    Http {
        rpc_url: String,
    },
    #[cfg(test)]
    Builder(CaptureBuilder),
}

impl AutoRunner {
    fn with_rpc_url(rpc_url: impl Into<String>, network_passphrase: impl Into<String>) -> Self {
        Self {
            source: CaptureSource::Http {
                rpc_url: rpc_url.into(),
            },
            network_passphrase: network_passphrase.into(),
            rpc_rate_limit: 0,
            protocol_policy: ProtocolPolicy::Exact,
            cache: None,
            offline: false,
            refresh: false,
        }
    }

    #[cfg(test)]
    pub(crate) fn with_builder(
        builder: CaptureBuilder,
        network_passphrase: impl Into<String>,
    ) -> Self {
        Self {
            source: CaptureSource::Builder(builder),
            network_passphrase: network_passphrase.into(),
            rpc_rate_limit: 0,
            protocol_policy: ProtocolPolicy::Exact,
            cache: None,
            offline: false,
            refresh: false,
        }
    }

    /// Uses another RPC provider for the runner's selected network.
    ///
    /// This changes only the capture provider. The network passphrase, strict
    /// cache validation, and automatic cache identity remain unchanged.
    /// Online runs validate and contact the provider even when the cached
    /// ledger is still current. Offline replay neither parses nor contacts it.
    #[must_use]
    pub fn rpc_url(mut self, url: impl Into<String>) -> Self {
        self.source = CaptureSource::Http {
            rpc_url: url.into(),
        };
        self
    }

    /// Limits read-only RPC requests within each capture run, including retry
    /// attempts, to at most the supplied requests per second. The default and
    /// `0` both mean unlimited. Separate capture runs do not share a quota.
    #[must_use]
    pub const fn rpc_rate_limit(mut self, max_requests_per_second: u32) -> Self {
        self.rpc_rate_limit = max_requests_per_second;
        self
    }

    /// Opts into capturing and replaying a network exactly one ledger protocol
    /// newer than [`crate::SUPPORTED_PROTOCOL_VERSION`].
    ///
    /// Applies to online capture and to loading the cache, also with
    /// [`Self::offline`]. Captures stay truthful: the cache bundle, its
    /// provenance, and every digest keep the real network protocol. Only
    /// execution is downgraded: the scenario's `Env` gives the Host
    /// [`crate::SUPPORTED_PROTOCOL_VERSION`] as the ledger protocol, so the
    /// scenario `Env`'s ledger info reports the executed protocol.
    /// [`ScenarioFork::network_protocol_version`],
    /// [`ScenarioFork::executed_protocol_version`], and
    /// [`crate::CaptureProvenance::executed_protocol_version`] expose both.
    /// See [`CaptureBuilder::allow_newer_protocol`] for what can differ from
    /// the network.
    ///
    /// Older protocols and protocols two or more above the Host are still
    /// rejected with the usual `UnsupportedProtocol` errors.
    #[must_use]
    pub fn allow_newer_protocol(mut self) -> Self {
        self.protocol_policy = ProtocolPolicy::AllowNewer;
        #[cfg(test)]
        if let CaptureSource::Builder(builder) = self.source {
            self.source = CaptureSource::Builder(builder.allow_newer_protocol());
        }
        self
    }

    /// Uses a scenario-specific capture bundle as a cache.
    ///
    /// A missing cache is created after a successful strict replay. Online
    /// runs first compare the complete current ledger anchor with the cached
    /// anchor. An exact match replays without ledger-entry reads. A changed
    /// anchor refreshes every cached key in coherent batches, then discovers
    /// additions. Cached values are never reused across ledgers. If an exact
    /// anchor replay reaches an Unknown key, the same seeded recapture runs.
    /// Cache replacement remains atomic and follows successful strict replay.
    #[must_use]
    pub fn cache(mut self, path: impl Into<PathBuf>) -> Self {
        self.cache = Some(path.into());
        self
    }

    /// Requires a cache hit and forbids automatic network discovery.
    #[must_use]
    pub const fn offline(mut self) -> Self {
        self.offline = true;
        self
    }

    /// Ignores both cached values and its key inventory, then performs a cold
    /// capture from a fresh coherent ledger.
    #[must_use]
    pub const fn refresh(mut self) -> Self {
        self.refresh = true;
        self
    }

    /// Runs the same closure for discovery and strict replay.
    ///
    /// Generated Soroban clients may use [`ScenarioFork::env`] while other
    /// contracts are called through [`ScenarioFork::invoke`] in the same
    /// closure and environment. An exact online cache hit or offline replay
    /// executes the closure once. A cold or inventory-seeded capture can
    /// execute it several times, each in a fresh environment, so contract
    /// mutations never accumulate between discovery passes. External effects
    /// such as randomness, file or network I/O, counters, and output would be
    /// repeated; produce one-time ordinary Rust inputs before calling this
    /// method. Environment-bound values and clients must still be created
    /// inside the closure.
    ///
    /// Imported WASM used by `contractimport!` supplies only the generated
    /// client ABI. Calls to captured addresses always execute the contract
    /// instance and WASM loaded from network state.
    ///
    /// # Errors
    ///
    /// Returns a capture, cache validation, offline-cache, or strict replay
    /// error. Scenario panics remain opaque at this boundary.
    pub fn run<F>(&self, scenario: F) -> Result<AutoRun, AutoRunError>
    where
        F: for<'a> Fn(&ScenarioFork<'a>),
    {
        if self.offline {
            if let Some(path) = self.cache.as_deref().filter(|_| !self.refresh) {
                if path.exists() {
                    let cached = CapturedFixture::from_file_with_policy(
                        path,
                        &self.network_passphrase,
                        self.protocol_policy,
                    )?;
                    replay(&cached, &scenario)?;
                    return Ok(AutoRun {
                        fixture: cached,
                        cache_status: CacheStatus::Hit,
                    });
                }
                return Err(AutoRunError::OfflineCacheMissing {
                    path: path.to_path_buf(),
                });
            }
            return Err(AutoRunError::OfflineCacheMissing {
                path: self.cache.clone().unwrap_or_default(),
            });
        }

        match &self.source {
            CaptureSource::Http { rpc_url } => {
                let mut builder =
                    CaptureBuilder::rpc(rpc_url.clone(), self.network_passphrase.clone())?
                        .rpc_rate_limit(self.rpc_rate_limit);
                if self.protocol_policy == ProtocolPolicy::AllowNewer {
                    builder = builder.allow_newer_protocol();
                }
                self.run_online(&builder, &scenario)
            }
            #[cfg(test)]
            CaptureSource::Builder(builder) => self.run_online(builder, &scenario),
        }
    }

    fn run_online<F>(&self, builder: &CaptureBuilder, scenario: &F) -> Result<AutoRun, AutoRunError>
    where
        F: for<'a> Fn(&ScenarioFork<'a>),
    {
        let cache_existed = self.cache.as_deref().is_some_and(Path::exists);
        let captured = if let Some(path) = self.cache.as_deref().filter(|_| !self.refresh) {
            if path.exists() {
                let cached = CapturedFixture::from_file_with_policy(
                    path,
                    &self.network_passphrase,
                    self.protocol_policy,
                )?;
                if builder.cached_anchor_is_current(&cached)? {
                    match replay(&cached, scenario) {
                        Ok(()) => {
                            return Ok(AutoRun {
                                fixture: cached,
                                cache_status: CacheStatus::Hit,
                            });
                        }
                        Err(CaptureError::UnknownLedgerKeys { .. }) => {}
                        Err(error) => return Err(error.into()),
                    }
                }
                builder.capture_with_inventory(&cached, |env, local, source| {
                    scenario(&ScenarioFork::new(env, local, Some(source)));
                })?
            } else {
                builder.capture_with_local(|env, local, source| {
                    scenario(&ScenarioFork::new(env, local, Some(source)));
                })?
            }
        } else {
            builder.capture_with_local(|env, local, source| {
                scenario(&ScenarioFork::new(env, local, Some(source)));
            })?
        };
        replay(&captured, scenario)?;

        let cache_status = match self.cache.as_deref() {
            Some(path) => {
                if let Some(parent) = path
                    .parent()
                    .filter(|parent| !parent.as_os_str().is_empty())
                {
                    fs::create_dir_all(parent).map_err(|source| CaptureError::CaptureBundleIo {
                        operation: "create-cache-directory",
                        source,
                    })?;
                }
                captured.write_file(path)?;
                if cache_existed {
                    CacheStatus::Refreshed
                } else {
                    CacheStatus::Created
                }
            }
            None => CacheStatus::Disabled,
        };
        Ok(AutoRun {
            fixture: captured,
            cache_status,
        })
    }
}

fn replay<F>(fixture: &CapturedFixture, scenario: &F) -> Result<(), CaptureError>
where
    F: for<'a> Fn(&ScenarioFork<'a>),
{
    fixture.replay_with_local(|env, local, source| {
        scenario(&ScenarioFork::new(env, local, Some(source)));
    })
}

/// Authorization policy for an isolated [`ScenarioFork::preview`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PreviewAuth {
    /// Record and mock-satisfy the authorization tree requested by the call.
    Record,
    /// Record and require an exact detached authorization tree.
    ///
    /// Exact validation is intentionally preview-only. It does not apply state
    /// to the outer scenario environment.
    Exact(Vec<AuthorizationTree>),
}

/// Detached evidence from one isolated high-level preview.
///
/// Resources are the local Host estimate for this invocation. They do not
/// model transaction-envelope work and are not a network fee quote.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InvocationReport {
    receipt: Receipt,
    resources: Option<InvocationResources>,
    network_protocol_version: u32,
}

impl InvocationReport {
    /// Ledger protocol of the captured network. The receipt's digests refer
    /// to ledger state at this protocol.
    #[must_use]
    pub const fn network_protocol_version(&self) -> u32 {
        self.network_protocol_version
    }

    /// Ledger protocol the Host executed this preview with.
    ///
    /// It differs from [`Self::network_protocol_version`] only under the
    /// opt-in newer-protocol mode; resources are then estimates of the older
    /// Host.
    #[must_use]
    pub const fn executed_protocol_version(&self) -> u32 {
        executed_protocol_version(self.network_protocol_version)
    }

    #[must_use]
    pub const fn receipt(&self) -> &Receipt {
        &self.receipt
    }

    #[must_use]
    pub const fn resources(&self) -> Option<&InvocationResources> {
        self.resources.as_ref()
    }

    #[must_use]
    pub fn authorization(&self) -> &[AuthorizationTree] {
        &self.receipt.authorization
    }

    #[must_use]
    pub fn events(&self) -> &[crate::DetachedEvent] {
        &self.receipt.events
    }

    #[must_use]
    pub fn diagnostics(&self) -> &[crate::DetachedEvent] {
        &self.receipt.diagnostics
    }

    #[must_use]
    pub fn state_changes(&self) -> &[StateChange] {
        &self.receipt.state_changes
    }

    /// Converts the detached return value into an SDK value in `env`.
    ///
    /// A conversion failure is reported as
    /// [`InvokeErrorKind::ResultConversion`]; this method never executes the
    /// contract again.
    ///
    /// # Errors
    ///
    /// Returns the invocation's detached failure, or a result-conversion
    /// failure when `R` is incompatible with the returned [`ScVal`].
    pub fn result<R>(&self, env: &Env) -> Result<R, InvocationFailure>
    where
        R: TryFromVal<Env, Val>,
    {
        let value = match &self.receipt.outcome {
            InvokeOutcome::Success(value) => value,
            InvokeOutcome::Failure { error, kind } => {
                return Err(InvocationFailure {
                    error: error.clone(),
                    kind: *kind,
                });
            }
        };
        let value = Val::try_from_val(env, value).map_err(|_| InvocationFailure {
            error: None,
            kind: InvokeErrorKind::ResultConversion,
        })?;
        R::try_from_val(env, &value).map_err(|_| InvocationFailure {
            error: None,
            kind: InvokeErrorKind::ResultConversion,
        })
    }
}

/// One stateful scenario pass.
///
/// The environment is never replaced during a pass, so generated clients and
/// dynamic invocations can safely share it. The runner recreates the complete
/// closure, environment, addresses, and clients for every discovery retry and
/// for final strict replay.
pub struct ScenarioFork<'a> {
    env: &'a Env,
    local_accounts: RefCell<BTreeSet<[u8; 32]>>,
    local_ledger: Rc<LocalLedger>,
    tracking_source: Option<Rc<TrackingSource>>,
    network_protocol_version: u32,
}

impl<'a> ScenarioFork<'a> {
    fn new(
        env: &'a Env,
        local_ledger: Rc<LocalLedger>,
        tracking_source: Option<Rc<TrackingSource>>,
    ) -> Self {
        // Every runner pass has a tracking source that knows the network
        // protocol. Without one, the Env executes its own network protocol.
        let network_protocol_version = tracking_source.as_ref().map_or_else(
            || {
                env.host()
                    .with_ledger_info(|ledger| Ok(ledger.protocol_version))
                    .expect("the scenario environment must have ledger metadata")
            },
            |source| source.network_protocol_version(),
        );
        Self {
            env,
            local_accounts: RefCell::new(BTreeSet::new()),
            local_ledger,
            tracking_source,
            network_protocol_version,
        }
    }

    /// Current pass environment for generated Soroban clients.
    ///
    /// Its ledger protocol is [`Self::executed_protocol_version`].
    #[must_use]
    pub const fn env(&self) -> &'a Env {
        self.env
    }

    /// Ledger protocol of the network this pass's state was captured from.
    #[must_use]
    pub const fn network_protocol_version(&self) -> u32 {
        self.network_protocol_version
    }

    /// Ledger protocol the Host executes this pass with.
    ///
    /// It differs from [`Self::network_protocol_version`] only under
    /// [`AutoRunner::allow_newer_protocol`], where it is
    /// [`crate::SUPPORTED_PROTOCOL_VERSION`].
    #[must_use]
    pub const fn executed_protocol_version(&self) -> u32 {
        executed_protocol_version(self.network_protocol_version)
    }

    /// Parses a contract C-address in the current pass environment.
    ///
    /// # Panics
    ///
    /// Panics if `contract` is not a valid contract C-address.
    #[must_use]
    pub fn contract(&self, contract: &str) -> Address {
        let address = Address::from_str(self.env, contract);
        assert!(
            matches!(ScAddress::from(&address), ScAddress::Contract(_)),
            "expected a contract C-address"
        );
        address
    }

    /// Parses an existing Stellar G-account in the current pass environment.
    ///
    /// Ledger state is not injected or altered. Contract calls that read this
    /// address discover its real `AccountEntry`, trustlines, and other
    /// Host-supported ledger entries on demand.
    ///
    /// # Panics
    ///
    /// Panics if `account` is not a valid account G-address.
    #[must_use]
    pub fn account(&self, account: &str) -> Address {
        let address = Address::from_str(self.env, account);
        assert!(
            matches!(ScAddress::from(&address), ScAddress::Account(_)),
            "expected an account G-address"
        );
        address
    }

    /// Parses a multiplexed Stellar M-address in the current pass environment.
    ///
    /// The multiplexing ID is contract input/event metadata. When a contract
    /// resolves [`MuxedAddress::address`], ledger access targets the underlying
    /// G-account and is captured normally.
    ///
    /// # Panics
    ///
    /// Panics if `account` is not a valid multiplexed M-address.
    #[must_use]
    pub fn muxed_account(&self, account: &str) -> MuxedAddress {
        let address = MuxedAddress::from_str(self.env, account);
        assert!(address.id().is_some(), "expected a multiplexed M-address");
        address
    }

    /// Creates an unfunded local Stellar address.
    ///
    /// The address is pseudorandom but deterministic for the captured network
    /// and `label`. This keeps dependency discovery, strict replay, cache hits,
    /// and CI runs reproducible. Reusing a label in one scenario pass returns
    /// the same account without resetting its state.
    ///
    /// No `AccountEntry`, XLM, trustline, or signing key is created implicitly.
    /// Fund it explicitly with [`ScenarioFork::fund_local_account`] when the
    /// scenario needs an existing account. Use an explicit authorization mode
    /// such as [`ScenarioFork::mock_all_auths`]. Classic assets still require
    /// calling the SAC's `trust` method, and may require `set_authorized`,
    /// before minting or transferring the asset.
    ///
    /// # Panics
    ///
    /// Panics if the generated address already exists in captured network
    /// state.
    #[must_use]
    pub fn local_account(&self, label: &str) -> Address {
        let network_id = self
            .env
            .host()
            .with_ledger_info(|ledger| Ok(ledger.network_id))
            .expect("the scenario environment must have ledger metadata");
        let mut digest = Sha256::new();
        digest.update(LOCAL_ACCOUNT_DOMAIN);
        digest.update(network_id);
        digest.update((label.len() as u64).to_be_bytes());
        digest.update(label.as_bytes());
        let public_key: [u8; 32] = digest.finalize().into();
        let account_id = AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(public_key)));
        let address_xdr = ScAddress::Account(account_id.clone());
        let address = Address::try_from_val(self.env, &address_xdr)
            .expect("a generated Ed25519 account must be a valid Soroban address");

        if self.local_accounts.borrow().contains(&public_key) {
            return address;
        }

        let key = Rc::new(LedgerKey::Account(LedgerKeyAccount {
            account_id: account_id.clone(),
        }));
        if self
            .env
            .host()
            .get_ledger_entry(&key)
            .expect("the Host must be able to inspect the generated account")
            .is_some()
        {
            panic!("generated local account collides with captured network state");
        }
        let inserted = self.local_accounts.borrow_mut().insert(public_key);
        assert!(inserted, "local account tracking must be deterministic");
        self.local_ledger.mark_address(address_xdr);

        address
    }

    /// Adds `amount` stroops to an address created by [`Self::local_account`].
    ///
    /// The first funding creates a valid `AccountEntry` with no subentries; its
    /// amount must cover the network's two-base-reserve minimum. Later calls
    /// add to the existing balance. This is explicit local ledger injection,
    /// not a Stellar payment or transaction-faithful funding operation.
    ///
    /// # Panics
    ///
    /// Panics if `amount` is not positive, first funding is below the minimum,
    /// `account` was not created by this scenario pass, its existing entry is
    /// malformed, the resulting balance overflows `i64`, or the Host rejects
    /// the entry.
    pub fn fund_local_account(&self, account: &Address, amount: i64) {
        assert!(amount > 0, "local account funding must be positive");
        let ScAddress::Account(account_id) = ScAddress::from(account) else {
            panic!("expected a local G-account");
        };
        let AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(public_key))) = &account_id;
        assert!(
            self.local_accounts.borrow().contains(public_key),
            "account was not created by this scenario pass"
        );

        let key = Rc::new(LedgerKey::Account(LedgerKeyAccount {
            account_id: account_id.clone(),
        }));
        let existing = self
            .env
            .host()
            .get_ledger_entry(&key)
            .expect("the Host must be able to inspect the local account");
        let (base_reserve, ledger_sequence) = self
            .env
            .host()
            .with_ledger_info(|ledger| Ok((ledger.base_reserve, ledger.sequence_number)))
            .expect("the scenario environment must have ledger metadata");
        let entry = if let Some((entry, live_until)) = existing {
            assert!(
                live_until.is_none(),
                "local AccountEntry must not have a live-until ledger"
            );
            let mut entry = (*entry).clone();
            let LedgerEntryData::Account(local) = &mut entry.data else {
                panic!("local account key must contain an AccountEntry");
            };
            assert_eq!(
                local.account_id, account_id,
                "local AccountEntry must match its ledger key"
            );
            local.balance = local
                .balance
                .checked_add(amount)
                .expect("local account balance overflow");
            entry.last_modified_ledger_seq = ledger_sequence;
            entry
        } else {
            let minimum = i64::from(base_reserve)
                .checked_mul(2)
                .expect("local account minimum balance overflow");
            assert!(
                amount >= minimum,
                "first local account funding must cover two base reserves"
            );
            let sequence = i64::from(ledger_sequence)
                .checked_mul(1_i64 << 32)
                .expect("the ledger sequence must fit a Stellar account sequence number");
            LedgerEntry {
                last_modified_ledger_seq: ledger_sequence,
                data: LedgerEntryData::Account(AccountEntry {
                    account_id,
                    balance: amount,
                    seq_num: SequenceNumber(sequence),
                    num_sub_entries: 0,
                    inflation_dest: None,
                    flags: 0,
                    home_domain: String32::default(),
                    thresholds: Thresholds([1, 0, 0, 0]),
                    signers: VecM::default(),
                    ext: AccountEntryExt::V0,
                }),
                ext: LedgerEntryExt::V0,
            }
        };
        self.env
            .host()
            .add_ledger_entry(&key, &Rc::new(entry), None)
            .expect("the Host must accept explicit local account funding");
    }

    /// Locally installs candidate WASM and runs its constructor, if defined.
    ///
    /// The returned contract shares this scenario's mutable environment, so it
    /// can call captured network contracts and mutate their forked state.
    /// Installation is deterministic when the scenario is deterministic.
    /// Contract IDs are hashed in a network-specific local namespace instead
    /// of using the SDK's small counter addresses, which may already hold
    /// token balances on the captured network. Its
    /// code and contract-owned storage remain local rather than becoming
    /// network-cache dependencies; the generated contract address is still
    /// checked for an existing contract instance before installation.
    ///
    /// This uses the SDK test registration path. It does not emulate Soroban
    /// upload/create transactions, deployment authorization, fees, signatures,
    /// or Stellar Core consensus.
    ///
    /// # Panics
    ///
    /// Panics if the generated address collides with captured network state,
    /// the WASM is invalid, its constructor fails, or the Host rejects local
    /// installation.
    #[must_use]
    pub fn deploy<A>(&self, wasm: &[u8], constructor_args: A) -> Address
    where
        A: ConstructorArgs,
    {
        let ScAddress::Contract(ContractId(Hash(seed))) =
            ScAddress::from(&Address::generate(self.env))
        else {
            unreachable!("generated candidate address must be a contract");
        };
        let network_id = self
            .env
            .host()
            .with_ledger_info(|ledger| Ok(ledger.network_id))
            .expect("the scenario environment must have ledger metadata");
        let mut digest = Sha256::new();
        digest.update(LOCAL_CONTRACT_DOMAIN);
        digest.update(network_id);
        digest.update(seed);
        let address_xdr = ScAddress::Contract(ContractId(Hash(digest.finalize().into())));
        let address = Address::try_from_val(self.env, &address_xdr)
            .expect("a generated contract ID must be a valid Soroban address");
        let key = Rc::new(contract_instance_key(address_xdr.clone()));
        if self
            .env
            .host()
            .get_ledger_entry(&key)
            .expect("the Host must be able to inspect the candidate address")
            .is_some()
        {
            panic!("generated candidate address collides with captured network state");
        }

        self.local_ledger.mark_address(address_xdr);
        self.local_ledger.mark_code(Sha256::digest(wasm).into());
        self.env.register_at(&address, wasm, constructor_args)
    }

    /// Replaces an existing captured contract's WASM without changing its
    /// address or storage.
    ///
    /// The replacement code is installed locally, then only the executable in
    /// the existing contract instance is changed to direct WASM. Instance,
    /// persistent, and temporary storage remain intact, the instance TTL is
    /// preserved, and the replacement constructor is not called. An external
    /// executable reference is left in storage but is no longer followed by
    /// that locally overridden instance. Calls from other captured contracts
    /// to the same address therefore execute the replacement code.
    ///
    /// This is a test-only code override. It does not invoke the production
    /// contract's upgrade entrypoint or emulate upgrade authorization,
    /// transaction envelopes, fees, signatures, or consensus.
    ///
    /// Returns the SHA-256 hash of the replacement WASM.
    ///
    /// # Panics
    ///
    /// Panics if `contract` is not an existing WASM contract, `wasm` is
    /// invalid, or the Host rejects the local code override.
    pub fn replace_wasm(&self, contract: &Address, wasm: &[u8]) -> [u8; 32] {
        let address = ScAddress::from(contract);
        assert!(
            matches!(address, ScAddress::Contract(_)),
            "WASM can only replace a contract C-address"
        );

        let instance_key = Rc::new(contract_instance_key(address));
        let (instance_entry, live_until_ledger) = self
            .env
            .host()
            .get_ledger_entry(&instance_key)
            .expect("the Host must be able to inspect the existing contract")
            .expect("WASM can only replace an existing contract");
        let mut instance_entry = instance_entry.as_ref().clone();
        let LedgerEntryData::ContractData(instance_data) = &mut instance_entry.data else {
            panic!("contract instance key must contain ContractData");
        };
        let ScVal::ContractInstance(instance) = &mut instance_data.val else {
            panic!("contract instance key must contain a contract instance");
        };
        assert!(
            !matches!(instance.executable, ContractExecutable::StellarAsset),
            "WASM cannot replace a Stellar Asset Contract"
        );

        let wasm_sha256: [u8; 32] = Sha256::digest(wasm).into();
        self.local_ledger.mark_code(wasm_sha256);
        let uploaded = self.env.deployer().upload_contract_wasm(wasm);
        assert_eq!(
            uploaded.to_array(),
            wasm_sha256,
            "the Host returned an unexpected replacement WASM hash"
        );

        instance.executable = ContractExecutable::Wasm(Hash(wasm_sha256));
        self.env
            .host()
            .add_ledger_entry(&instance_key, &Rc::new(instance_entry), live_until_ledger)
            .expect("the Host must accept the local code override");

        wasm_sha256
    }

    /// Enables the SDK's explicit record-and-mock authorization mode.
    ///
    /// This is mocked behavioral evidence, not signature evidence.
    pub fn mock_all_auths(&self) {
        self.env.mock_all_auths();
    }

    /// Dynamically invokes a contract while sharing state with generated
    /// clients in this scenario pass.
    ///
    /// Heterogeneous tuples with up to 13 values are accepted as arguments,
    /// using the same SDK conversions as generated clients. The caller selects
    /// the return type with an annotation or turbofish.
    ///
    /// # Panics
    ///
    /// Panics under the same conditions as [`Env::invoke_contract`], including
    /// an ABI mismatch, contract failure, or incompatible requested result
    /// type.
    #[allow(clippy::needless_pass_by_value)]
    pub fn invoke<R>(
        &self,
        contract: &Address,
        function: &str,
        args: impl IntoVal<Env, SorobanVec<Val>>,
    ) -> R
    where
        R: TryFromVal<Env, Val>,
    {
        self.env.invoke_contract(
            contract,
            &Symbol::new(self.env, function),
            args.into_val(self.env),
        )
    }

    /// Dynamically invokes a contract once in the current mutable environment.
    ///
    /// Contract and Host failures are returned as structured values without
    /// parsing panic or diagnostic strings. Failed Host invocations roll back
    /// their contract state atomically. As with [`Env::try_invoke_contract`], a
    /// [`InvokeErrorKind::ResultConversion`] is detected only after a successful
    /// Host call, so the call's state may already have been applied.
    ///
    /// # Errors
    ///
    /// Returns a structured contract, Host, panic, or return-conversion
    /// failure. No diagnostic or panic strings are parsed.
    #[allow(clippy::needless_pass_by_value)]
    pub fn try_invoke<R>(
        &self,
        contract: &Address,
        function: &str,
        args: impl IntoVal<Env, SorobanVec<Val>>,
    ) -> Result<R, InvocationFailure>
    where
        R: TryFromVal<Env, Val>,
    {
        let prepared = catch_unwind(AssertUnwindSafe(|| {
            let function = function
                .try_into()
                .map(ScSymbol)
                .map_err(|_| InvocationFailure {
                    error: None,
                    kind: InvokeErrorKind::Abort,
                })?;
            let function =
                Symbol::try_from_val(self.env, &ScVal::Symbol(function)).map_err(|_| {
                    InvocationFailure {
                        error: None,
                        kind: InvokeErrorKind::Abort,
                    }
                })?;
            Ok::<_, InvocationFailure>((function, args.into_val(self.env)))
        }));
        let (function, args) = match prepared {
            Ok(Ok(prepared)) => prepared,
            Ok(Err(failure)) => return Err(failure),
            Err(_) => {
                return Err(InvocationFailure {
                    error: None,
                    kind: InvokeErrorKind::Abort,
                });
            }
        };
        invoke_once(self.env, contract, &function, args)
    }

    /// Executes one contract call in an isolated child environment.
    ///
    /// The returned report contains detached return/error, authorization,
    /// events, diagnostics, state changes, and an optional local resource
    /// estimate. The outer environment's state, events, authorization, and SDK
    /// generators are never changed. Locally deployed WASM and captured
    /// cross-contract calls remain available through the cloned snapshot.
    ///
    /// Preview resources are local Host estimates, not network fee parity.
    ///
    /// # Errors
    ///
    /// Returns a typed strict error for invalid detached values, exact-auth
    /// mismatch, Host inspection failure, or an unknown offline dependency.
    #[allow(clippy::needless_pass_by_value)]
    pub fn preview(
        &self,
        contract: &Address,
        function: &str,
        args: impl IntoVal<Env, SorobanVec<Val>>,
        auth: PreviewAuth,
    ) -> Result<InvocationReport, StrictForkError> {
        let function = ScSymbol(
            function
                .try_into()
                .map_err(|_| StrictForkError::InvalidInvocationXdr)?,
        );
        let args = catch_unwind(AssertUnwindSafe(|| {
            let args = args.into_val(self.env);
            args.iter()
                .map(|arg| {
                    ScVal::try_from_val(self.env, &arg)
                        .map_err(|_| StrictForkError::InvalidInvocationXdr)
                })
                .collect::<Result<Vec<_>, _>>()
        }))
        .map_err(|_| StrictForkError::InvalidInvocationXdr)??;
        let request = InvokeRequest {
            contract: ScAddress::from(contract),
            function,
            args,
        };

        let before = network_ledger_snapshot(self.env, self.network_protocol_version);
        let before_digest = crate::canonical_ledger_digest(&before)?;
        let mut snapshot = self.env.to_snapshot();
        restore_network_protocol(
            &mut snapshot.ledger.protocol_version,
            self.network_protocol_version,
        );
        let child = fork_env(ForkEnvSeed::Snapshot(snapshot));
        child.mock_all_auths();
        let (contract, function, args) = invocation_values(&child, &request)?;
        let outcome = invoke_outcome(&child, &contract, &function, args);
        let upstream_reads = self.forward_preview_reads(&child)?;
        let resources = child.host().get_last_invocation_resources();
        let (authorization, events) = detached_snapshot_evidence(&child);
        let (auth_mode, expected) = match auth {
            PreviewAuth::Record => (AppliedAuthMode::RecordMockSatisfied, None),
            PreviewAuth::Exact(expected) => (AppliedAuthMode::MockExact, Some(expected)),
        };
        if expected
            .as_ref()
            .is_some_and(|expected| expected != &authorization)
        {
            return Err(StrictForkError::AuthTreeMismatch);
        }

        let mut after = network_ledger_snapshot(&child, self.network_protocol_version);
        strip_new_mock_nonces(&before, &mut after)?;
        let after_digest = crate::canonical_ledger_digest(&after)?;
        let state_changes = state_diff(&before, &after)?;
        let diagnostics = detached_diagnostics(&child)?;
        Ok(InvocationReport {
            receipt: Receipt {
                request,
                outcome,
                auth_mode,
                authorization,
                events,
                diagnostics,
                state_changes,
                before_digest,
                after_digest,
                disposition: ReceiptDisposition::Previewed,
                upstream_reads,
            },
            resources,
            network_protocol_version: self.network_protocol_version,
        })
    }

    fn forward_preview_reads(&self, child: &Env) -> Result<u64, StrictForkError> {
        let Some(source) = &self.tracking_source else {
            return Ok(0);
        };
        let reads_before = source.rpc_reads();
        let mut inspection_failed = false;
        for (key, _) in child
            .host()
            .get_stored_entries()
            .map_err(|_| StrictForkError::HostInspection)?
        {
            if matches!(
                key.as_ref(),
                LedgerKey::ContractData(data) if is_nonce_data(data)
            ) {
                continue;
            }
            if source.observe(&key).is_err() {
                inspection_failed = true;
            }
        }
        let unknown = source.unknown_keys();
        if !unknown.is_empty() {
            return Err(StrictForkError::UnknownLedgerKeys {
                count: unknown.len(),
                keys: unknown.into_iter().collect(),
            });
        }
        if inspection_failed {
            return Err(StrictForkError::HostInspection);
        }
        Ok(source.rpc_reads().saturating_sub(reads_before))
    }
}

/// How the automatic runner obtained its fixture.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CacheStatus {
    Disabled,
    Hit,
    Created,
    Refreshed,
}

/// Result of a successful automatic scenario.
pub struct AutoRun {
    fixture: CapturedFixture,
    cache_status: CacheStatus,
}

impl AutoRun {
    /// Captured fixture that passed the strict scenario replay.
    #[must_use]
    pub const fn fixture(&self) -> &CapturedFixture {
        &self.fixture
    }

    #[must_use]
    pub const fn cache_status(&self) -> CacheStatus {
        self.cache_status
    }
}

/// Automatic runner failures.
#[derive(Debug, Error)]
pub enum AutoRunError {
    #[error(transparent)]
    Capture(#[from] CaptureError),
    #[error("offline mode requires an existing capture cache at {path}")]
    OfflineCacheMissing { path: PathBuf },
}

#[cfg(test)]
mod tests {
    use soroban_env_host::xdr::{
        ContractDataDurability, ContractDataEntry, ContractExecutableExternalRef, ExtensionPoint,
        LedgerKeyContractData, ScError, ScString,
    };
    use soroban_sdk::testutils::{EnvTestConfig, Ledger as _};

    use super::*;

    mod stateful {
        soroban_sdk::contractimport!(
            file = "fixtures/wasm/kanatoko_stateful_fixture.wasm",
            sha256 = "0156a9a840e4147732fcf0479846220840ae4b4281c58354aa31cf70daf6b2ea",
        );
    }

    mod legacy_v25 {
        soroban_sdk::contractimport!(
            file = "fixtures/wasm/kanatoko_legacy_v25_fixture.wasm",
            sha256 = "d601c7569be29b0a52af409ed65425b8c3595db8a83c444fe65dd8294423a879",
        );
    }

    #[test]
    fn local_account_is_unfunded_and_explicit_funding_is_scoped_and_additive() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        env.ledger().set_base_reserve(5_000_000);
        env.ledger().set_sequence_number(123);
        let network_id = env
            .host()
            .with_ledger_info(|ledger| Ok(ledger.network_id))
            .unwrap();
        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);

        let actual = fork.local_account("alice");
        let mut digest = Sha256::new();
        digest.update(b"kanatoko.local-account.v2");
        digest.update(network_id);
        digest.update((5_u64).to_be_bytes());
        digest.update(b"alice");
        let expected = ScAddress::Account(AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(
            digest.finalize().into(),
        ))));

        assert_eq!(ScAddress::from(&actual), expected);
        assert_eq!(local_account_balance(&env, &actual), None);
        assert_eq!(fork.local_account("alice"), actual);
        assert_ne!(fork.local_account("bob"), actual);

        let minimum = env
            .host()
            .with_ledger_info(|ledger| Ok(i64::from(ledger.base_reserve) * 2))
            .unwrap();
        fork.fund_local_account(&actual, minimum);
        assert_eq!(local_account_balance(&env, &actual), Some(minimum));
        fork.fund_local_account(&actual, 5);
        assert_eq!(local_account_balance(&env, &actual), Some(minimum + 5));
        assert_eq!(fork.local_account("alice"), actual);
        assert_eq!(local_account_balance(&env, &actual), Some(minimum + 5));

        let below_reserve = fork.local_account("below-reserve");
        assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            fork.fund_local_account(&below_reserve, minimum - 1);
        }))
        .is_err());
        assert_eq!(local_account_balance(&env, &below_reserve), None);

        let nonlocal = Address::from_str(
            &env,
            "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
        );
        assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            fork.fund_local_account(&nonlocal, minimum);
        }))
        .is_err());
    }

    fn local_account_balance(env: &Env, account: &Address) -> Option<i64> {
        let ScAddress::Account(account_id) = ScAddress::from(account) else {
            panic!("local account must be a G-address");
        };
        let key = Rc::new(LedgerKey::Account(LedgerKeyAccount { account_id }));
        let (entry, _) = env.host().get_ledger_entry(&key).unwrap()?;
        let LedgerEntryData::Account(account) = &entry.data else {
            panic!("local account key must contain an AccountEntry");
        };
        Some(account.balance)
    }

    #[test]
    fn deploy_rejects_generated_address_collision_without_replacing_contract() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let mut mirror = Env::default();
        mirror.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let occupied_xdr = ScAddress::from(
            &ScenarioFork::new(&mirror, Rc::new(LocalLedger::default()), None)
                .deploy(stateful::WASM, (0_i64,)),
        );
        let occupied = Address::try_from_val(&env, &occupied_xdr).unwrap();
        env.register_at(&occupied, stateful::WASM, (41_i64,));
        let existing = stateful::Client::new(&env, &occupied);
        assert_eq!(existing.get(), 41);

        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = fork.deploy(stateful::WASM, (99_i64,));
        }))
        .is_err());
        assert_eq!(existing.get(), 41);
    }

    #[test]
    fn deploy_does_not_inherit_native_balance_at_sdk_generated_address() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let mut mirror = Env::default();
        mirror.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let occupied =
            Address::try_from_val(&env, &ScAddress::from(&Address::generate(&mirror))).unwrap();
        let native = env
            .host()
            .invoke_function(soroban_env_host::xdr::HostFunction::CreateContract(
                soroban_env_host::xdr::CreateContractArgs {
                    contract_id_preimage: soroban_env_host::xdr::ContractIdPreimage::Asset(
                        soroban_env_host::xdr::Asset::Native,
                    ),
                    executable: ContractExecutable::StellarAsset,
                },
            ))
            .unwrap();
        let native = Address::try_from_val(&env, &native).unwrap();
        let token = soroban_sdk::token::TokenClient::new(&env, &native);
        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        fork.mock_all_auths();
        let donor = fork.local_account("donor");
        fork.fund_local_account(&donor, 200_000_000_000);
        token.transfer(&donor, &occupied, &100_000_000_000);

        let candidate = fork.deploy(stateful::WASM, (99_i64,));
        assert_eq!(token.balance(&candidate), 0);
        assert_eq!(token.balance(&occupied), 100_000_000_000);
    }

    #[test]
    fn deploy_addresses_are_repeatable_unique_and_network_scoped() {
        fn addresses(network: [u8; 32]) -> [ScAddress; 2] {
            let mut env = Env::default();
            env.set_config(EnvTestConfig {
                capture_snapshot_at_drop: false,
            });
            env.ledger().set_network_id(network);
            let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
            [
                ScAddress::from(&fork.deploy(stateful::WASM, (1_i64,))),
                ScAddress::from(&fork.deploy(stateful::WASM, (2_i64,))),
            ]
        }
        let first = addresses([1; 32]);
        assert_eq!(first, addresses([1; 32]));
        assert_ne!(first[0], first[1]);
        assert_ne!(first[0], addresses([2; 32])[0]);
    }

    #[test]
    fn replace_wasm_preserves_instance_and_does_not_run_constructor() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let contract = env.register(stateful::WASM, (41_i64,));
        let instance_key = Rc::new(contract_instance_key((&contract).into()));
        let before = env.host().get_ledger_entry(&instance_key).unwrap().unwrap();

        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        fork.replace_wasm(&contract, legacy_v25::WASM);
        assert_eq!(legacy_v25::Client::new(&env, &contract).sdk_major(), 25);

        assert_eq!(
            fork.replace_wasm(&contract, stateful::WASM),
            <[u8; 32]>::from(Sha256::digest(stateful::WASM))
        );

        let after = env.host().get_ledger_entry(&instance_key).unwrap().unwrap();
        assert_eq!(after, before);
        assert_eq!(stateful::Client::new(&env, &contract).get(), 41);
    }

    #[test]
    fn replace_wasm_detaches_an_external_ref_without_changing_storage_or_reference() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let contract = env.register(stateful::WASM, (41_i64,));
        let contract_xdr = ScAddress::from(&contract);
        let instance_key = Rc::new(contract_instance_key(contract_xdr.clone()));
        let (instance_entry, live_until) =
            env.host().get_ledger_entry(&instance_key).unwrap().unwrap();
        let mut external_instance = instance_entry.as_ref().clone();
        let LedgerEntryData::ContractData(instance_data) = &mut external_instance.data else {
            panic!("instance must be contract data");
        };
        let ScVal::ContractInstance(instance) = &mut instance_data.val else {
            panic!("instance key must contain a contract instance");
        };
        let original_storage = instance.storage.clone();
        let tag = ScString(b"kanatoko-replace".to_vec().try_into().unwrap());
        instance.executable = ContractExecutable::ExternalRef(ContractExecutableExternalRef {
            executable_owner: contract_xdr.clone(),
            tag: tag.clone(),
        });
        env.host()
            .add_ledger_entry(&instance_key, &Rc::new(external_instance), live_until)
            .unwrap();

        let reference_key = Rc::new(LedgerKey::ContractData(LedgerKeyContractData {
            contract: contract_xdr.clone(),
            key: ScVal::ExecutableTag(tag.clone()),
            durability: ContractDataDurability::Persistent,
        }));
        let reference_entry = Rc::new(LedgerEntry {
            last_modified_ledger_seq: 0,
            data: LedgerEntryData::ContractData(ContractDataEntry {
                ext: ExtensionPoint::V0,
                contract: contract_xdr,
                key: ScVal::ExecutableTag(tag),
                durability: ContractDataDurability::Persistent,
                val: ScVal::Bytes(
                    <[u8; 32]>::from(Sha256::digest(stateful::WASM))
                        .to_vec()
                        .try_into()
                        .unwrap(),
                ),
            }),
            ext: LedgerEntryExt::V0,
        });
        env.host()
            .add_ledger_entry(&reference_key, &reference_entry, live_until)
            .unwrap();
        let reference_before = env.host().get_ledger_entry(&reference_key).unwrap();

        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        let replacement_hash = fork.replace_wasm(&contract, legacy_v25::WASM);

        assert_eq!(legacy_v25::Client::new(&env, &contract).sdk_major(), 25);
        let (after, after_live_until) =
            env.host().get_ledger_entry(&instance_key).unwrap().unwrap();
        let LedgerEntryData::ContractData(after_data) = &after.data else {
            panic!("instance must remain contract data");
        };
        let ScVal::ContractInstance(after_instance) = &after_data.val else {
            panic!("instance must remain a contract instance");
        };
        assert_eq!(
            after_instance.executable,
            ContractExecutable::Wasm(Hash(replacement_hash))
        );
        assert_eq!(after_instance.storage, original_storage);
        assert_eq!(after_live_until, live_until);
        assert_eq!(
            env.host().get_ledger_entry(&reference_key).unwrap(),
            reference_before
        );
    }

    #[test]
    fn try_invoke_applies_success_and_returns_contract_failure_atomically() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        let contract = fork.deploy(stateful::WASM, (41_i64,));

        assert_eq!(
            fork.try_invoke::<i64>(&contract, "increment", (1_i64,))
                .unwrap(),
            42
        );

        let failure = fork
            .try_invoke::<i64>(&contract, "increment_then_fail", (5_i64,))
            .unwrap_err();
        assert_eq!(failure.error, Some(ScError::Contract(1)));
        assert_eq!(failure.kind, InvokeErrorKind::Contract(1));
        assert_eq!(fork.invoke::<i64>(&contract, "get", ()), 42);
    }

    #[test]
    fn try_invoke_rejects_long_function_without_panicking_or_mutating() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        let contract = fork.deploy(stateful::WASM, (41_i64,));
        let before = env.to_snapshot();

        let failure = fork
            .try_invoke::<i64>(
                &contract,
                "function_name_that_is_definitely_longer_than_thirty_two_characters",
                (),
            )
            .unwrap_err();

        assert_eq!(failure.error, None);
        assert_eq!(failure.kind, InvokeErrorKind::Abort);
        assert_eq!(env.to_snapshot(), before);
    }

    #[test]
    fn preview_reports_detached_evidence_without_leaking_into_outer_env() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        let contract = fork.deploy(stateful::WASM, (41_i64,));
        let outer_before = env.to_snapshot();

        let report = fork
            .preview(&contract, "increment", (1_i64,), PreviewAuth::Record)
            .unwrap();

        assert_eq!(report.result::<i64>(&env).unwrap(), 42);
        assert_eq!(report.receipt().disposition, ReceiptDisposition::Previewed);
        assert!(!report.events().is_empty());
        assert!(!report.state_changes().is_empty());
        assert!(report.resources().is_some());
        assert_eq!(env.to_snapshot().events, outer_before.events);
        assert_eq!(env.to_snapshot().auth, outer_before.auth);
        assert_eq!(fork.invoke::<i64>(&contract, "get", ()), 41);
    }

    #[test]
    fn preview_record_then_exact_validates_auth_without_mutation() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        let contract = fork.deploy(stateful::WASM, (41_i64,));
        let user = fork.local_account("preview-auth-user");
        let outer_before = env.to_snapshot();

        let recorded = fork
            .preview(
                &contract,
                "authorized_increment",
                (user.clone(), 1_i64),
                PreviewAuth::Record,
            )
            .unwrap();
        assert_eq!(recorded.result::<i64>(&env).unwrap(), 42);
        assert!(!recorded.authorization().is_empty());

        let exact = fork
            .preview(
                &contract,
                "authorized_increment",
                (user.clone(), 1_i64),
                PreviewAuth::Exact(recorded.authorization().to_vec()),
            )
            .unwrap();
        assert_eq!(exact.result::<i64>(&env).unwrap(), 42);

        let mismatch = fork
            .preview(
                &contract,
                "authorized_increment",
                (user, 1_i64),
                PreviewAuth::Exact(Vec::new()),
            )
            .unwrap_err();
        assert!(matches!(mismatch, StrictForkError::AuthTreeMismatch));
        assert_eq!(env.to_snapshot().events, outer_before.events);
        assert_eq!(env.to_snapshot().auth, outer_before.auth);
        assert_eq!(fork.invoke::<i64>(&contract, "get", ()), 41);
    }

    #[test]
    fn preview_rejects_long_function_without_panicking_or_mutating() {
        let mut env = Env::default();
        env.set_config(EnvTestConfig {
            capture_snapshot_at_drop: false,
        });
        let fork = ScenarioFork::new(&env, Rc::new(LocalLedger::default()), None);
        let contract = fork.deploy(stateful::WASM, (41_i64,));
        let before = env.to_snapshot();

        let failure = fork
            .preview(
                &contract,
                "function_name_that_is_definitely_longer_than_thirty_two_characters",
                (),
                PreviewAuth::Record,
            )
            .unwrap_err();

        assert!(matches!(failure, StrictForkError::InvalidInvocationXdr));
        assert_eq!(env.to_snapshot(), before);
    }

    #[test]
    fn default_cache_path_is_deterministic_sanitized_and_bounded() {
        let first = mainnet_from_stable_callsite();
        let second = mainnet_from_stable_callsite();
        assert_eq!(first.cache, second.cache);
        assert_ne!(first.cache, mainnet_from_other_callsite().cache);
        let path = first
            .cache
            .expect("public mainnet runner must cache by default");
        assert_eq!(path.parent(), Some(Path::new(".kanatoko")));
        let file_name = path.file_name().unwrap().to_str().unwrap();
        assert!(Path::new(file_name)
            .extension()
            .is_some_and(|extension| extension.eq_ignore_ascii_case("json")));
        assert!(file_name
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.')));

        let sanitized = default_cache_path(
            MAINNET_PASSPHRASE,
            "module::test / unicode 🚀 and a very long suffix that must not make filesystem paths surprising 0123456789",
            "tests/example.rs",
            12,
            34,
        );
        let stem = sanitized.file_stem().unwrap().to_str().unwrap();
        let (human, hash) = stem.rsplit_once('-').unwrap();
        assert!(human.len() <= DEFAULT_CACHE_NAME_MAX);
        assert_eq!(hash.len(), DEFAULT_CACHE_HASH_HEX);
        assert!(hash.chars().all(|ch| ch.is_ascii_hexdigit()));
        assert!(!human.contains("--"));
        assert!(
            default_cache_path(MAINNET_PASSPHRASE, "🚀", "tests/example.rs", 12, 34)
                .file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .starts_with("scenario-")
        );

        let punctuation_a = default_cache_path(
            MAINNET_PASSPHRASE,
            "module::test",
            "tests/example.rs",
            12,
            34,
        );
        let punctuation_b = default_cache_path(
            MAINNET_PASSPHRASE,
            "module--test",
            "tests/example.rs",
            12,
            34,
        );
        assert_eq!(
            sanitize_cache_name("module::test"),
            sanitize_cache_name("module--test")
        );
        assert_ne!(cache_hash(&punctuation_a), cache_hash(&punctuation_b));

        let long_prefix = "a".repeat(DEFAULT_CACHE_NAME_MAX);
        let unicode_a = default_cache_path(
            MAINNET_PASSPHRASE,
            &format!("{long_prefix}🚀first"),
            "tests/example.rs",
            12,
            34,
        );
        let unicode_b = default_cache_path(
            MAINNET_PASSPHRASE,
            &format!("{long_prefix}🎯second"),
            "tests/example.rs",
            12,
            34,
        );
        assert_eq!(
            unicode_a.file_stem().unwrap().to_str().unwrap()[..DEFAULT_CACHE_NAME_MAX],
            unicode_b.file_stem().unwrap().to_str().unwrap()[..DEFAULT_CACHE_NAME_MAX]
        );
        assert_ne!(cache_hash(&unicode_a), cache_hash(&unicode_b));

        let case_a = default_cache_path(MAINNET_PASSPHRASE, "CaseName", "tests/example.rs", 12, 34);
        let case_b = default_cache_path(MAINNET_PASSPHRASE, "casename", "tests/example.rs", 12, 34);
        assert_ne!(cache_hash(&case_a), cache_hash(&case_b));
    }

    #[test]
    fn public_network_runners_use_expected_defaults_and_network_cache_identity() {
        let mainnet_runner = mainnet_from_stable_callsite();
        let testnet_runner = testnet_from_stable_callsite();

        assert_eq!(mainnet_runner.network_passphrase, MAINNET_PASSPHRASE);
        assert_eq!(testnet_runner.network_passphrase, TESTNET_PASSPHRASE);
        assert_eq!(mainnet_runner.rpc_rate_limit, 0);
        assert_eq!(testnet_runner.rpc_rate_limit, 0);
        assert!(matches!(
            &mainnet_runner.source,
            CaptureSource::Http { rpc_url } if rpc_url == DEFAULT_MAINNET_RPC_URL
        ));
        assert!(matches!(
            &testnet_runner.source,
            CaptureSource::Http { rpc_url } if rpc_url == DEFAULT_TESTNET_RPC_URL
        ));

        let mainnet_path = default_cache_path(
            MAINNET_PASSPHRASE,
            "module::scenario",
            "tests/example.rs",
            12,
            34,
        );
        let testnet_path = default_cache_path(
            TESTNET_PASSPHRASE,
            "module::scenario",
            "tests/example.rs",
            12,
            34,
        );
        assert_ne!(mainnet_path, testnet_path);
    }

    #[test]
    fn rpc_override_changes_provider_without_changing_network_or_default_cache() {
        let default = mainnet_from_stable_callsite();
        let overridden = mainnet_from_stable_callsite().rpc_url("https://rpc.example.test/private");

        assert_eq!(overridden.network_passphrase, MAINNET_PASSPHRASE);
        assert_eq!(overridden.cache, default.cache);
        assert!(matches!(
            &overridden.source,
            CaptureSource::Http { rpc_url }
                if rpc_url == "https://rpc.example.test/private"
        ));

        let testnet_runner =
            testnet_from_stable_callsite().rpc_url("https://testnet-rpc.example.test");
        assert_eq!(testnet_runner.network_passphrase, TESTNET_PASSPHRASE);

        let limited = mainnet_from_stable_callsite().rpc_rate_limit(5);
        assert_eq!(limited.rpc_rate_limit, 5);
        assert_eq!(limited.cache, default.cache);
    }

    #[test]
    fn invalid_rpc_override_is_typed_only_when_capture_is_required_and_redacted() {
        let secret = "credential-must-not-leak";
        let result = mainnet()
            .rpc_url(format!("not-a-url-{secret}"))
            .cache(
                std::env::temp_dir()
                    .join(format!("kanatoko-invalid-rpc-{}.json", std::process::id())),
            )
            .refresh()
            .run(|_| {});

        let Err(error) = result else {
            panic!("an invalid RPC URL must fail when capture is required");
        };
        assert!(matches!(
            error,
            AutoRunError::Capture(CaptureError::InvalidRpcUrl)
        ));
        assert!(!format!("{error:?} {error}").contains(secret));
    }

    #[test]
    fn explicit_cache_overrides_public_default_while_custom_builder_stays_disabled() {
        let explicit = PathBuf::from("custom/capture.json");
        assert_eq!(
            mainnet_from_stable_callsite().cache(&explicit).cache,
            Some(explicit)
        );

        let builder =
            CaptureBuilder::mainnet(DEFAULT_MAINNET_RPC_URL).expect("built-in URL must be valid");
        assert!(AutoRunner::with_builder(builder, MAINNET_PASSPHRASE)
            .cache
            .is_none());
    }

    fn mainnet_from_stable_callsite() -> AutoRunner {
        mainnet()
    }

    fn mainnet_from_other_callsite() -> AutoRunner {
        mainnet()
    }

    fn testnet_from_stable_callsite() -> AutoRunner {
        testnet()
    }

    fn cache_hash(path: &Path) -> &str {
        path.file_stem()
            .unwrap()
            .to_str()
            .unwrap()
            .rsplit_once('-')
            .unwrap()
            .1
    }
}