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
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
//! The crate's front door: [`Scope`] (an RPC-backed client that caches what it
//! fetches) and [`Replay`] (a transaction's reconstructed world, fetched once,
//! replayable any number of times with zero further RPC).
//!
//! ```no_run
//! use svmscope::{Mutation, Scope};
//!
//! let scope = Scope::new("https://api.mainnet-beta.solana.com");
//! let mut replay = scope.replay("<signature>")?; // all RPC happens here
//! replay.advance_seconds(30 * 86_400); // +30 days
//! let out = replay.simulate(&[Mutation::lamports("<account>", 0)])?;
//! println!("success: {}", out.result.success);
//! # Ok::<(), svmscope::Error>(())
//! ```
use serde::Serialize;
use serde_json::json;
use solana_address::Address;
use solana_client::rpc_client::RpcClient;
use solana_client::rpc_config::RpcSendTransactionConfig;
use solana_client::rpc_request::RpcRequest;
use solana_transaction::versioned::VersionedTransaction;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Mutex;
use std::thread;
use std::time::{Duration, Instant};
use crate::analyze::{
build_overview, AccountDiff, AccountOverview, Analysis, Explanation, FieldDiff, ProgramInfo,
SigInfo, SimulationReport,
};
use crate::check::{Check, Scenario};
use crate::error::{Error, Result};
use crate::fixture::Fixture;
use crate::replay::{
FeatureToggle, Mutation, PreState, ReplayContext, ReplayResult, ScenarioOutcome, TimeTravel,
};
use crate::search::{search_threshold, Threshold};
use crate::trace::Trace;
use crate::{cpi_tree, decode, diffs, idl, ixname, utils, CapturedTransaction};
/// An RPC-backed client with caches. Everything svmscope fetches — transaction
/// JSON, program IDLs — is fetched once per `Scope` and reused, so
/// `analyze(sig)` followed by `replay(sig)` costs one transaction fetch, and
/// repeated simulations cost zero.
pub struct Scope {
client: RpcClient,
archive: Option<RpcClient>,
/// getTransaction (json encoding) responses by signature.
tx_cache: Mutex<HashMap<String, serde_json::Value>>,
/// On-chain IDL by program id; `None` = checked, program publishes none.
idl_cache: Mutex<HashMap<String, Option<serde_json::Value>>>,
}
fn status_is_confirmed(status: &serde_json::Value) -> bool {
match status
.get("confirmationStatus")
.and_then(serde_json::Value::as_str)
{
Some("confirmed" | "finalized") => true,
Some("processed") => false,
None => status.get("confirmations").is_some_and(|confirmation| {
confirmation.is_null() || confirmation.as_u64().is_some_and(|count| count > 1)
}),
Some(_) => false,
}
}
/// A fetched account, as `(owner, lamports, executable, data)`.
type RawAccount = (String, u64, bool, Vec<u8>);
impl Scope {
/// A scope talking to the given RPC endpoint.
pub fn new(rpc_url: impl Into<String>) -> Scope {
Scope::from_client(RpcClient::new(rpc_url.into()))
}
/// A scope over an existing client (custom commitment/timeout config).
pub fn from_client(client: RpcClient) -> Scope {
Scope {
client,
archive: None,
tx_cache: Mutex::new(HashMap::new()),
idl_cache: Mutex::new(HashMap::new()),
}
}
/// Register a program's IDL for every API on this scope — `analyze`,
/// `diagnose`, `preflight_overview`, and the replays and traces built from
/// signatures — so instructions, accounts, arguments, events and errors of
/// that program are named even when it publishes no IDL on-chain (a local
/// or private deployment). Takes precedence over the on-chain lookup.
pub fn add_idl(&self, program: impl Into<String>, idl: serde_json::Value) {
self.idl_cache
.lock()
.unwrap()
.insert(program.into(), Some(idl));
}
/// Attach an archival RPC endpoint (e.g. Alchemy's Account Archive) so
/// `replay_at_slot` can fetch account state as of a transaction's slot.
pub fn with_archive(mut self, archive_url: impl Into<String>) -> Scope {
self.archive = Some(RpcClient::new(archive_url.into()));
self
}
/// The underlying RPC client — the escape hatch for anything svmscope
/// doesn't wrap.
pub fn client(&self) -> &RpcClient {
&self.client
}
/// Accept a transaction signature OR an account/program address. A 32-byte
/// value parses as an address and resolves to its most recent transaction;
/// a 64-byte signature is used as-is.
fn resolve_signature(&self, input: &str) -> Result<String> {
let input = input.trim();
if Address::from_str(input).is_ok() {
let resp: serde_json::Value = self
.client
.send(
RpcRequest::GetSignaturesForAddress,
json!([input, { "limit": 1 }]),
)
.map_err(Error::rpc)?;
return resp
.as_array()
.and_then(|a| a.first())
.and_then(|s| s["signature"].as_str())
.map(String::from)
.ok_or_else(|| Error::NoSignatures(input.to_string()));
}
Ok(input.to_string())
}
/// The transaction's `getTransaction` JSON, fetched once and cached.
fn fetch_transaction_json(&self, signature: &str) -> Result<Option<serde_json::Value>> {
if let Some(tx) = self.tx_cache.lock().unwrap().get(signature) {
return Ok(Some(tx.clone()));
}
let tx: serde_json::Value = self
.client
.send(
RpcRequest::GetTransaction,
json!([
signature,
{
"encoding": "json",
"commitment": "confirmed",
"maxSupportedTransactionVersion": 0
}
]),
)
.map_err(Error::rpc)?;
// A recently confirmed transaction may not be indexed yet.
if tx.is_null() {
return Ok(None);
}
self.tx_cache
.lock()
.unwrap()
.insert(signature.to_string(), tx.clone());
Ok(Some(tx))
}
fn transaction_json(&self, signature: &str) -> Result<serde_json::Value> {
self.fetch_transaction_json(signature)?
.ok_or_else(|| Error::TransactionNotFound(signature.to_string()))
}
/// A program's on-chain IDL, fetched once and cached (`None` = has none).
/// Two layers: per-`Scope` (this request) and process-wide with a 10-minute
/// TTL, so a server handling many requests for the same programs fetches
/// each IDL once, not once per request.
fn idl_for(&self, program: &str) -> Option<serde_json::Value> {
type IdlCache = HashMap<String, (Instant, Option<serde_json::Value>)>;
static GLOBAL: std::sync::LazyLock<Mutex<IdlCache>> =
std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
const TTL: Duration = Duration::from_secs(600);
let mut cache = self.idl_cache.lock().unwrap();
if let Some(v) = cache.get(program) {
return v.clone();
}
if let Ok(g) = GLOBAL.lock() {
if let Some((at, v)) = g.get(program) {
if at.elapsed() < TTL {
cache.insert(program.to_string(), v.clone());
return v.clone();
}
}
}
let fetched = Address::from_str(program)
.ok()
.and_then(|a| idl::fetch_idl_json(&self.client, a));
cache.insert(program.to_string(), fetched.clone());
if let Ok(mut g) = GLOBAL.lock() {
if g.len() >= 512 {
g.clear();
}
g.insert(program.to_string(), (Instant::now(), fetched.clone()));
}
fetched
}
/// Decode a transaction: the full CPI tree with IDL-named instructions,
/// balance and token diffs, per-program compute units, logs, and every
/// touched account. `input` may be a signature or an address (resolved to
/// its latest transaction). Decode only — replay via [`Scope::replay`].
pub fn analyze(&self, input: &str) -> Result<Analysis> {
let signature = self.resolve_signature(input)?;
let tx = self.transaction_json(&signature)?;
let account_keys = utils::resolve_account_keys(&tx);
let mut cpi_tree = cpi_tree::build_cpi_tree(&tx);
// Decode each instruction — name, arguments, and named accounts — from
// native layouts (always) or the program's on-chain Anchor IDL (cached).
{
let mut idls = self.idl_cache.lock().unwrap();
for e in &mut cpi_tree {
let (name, args, accounts) = ixname::enrich(
&self.client,
&mut idls,
&e.program,
&e.data,
&e.account_indexes,
&account_keys,
);
e.name = name;
e.args = args;
e.accounts = accounts;
}
}
Ok(Analysis {
overview: build_overview(&tx, &cpi_tree, account_keys.len()),
cpi_tree,
balance_change: diffs::account_diffs(&tx),
token_change: diffs::token_diffs(&tx),
compute: crate::compute::cu_per_program(&tx),
logs: tx["meta"]["logMessages"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|l| l.as_str().map(String::from))
.collect()
})
.unwrap_or_default(),
replay: None,
accounts: decode::describe_accounts(&self.client, &account_keys),
signature,
})
}
/// Diagnose a transaction: **why did it fail, and how do I fix it?** Reads the
/// *recorded* on-chain outcome (not a drift-prone re-simulation), resolves the
/// error to a plain name and message — from the Anchor logs, or the failing
/// program's on-chain IDL — and suggests a concrete fix. Free.
pub fn diagnose(&self, input: &str) -> Result<crate::Diagnosis> {
let signature = self.resolve_signature(input)?;
let tx = self.transaction_json(&signature)?;
Ok(crate::diagnose::diagnose_tx(&tx, |program| {
self.idl_for(program)
}))
}
/// Reconstruct the transaction's world for local replay — every touched
/// account, every program ELF, the on-chain outcome, and the IDLs needed to
/// name errors and fields. **All RPC happens here**; every run of the
/// returned [`Replay`] is local and free.
pub fn replay(&self, input: &str) -> Result<Replay> {
let signature = self.resolve_signature(input)?;
let tx = self.transaction_json(&signature)?;
let account_keys = utils::resolve_account_keys(&tx);
let pre = PreState::from_meta(&tx, &account_keys);
let mut ctx = crate::replay::build_context(
&self.client,
&signature,
&account_keys,
tx["slot"].as_u64(),
&pre,
)?;
self.preload_idls(&mut ctx);
Ok(Replay {
recorded: Some(OnchainRecord::from_tx_json(&tx)),
ctx,
time_travel: TimeTravel::default(),
fidelity: Fidelity::Current,
})
}
/// Replay a transaction as of its own slot, at the best fidelity the
/// available data allows — see [`Replay::fidelity`] for what you actually got.
/// Mutations compose on top: the returned [`Replay`]'s [`Replay::simulate`] /
/// [`Replay::verify`] apply what-if changes to that same state, so you can
/// mutate at a specific slot too.
///
/// Two tiers, chosen automatically:
/// - **Exact** — when an archival endpoint is set via [`Scope::with_archive`]
/// *and* it honors the historical `slot` parameter (e.g. Alchemy's Account
/// Archive). Accounts and program ELFs are loaded at the end of the slot
/// *before* the transaction's (its true pre-block boundary — fetching at
/// the transaction's own slot would return its post-state), then the
/// transaction's recorded pre-balances correct any same-slot predecessor's
/// balance effects. Same-slot predecessor *data* writes are the one
/// remaining gap of a slot-granular archive.
/// - **Reconstructed** — the free path, no archive required. Accounts load at
/// current state, then SOL and SPL-token balances are rewound to their
/// pre-transaction values from the transaction's own metadata, and the clock
/// is set to the transaction's slot. Faithful for balances and time; account
/// *data* (pool reserves, oracle prices) is still current — [`Fidelity`]
/// reports this honestly rather than pretending the replay is exact.
pub fn replay_at_slot(&self, input: &str) -> Result<Replay> {
let signature = self.resolve_signature(input)?;
let tx = self.transaction_json(&signature)?;
let slot = tx["slot"]
.as_u64()
.ok_or_else(|| Error::MalformedRpcResponse("transaction has no slot".into()))?;
let account_keys = utils::resolve_account_keys(&tx);
let pre = PreState::from_meta(&tx, &account_keys);
// Exact tier: only when an archive is set AND actually honors the slot.
let archive = self
.archive
.as_ref()
.filter(|a| crate::replay::archive_honors_slot(a, slot));
let (mut ctx, fidelity) = match archive {
Some(archive) => {
// Fetch at S-1: the archive answers "≤ slot", and at S that
// includes this transaction's own writes (post-state). The
// recorded pre-balances in `pre` then correct any same-slot
// predecessor's balance effects on top.
let ctx = crate::replay::build_context_at_slot(
archive,
&signature,
&account_keys,
slot.saturating_sub(1),
slot,
tx["blockTime"].as_i64(),
&pre,
)?;
(ctx, Fidelity::Exact { slot })
}
None => {
// Free reconstruction: current accounts + metadata balance rewind.
let ctx = crate::replay::build_context(
&self.client,
&signature,
&account_keys,
Some(slot),
&pre,
)?;
(ctx, Fidelity::Reconstructed { slot })
}
};
self.preload_idls(&mut ctx);
let mut replay = Replay {
recorded: Some(OnchainRecord::from_tx_json(&tx)),
ctx,
time_travel: TimeTravel::default(),
fidelity: Fidelity::Current,
};
replay.set_fidelity(fidelity);
// Anchor the clock to the transaction's slot/time for both tiers.
replay.warp_to_slot(slot);
if let Some(ts) = tx["blockTime"].as_i64() {
replay.warp_to_timestamp(ts);
}
Ok(replay)
}
/// Replay a transaction against archival account state at a **slot you
/// choose** — the "what if this ran at slot N?" primitive. Every account and
/// program ELF is loaded as of `slot`, and the clock is set to `slot`.
///
/// Unlike [`Scope::replay_at_slot`] (which reconstructs the transaction's own
/// slot for free from metadata), an *arbitrary* slot needs real historical
/// account state, so this **requires** an archival endpoint set via
/// [`Scope::with_archive`] that honors the historical `slot` parameter (e.g.
/// Alchemy's Account Archive). A non-archival endpoint is detected and
/// refused rather than silently returning current state.
pub fn replay_at(&self, input: &str, slot: u64) -> Result<Replay> {
let archive = self.archive.as_ref().ok_or_else(|| {
Error::InvalidSpec(
"replaying at an arbitrary slot needs historical account state — set an archival \
endpoint with Scope::with_archive(url) (e.g. Alchemy PAYG)"
.into(),
)
})?;
if !crate::replay::archive_honors_slot(archive, slot) {
return Err(Error::InvalidSpec(format!(
"the archive endpoint ignored historical slot {slot} and returned current state — \
replay_at needs an endpoint with account archival; a public node or Helius will not work"
)));
}
let signature = self.resolve_signature(input)?;
let tx = self.transaction_json(&signature)?;
let account_keys = utils::resolve_account_keys(&tx);
// The transaction's own metadata pre-state is only valid at its own slot;
// at an arbitrary slot the archive is authoritative, so pass none.
let pre = PreState::default();
let block_time = archive.get_block_time(slot).ok();
// An arbitrary slot means "the world as of end of slot N" — state and
// clock share the same boundary, no pre-balance patching.
let mut ctx = crate::replay::build_context_at_slot(
archive,
&signature,
&account_keys,
slot,
slot,
block_time,
&pre,
)?;
self.preload_idls(&mut ctx);
let mut replay = Replay {
recorded: Some(OnchainRecord::from_tx_json(&tx)),
ctx,
time_travel: TimeTravel::default(),
fidelity: Fidelity::Exact { slot },
};
replay.warp_to_slot(slot);
if let Some(ts) = block_time {
replay.warp_to_timestamp(ts);
}
Ok(replay)
}
/// Reconstruct the world for an **unsigned / not-yet-sent** transaction
/// (base64 wire bytes) — the pre-flight "what will this do if I send it
/// now?" primitive. Current on-chain state IS its pre-state, so no drift.
///
/// Accepts either a full serialized `VersionedTransaction` or a bare
/// serialized message — the "Base64 message" wallets in developer mode show
/// on the approval screen (and what Solana Explorer's inspector takes). A
/// bare message is wrapped with placeholder signatures before simulation.
pub fn preflight(&self, tx_b64: &str) -> Result<Replay> {
self.preflight_tx(parse_unsigned(tx_b64)?)
}
/// [`Scope::preflight`] for an already-deserialized transaction.
pub fn preflight_tx(
&self,
tx: solana_transaction::versioned::VersionedTransaction,
) -> Result<Replay> {
let mut ctx = crate::replay::preflight_context(&self.client, tx)?;
self.preload_idls(&mut ctx);
Ok(Replay {
recorded: None,
ctx,
time_travel: TimeTravel::default(),
fidelity: Fidelity::Current,
})
}
/// See [`Scope::preflight`]: parse base64 into a transaction, accepting a
/// bare message too. Exposed for testing.
#[doc(hidden)]
pub fn parse_unsigned_b64(
tx_b64: &str,
) -> Result<solana_transaction::versioned::VersionedTransaction> {
parse_unsigned(tx_b64)
}
/// The pre-sign overview of an unsigned transaction: serialized size, fee
/// breakdown (base + ComputeBudget priority fee), fee payer with live
/// balance, IDL-named instructions, and plain-English actions with danger
/// flags (delegations, authority changes, closes). Pairs with
/// [`Scope::preflight`] — decode what signing would do, then simulate it.
pub fn preflight_overview(&self, tx: &VersionedTransaction) -> crate::PreflightOverview {
let mut idls = self.idl_cache.lock().unwrap();
crate::preflight::build_overview(&self.client, &mut idls, tx)
}
/// Freeze a transaction's world into a portable, self-contained [`Fixture`]:
/// capture once, then replay deterministically forever with no RPC.
pub fn capture(&self, input: &str) -> Result<Fixture> {
self.replay(input)?.to_fixture()
}
/// Load the IDLs a replay will want — for every loaded program and every
/// distinct data-account owner — so error names, explanations, and
/// named-field asserts all resolve without further RPC.
fn preload_idls(&self, ctx: &mut ReplayContext) {
for program in ctx.interesting_programs() {
if let Some(idl) = self.idl_for(&program) {
ctx.add_idl(program, idl);
}
}
}
/// An explorer-style overview of any account or program address.
pub fn account(&self, address: &str) -> Result<AccountOverview> {
let address = address.trim();
if Address::from_str(address).is_err() {
return Err(Error::InvalidAddress(address.to_string()));
}
let Some((owner, lamports, executable, data)) = self.account_raw(address)? else {
return Ok(AccountOverview {
address: address.to_string(),
exists: false,
owner: String::new(),
lamports: 0,
executable: false,
data_len: 0,
program: None,
idl_name: None,
decoded: None,
});
};
let mut ov = AccountOverview {
address: address.to_string(),
exists: true,
owner: owner.clone(),
lamports,
executable,
data_len: data.len(),
program: None,
idl_name: None,
decoded: None,
};
if executable {
ov.program = self.program_info(&data, &owner);
ov.idl_name = self.idl_for(address).and_then(|idl| {
idl.get("metadata")
.and_then(|m| m.get("name"))
.or_else(|| idl.get("name"))
.and_then(|n| n.as_str())
.map(String::from)
});
} else {
// Reuse the decoder for recognized data accounts (SPL / IDL).
ov.decoded = decode::describe_accounts(&self.client, &[address.to_string()])
.into_iter()
.next()
.and_then(|a| a.decoded);
}
Ok(ov)
}
/// Recent transactions that touched an account or program — what an
/// explorer shows on an address page. Newest first.
pub fn signatures(&self, address: &str, limit: usize) -> Result<Vec<SigInfo>> {
let address = address.trim();
if Address::from_str(address).is_err() {
return Err(Error::InvalidAddress(address.to_string()));
}
let resp: serde_json::Value = self
.client
.send(
RpcRequest::GetSignaturesForAddress,
json!([address, { "limit": limit }]),
)
.map_err(Error::rpc)?;
let arr = resp.as_array().ok_or_else(|| {
Error::MalformedRpcResponse("getSignaturesForAddress: not an array".into())
})?;
Ok(arr
.iter()
.map(|s| SigInfo {
signature: s["signature"].as_str().unwrap_or_default().to_string(),
slot: s["slot"].as_u64(),
err: !s["err"].is_null(),
block_time: s["blockTime"].as_i64(),
})
.collect())
}
/// Decode one account, optionally with a caller-supplied IDL.
///
/// The on-chain IDL is the happy path, but plenty of programs never publish
/// one — including your own during development. Passing the IDL JSON (from
/// `target/idl/<program>.json`) gives full named-field decoding anyway.
pub fn decode_account(
&self,
address: &str,
user_idl: Option<&serde_json::Value>,
) -> Result<decode::AccountInfo> {
let address = address.trim();
if Address::from_str(address).is_err() {
return Err(Error::InvalidAddress(address.to_string()));
}
let mut info = decode::describe_accounts(&self.client, &[address.to_string()])
.into_iter()
.next()
.ok_or_else(|| Error::AccountNotFound(address.to_string()))?;
// A supplied IDL wins: it's authoritative for this program, and it beats
// the inferred layout we may have fallen back to.
if let Some(idl) = user_idl {
if let Ok(Some((_, _, _, bytes))) = self.account_raw(address) {
if let Some(d) = idl::decode_with_idl(idl, &bytes) {
info.decoded = Some(d);
}
}
}
Ok(info)
}
/// The instructions a program exposes, from its on-chain IDL — the input to
/// a transaction builder.
pub fn program_instructions(&self, program_id: &str) -> Result<Vec<idl::IdlInstruction>> {
let program_id = program_id.trim();
if Address::from_str(program_id).is_err() {
return Err(Error::InvalidAddress(program_id.to_string()));
}
let idl = self
.idl_for(program_id)
.ok_or_else(|| Error::NoIdl(program_id.to_string()))?;
Ok(idl::instructions(&idl))
}
/// A program's complete on-chain IDL, when the program publishes one.
pub fn program_idl(&self, program_id: &str) -> Result<Option<serde_json::Value>> {
let program_id = program_id.trim();
if Address::from_str(program_id).is_err() {
return Err(Error::InvalidAddress(program_id.to_string()));
}
Ok(self.idl_for(program_id))
}
/// Fetch an account's raw state: (owner, lamports, executable, data).
/// `None` if it doesn't exist.
/// `Ok(None)` means the account genuinely does not exist; `Err` means the
/// RPC call itself failed. Keeping these distinct stops a network outage from
/// masquerading as "account not found".
/// The account's current raw state on-chain — data bytes, lamports, owner —
/// or `None` if it doesn't exist. The free anchor and comparison point for
/// historical reconstruction (see the [`reconstruct`](crate::reconstruct)
/// module).
pub fn account_data(&self, address: &str) -> Result<Option<AccountState>> {
Ok(self
.account_raw(address)?
.map(|(owner, lamports, _executable, data)| AccountState {
data,
lamports,
owner,
}))
}
fn account_raw(&self, address: &str) -> Result<Option<RawAccount>> {
use base64::Engine;
let resp: serde_json::Value = self
.client
.send(
RpcRequest::GetAccountInfo,
json!([address, { "encoding": "base64" }]),
)
.map_err(Error::rpc)?;
let v = &resp["value"];
if v.is_null() {
return Ok(None);
}
let owner = match v["owner"].as_str() {
Some(o) => o.to_string(),
None => return Ok(None),
};
let Some(lamports) = v["lamports"].as_u64() else {
return Ok(None);
};
let executable = v["executable"].as_bool().unwrap_or(false);
let data = v["data"][0]
.as_str()
.and_then(|s| base64::engine::general_purpose::STANDARD.decode(s).ok())
.unwrap_or_default();
Ok(Some((owner, lamports, executable, data)))
}
/// Program deployment details from the (upgradeable) loader accounts.
fn program_info(&self, program_data_bytes: &[u8], owner: &str) -> Option<ProgramInfo> {
const UPGRADEABLE: &str = "BPFLoaderUpgradeab1e11111111111111111111111";
const LOADER_V2: &str = "BPFLoader2111111111111111111111111111111111";
if owner == UPGRADEABLE && program_data_bytes.len() >= 36 {
// Program account: [0..4]=variant, [4..36]=programdata address.
let pd_bytes: [u8; 32] = program_data_bytes[4..36].try_into().ok()?;
let pd_addr = Address::from(pd_bytes).to_string();
if let Ok(Some((_, _, _, pd))) = self.account_raw(&pd_addr) {
// ProgramData: [0..4]=variant, [4..12]=slot, [12]=Option tag, [13..45]=authority.
let slot = pd
.get(4..12)
.and_then(|s| s.try_into().ok())
.map(u64::from_le_bytes);
let (upgradeable, authority) = match pd.get(13..45) {
Some(a) if pd[12] == 1 => {
let a: [u8; 32] = a.try_into().ok()?;
(true, Some(Address::from(a).to_string()))
}
_ => (false, None),
};
return Some(ProgramInfo {
program_data: pd_addr,
upgradeable,
upgrade_authority: authority,
last_deployed_slot: slot,
});
}
return Some(ProgramInfo {
program_data: pd_addr,
upgradeable: true,
upgrade_authority: None,
last_deployed_slot: None,
});
}
if owner == LOADER_V2 {
return Some(ProgramInfo {
program_data: String::new(),
upgradeable: false,
upgrade_authority: None,
last_deployed_slot: None,
});
}
None
}
fn wait_for_transaction(&self, signature: &str) -> Result<serde_json::Value> {
const TIMEOUT: Duration = Duration::from_secs(20);
const POLL_INTERVAL: Duration = Duration::from_millis(100);
let deadline = Instant::now() + TIMEOUT;
let mut confirmed = false;
loop {
if Instant::now() >= deadline {
return if confirmed {
Err(Error::TransactionMetadataUnavailable {
signature: signature.to_string(),
})
} else {
Err(Error::ConfirmationTimeout {
signature: signature.to_string(),
})
};
}
if !confirmed {
let response: serde_json::Value = self
.client
.send(
RpcRequest::GetSignatureStatuses,
json!([
[signature],
{
"searchTransactionHistory": true,
}
]),
)
.map_err(Error::rpc)?;
let statuses = response
.get("value")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| {
Error::MalformedRpcResponse(
"getSignatureStatuses: missing value array".into(),
)
})?;
let status = statuses.first().ok_or_else(|| {
Error::MalformedRpcResponse("getSignatureStatuses: empty value array".into())
})?;
if !status.is_null() && status_is_confirmed(status) {
confirmed = true;
}
}
if confirmed {
if let Some(tx) = self.fetch_transaction_json(signature)? {
return Ok(tx);
}
}
let remaining = deadline.saturating_duration_since(Instant::now());
if !remaining.is_zero() {
thread::sleep(POLL_INTERVAL.min(remaining));
}
}
}
/// Submit a signed transaction while retaining its pre-transaction world
/// for replay, mutation, and time travel after it lands.
pub fn send_and_capture(&self, tx: VersionedTransaction) -> Result<CapturedTransaction> {
let mut replay = self.preflight_tx(tx.clone())?;
let signature = self
.client
.send_transaction_with_config(
&tx,
RpcSendTransactionConfig {
// A reverting transaction must still land so svmscope can
// capture its program failure as data.
skip_preflight: true,
..RpcSendTransactionConfig::default()
},
)
.map_err(Error::rpc)?;
let tx_json = self.wait_for_transaction(&signature.to_string())?;
replay.set_recorded(OnchainRecord::from_tx_json(&tx_json));
Ok(CapturedTransaction {
signature: signature.to_string(),
replay,
})
}
}
/// The transaction's actual on-chain outcome, kept alongside the replay so
/// local results can be compared against what really happened.
#[derive(Debug, Clone, PartialEq, Serialize, serde::Deserialize)]
pub struct OnchainRecord {
/// Whether the transaction succeeded on-chain.
pub success: bool,
/// The on-chain error, as reported by the RPC (JSON-encoded), when it failed.
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// Fee paid on-chain, in lamports.
pub fee: u64,
/// Compute units consumed on-chain, if reported.
pub compute_units: Option<u64>,
/// Slot the transaction landed in, if reported.
pub slot: Option<u64>,
/// Block time (unix seconds), when the RPC reports it.
pub block_time: Option<i64>,
/// The program logs the transaction produced on-chain.
pub logs: Vec<String>,
}
impl OnchainRecord {
pub(crate) fn from_tx_json(tx: &serde_json::Value) -> OnchainRecord {
// `getTransaction` may legally return `meta: null`. Treating a null meta
// as `err == null` would fabricate a success (and let `matches_onchain`
// compare against it); instead record it as an explicit unknown-outcome
// failure so nothing downstream reads a phantom success.
let has_meta = tx["meta"].is_object();
OnchainRecord {
success: has_meta && tx["meta"]["err"].is_null(),
error: if !has_meta {
Some("transaction metadata unavailable".to_string())
} else {
(!tx["meta"]["err"].is_null()).then(|| tx["meta"]["err"].to_string())
},
fee: tx["meta"]["fee"].as_u64().unwrap_or(0),
compute_units: tx["meta"]["computeUnitsConsumed"].as_u64(),
slot: tx["slot"].as_u64(),
block_time: tx["blockTime"].as_i64(),
logs: tx["meta"]["logMessages"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|l| l.as_str().map(String::from))
.collect()
})
.unwrap_or_default(),
}
}
}
/// How faithful a replay's starting state is to the transaction's real slot —
/// the honest label on every replay, so a convincing-but-drifted run is never
/// mistaken for an exact one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Fidelity {
/// Current-state replay ([`Scope::replay`]) — no historical anchoring.
Current,
/// Balances rewound to their pre-transaction values from the transaction's
/// own metadata, clock set to the transaction's slot; account *data* is still
/// current-state. Free — no archive needed.
Reconstructed {
/// The transaction's own slot, that the clock is anchored to.
slot: u64,
},
/// Every account and program ELF loaded at the true slot from an archive.
Exact {
/// The transaction's own slot, that state was loaded at.
slot: u64,
},
}
impl Fidelity {
/// A short human label: `current`, `reconstructed@<slot>`, `exact@<slot>`.
pub fn label(&self) -> String {
match self {
Fidelity::Current => "current".to_string(),
Fidelity::Reconstructed { slot } => format!("reconstructed@{slot}"),
Fidelity::Exact { slot } => format!("exact@{slot}"),
}
}
}
/// A reconstructed account's raw state — its data bytes, lamports, and owner.
#[derive(Debug, Clone, Serialize)]
pub struct AccountState {
/// The account's raw data bytes.
pub data: Vec<u8>,
/// The account's lamport balance.
pub lamports: u64,
/// The account's owner program, base58.
pub owner: String,
}
/// Where an account's loaded bytes came from — the honest per-account source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Provenance {
/// A frozen fixture — offline, content-addressed.
Fixture,
/// A historical archive, at the transaction's true slot.
HistoricalArchive,
/// Reconstructed from the transaction's own metadata (a pre-tx balance, or a
/// since-closed account rebuilt from `preTokenBalances`).
MetadataRewind,
/// Loaded at current state from a normal RPC — may differ from the true slot.
CurrentRpc,
}
/// One account's provenance within a replay.
#[derive(Debug, Clone, Serialize)]
pub struct AccountProvenance {
/// The account address.
pub address: String,
/// Where its loaded bytes came from.
pub source: Provenance,
/// Whether it was loaded as an executable program (its ELF) rather than data.
pub is_program: bool,
/// A blake3 hash of the exact bytes loaded, for content addressing.
pub hash: String,
}
/// An honest report of how faithful a replay's starting state is: the verdict,
/// where every account's bytes came from, which accounts may have drifted from
/// the transaction's true slot, and whether there is a recorded on-chain outcome
/// to check the replay against. Trust is a product feature — svmscope should
/// never silently hand back a convincing but historically inaccurate replay.
#[derive(Debug, Clone, Serialize)]
pub struct FidelityCertificate {
/// The overall fidelity tier of this replay.
pub fidelity: Fidelity,
/// The (possibly warped) clock the replay runs at, human-readable.
pub clock: String,
/// Provenance and hash of every loaded account.
pub accounts: Vec<AccountProvenance>,
/// Addresses whose bytes are current-state in a historical replay, so their
/// data may differ from the true slot. Empty for an exact or current replay.
pub drifted: Vec<String>,
/// Whether a recorded on-chain outcome exists to verify the replay against.
pub verifiable: bool,
}
impl FidelityCertificate {
/// A one-line human summary of the certificate.
pub fn summary(&self) -> String {
let n = self.accounts.len();
let verify = if self.verifiable {
"verifiable against mainnet"
} else {
"no recorded outcome"
};
match self.drifted.len() {
0 => format!(
"{} · {n} accounts, none drifted · {verify}",
self.fidelity.label()
),
d => format!(
"{} · {n} accounts, {d} may have drifted · {verify}",
self.fidelity.label()
),
}
}
}
/// The result of replaying a transaction against an original program and a
/// patched one — the pre-deployment "does this patch change what happened?" gate.
#[derive(Debug, Clone, Serialize)]
pub struct PatchComparison {
/// The program whose ELF was swapped.
pub program: String,
/// The outcome with the original (currently-loaded) program.
pub before: ReplayResult,
/// The outcome with the patched program.
pub after: ReplayResult,
}
impl PatchComparison {
/// Whether the patch flipped success ↔ failure.
pub fn success_changed(&self) -> bool {
self.before.success != self.after.success
}
/// Whether the patch changed the (formatted) error.
pub fn error_changed(&self) -> bool {
self.before.error != self.after.error
}
/// The change in compute units (patched − original), which may be negative.
pub fn compute_delta(&self) -> i64 {
self.after.compute_units as i64 - self.before.compute_units as i64
}
/// Whether the patch changed anything observable (outcome, error, or compute).
pub fn changed(&self) -> bool {
self.success_changed() || self.error_changed() || self.compute_delta() != 0
}
/// A one-line human summary of what the patch changed.
pub fn summary(&self) -> String {
if !self.changed() {
return format!("{}: no observable change", self.program);
}
let outcome = match (self.before.success, self.after.success) {
(false, true) => "revert → success".to_string(),
(true, false) => "success → revert".to_string(),
_ => format!(
"{:?} → {:?}",
self.before.error.as_deref().unwrap_or("ok"),
self.after.error.as_deref().unwrap_or("ok")
),
};
format!(
"{}: {outcome} · compute {:+}",
self.program,
self.compute_delta()
)
}
}
/// A transaction's reconstructed world — fetched once via [`Scope::replay`],
/// then replayed locally any number of times. Every run builds a pristine SVM,
/// so runs are independent, repeatable, and free.
pub struct Replay {
pub(crate) ctx: ReplayContext,
/// What actually happened on-chain (`None` for pre-flight transactions and
/// fixtures captured before outcomes were recorded).
recorded: Option<OnchainRecord>,
time_travel: TimeTravel,
fidelity: Fidelity,
}
impl Replay {
pub(crate) fn set_recorded(&mut self, recorded: OnchainRecord) {
self.recorded = Some(recorded);
}
pub(crate) fn set_fidelity(&mut self, fidelity: Fidelity) {
self.fidelity = fidelity;
}
/// How faithful this replay's starting state is to the transaction's slot.
pub fn fidelity(&self) -> Fidelity {
self.fidelity
}
/// An honest fidelity certificate for this replay: the verdict, per-account
/// provenance and hashes, which accounts may have drifted from the true slot,
/// and whether there is a recorded on-chain outcome to verify against.
pub fn certificate(&self) -> FidelityCertificate {
let accounts: Vec<AccountProvenance> = self
.ctx
.loaded_info()
.into_iter()
.map(|i| {
let source = match self.fidelity {
Fidelity::Exact { .. } => Provenance::HistoricalArchive,
// A balance-only account (system-owned, no data) is faithfully
// rewound from metadata; program ELFs and program-owned data
// accounts are still current-state.
Fidelity::Reconstructed { .. }
if !i.is_program && i.owner_is_system && i.data_len == 0 =>
{
Provenance::MetadataRewind
}
Fidelity::Reconstructed { .. } => Provenance::CurrentRpc,
Fidelity::Current => Provenance::CurrentRpc,
};
AccountProvenance {
address: i.address,
source,
is_program: i.is_program,
hash: i.hash,
}
})
.collect();
// In a historical replay, any account still on current-state bytes is a
// potential drift point. A plainly-current replay isn't "drifted" — it
// never claimed to be historical.
let drifted = if matches!(self.fidelity, Fidelity::Current) {
Vec::new()
} else {
accounts
.iter()
.filter(|a| a.source == Provenance::CurrentRpc)
.map(|a| a.address.clone())
.collect()
};
let verifiable = self
.recorded
.as_ref()
.is_some_and(|r| r.error.as_deref() != Some("transaction metadata unavailable"));
FidelityCertificate {
fidelity: self.fidelity,
clock: self.ctx.describe_clock(),
accounts,
drifted,
verifiable,
}
}
/// Rebuild a replay from a frozen fixture — fully offline, no RPC. A v2
/// fixture restores the recorded on-chain outcome and captured IDLs too.
pub fn from_fixture(fx: &Fixture) -> Result<Replay> {
Ok(Replay {
ctx: ReplayContext::from_fixture(fx)?,
recorded: fx.recorded.clone(),
time_travel: TimeTravel::default(),
fidelity: Fidelity::Current,
})
}
/// What actually happened on-chain, when known.
pub fn recorded(&self) -> Option<&OnchainRecord> {
self.recorded.as_ref()
}
// --- time travel ---------------------------------------------------------
/// Jump forward `n` slots (additive with other jumps).
pub fn advance_slots(&mut self, n: i64) {
// Saturating so repeated extreme jumps clamp instead of overflow-panicking
// in debug builds; the clock application saturates too.
self.time_travel.slots = Some(self.time_travel.slots.unwrap_or(0).saturating_add(n));
self.apply_tt();
}
/// Jump forward `n` epochs (additive with other jumps).
pub fn advance_epochs(&mut self, n: i64) {
self.time_travel.epochs = Some(self.time_travel.epochs.unwrap_or(0).saturating_add(n));
self.apply_tt();
}
/// Jump forward `n` seconds (additive with other jumps) — vesting cliffs,
/// cooldowns, auction deadlines.
pub fn advance_seconds(&mut self, n: i64) {
self.time_travel.seconds = Some(self.time_travel.seconds.unwrap_or(0).saturating_add(n));
self.apply_tt();
}
/// Set the clock's slot outright (wins over relative jumps).
pub fn warp_to_slot(&mut self, slot: u64) {
self.time_travel.at_slot = Some(slot);
self.apply_tt();
}
/// Set the clock's epoch outright (wins over relative jumps).
pub fn warp_to_epoch(&mut self, epoch: u64) {
self.time_travel.at_epoch = Some(epoch);
self.apply_tt();
}
/// Set the clock's unix timestamp outright (wins over relative jumps).
pub fn warp_to_timestamp(&mut self, unix_timestamp: i64) {
self.time_travel.at_unix_timestamp = Some(unix_timestamp);
self.apply_tt();
}
/// Replace the whole clock warp at once (the JSON suite format's shape).
pub fn set_time_travel(&mut self, tt: TimeTravel) {
self.time_travel = tt;
self.apply_tt();
}
fn apply_tt(&mut self) {
self.ctx.set_time_travel(self.time_travel.clone());
}
/// A human description of the (possibly warped) clock replays run at,
/// e.g. "slot 488,863,115 · epoch 1131 · 2026-09-26 14:03 UTC".
pub fn describe_clock(&self) -> String {
self.ctx.describe_clock()
}
// --- feature gates & IDLs ------------------------------------------------
/// Flip one runtime feature gate for subsequent runs — replay a transaction
/// as if a not-yet-live feature were active (or an active one weren't).
pub fn set_feature(&mut self, id: Address, active: bool) {
self.ctx.push_feature_toggle(FeatureToggle { id, active });
}
/// Replace all feature toggles at once (the JSON suite format's shape).
pub fn set_features(&mut self, toggles: Vec<FeatureToggle>) {
self.ctx.set_feature_toggles(toggles);
}
/// Register a program's IDL for named-field asserts and error explanations —
/// for programs that publish nothing on-chain (e.g. your own, in development).
pub fn add_idl(&mut self, program: impl Into<String>, idl: serde_json::Value) {
self.ctx.add_idl(program.into(), idl);
}
// --- execution -----------------------------------------------------------
/// Replay the transaction as-is. A reverting transaction is a successful
/// observation (`result.success == false`), never an `Err`.
pub fn run(&self) -> Result<Replayed> {
self.simulate(&[])
}
/// Replay after applying what-if `mutations` to a fresh copy of the state.
pub fn simulate(&self, mutations: &[Mutation]) -> Result<Replayed> {
let warped = !self.time_travel.is_noop();
let (mut result, raw_diffs) = self.ctx.run_with_diff(mutations)?;
let explain = (!result.success)
.then(|| explain_error(&result, self.ctx.idl_map()))
.flatten();
if result.error_name.is_none() {
result.error_name = explain.as_ref().map(|e| e.title.clone());
}
Ok(Replayed {
diffs: decode_diffs(raw_diffs, self.ctx.idl_map()),
clock: warped.then(|| self.ctx.describe_clock()),
explain,
result,
})
}
/// Unroll the transaction into a step-by-step [`Trace`] — the debugger's
/// view. Every top-level instruction is replayed as a prefix (`0..=k`) and
/// diffed against the previous prefix, so each step carries the exact
/// accounts it changed; CPIs are attached from the runtime's inner
/// instruction list with their logs and compute. `mutations` are applied to
/// the initial state first ("what if this field were X, step by step").
pub fn trace(&self, mutations: &[Mutation]) -> Result<Trace> {
use crate::replay::replay_result_of;
use crate::trace::{
spans_from_logs, DecodedEvent, LogSpan, ReturnData, Step, StepAccountState, StepError,
};
use base64::Engine;
use solana_account::Account;
use std::collections::HashMap;
// A prefix replay per instruction: bound it so a pathological 60-instruction
// transaction can't turn one request into a minute of CPU.
const MAX_TRACE_INSTRUCTIONS: usize = 64;
let n_ix = self.ctx.transaction().message.instructions().len();
if n_ix > MAX_TRACE_INSTRUCTIONS {
return Err(Error::InvalidSpec(format!(
"transaction has {n_ix} instructions; the debugger traces up to {MAX_TRACE_INSTRUCTIONS}"
)));
}
let runs = self.ctx.trace_raw(mutations)?;
let idls = self.ctx.idl_map();
let keys = self.ctx.message_account_keys();
let tx = self.ctx.transaction();
let top_ixs = tx.message.instructions();
let n = top_ixs.len();
// The whole transaction is the last prefix. Its logs are the canonical
// ones every step's log range indexes into: instruction k's lines sit at
// the same positions in prefix k and in the full run (execution is
// deterministic and later instructions can't rewrite earlier logs).
let full = runs.last().map(|r| replay_result_of(&r.result));
let mut result = full.clone().unwrap_or_default();
let explain = (!result.success)
.then(|| explain_error(&result, idls))
.flatten();
if result.error_name.is_none() {
result.error_name = explain.as_ref().map(|e| e.title.clone());
}
let whole_succeeded = result.success;
// Every invocation the full run logged, pre-order. Depth-1 spans are the
// top-level instructions in message order; the spans that follow a
// depth-1 span until the next one are its CPIs.
let full_spans: Vec<LogSpan> = spans_from_logs(&result.logs, 0);
let top_span_idx: Vec<usize> = full_spans
.iter()
.enumerate()
.filter(|(_, s)| s.depth == 1)
.map(|(i, _)| i)
.collect();
let spans_for = |k: usize| -> &[LogSpan] {
match top_span_idx.get(k) {
Some(&start) => {
let end = top_span_idx.get(k + 1).copied().unwrap_or(full_spans.len());
&full_spans[start..end]
}
None => &[],
}
};
let mut steps: Vec<Step> = Vec::new();
let mut failed_step: Option<usize> = None;
let mut prev_post: Option<HashMap<Address, Account>> = None;
let mut halted = false; // a real failure happened; later steps never ran
for (k, run) in runs.iter().enumerate().take(n) {
let meta = match &run.result {
Ok(m) => m,
Err(f) => &f.meta,
};
let run_failed = run.result.is_err();
let artifact = run_failed && whole_succeeded;
let pos = run.keep.iter().position(|&i| i == k).unwrap_or(0);
// Nodes for this step: the top-level instruction, then its CPIs in
// emission order (already pre-order), from the prefix run's own
// inner-instruction list.
let mut nodes: Vec<(
u8,
&solana_message::compiled_instruction::CompiledInstruction,
)> = vec![(1, &top_ixs[k])];
if let Some(inner) = meta.inner_instructions.get(pos) {
nodes.extend(inner.iter().map(|ii| (ii.stack_height, &ii.instruction)));
}
let spans = spans_for(k);
let aligned = spans.len() == nodes.len()
&& spans.iter().zip(nodes.iter()).all(|(s, (d, ix))| {
s.depth == *d
&& keys
.get(ix.program_id_index as usize)
.map(|p| *p == s.program)
.unwrap_or(false)
});
let top_range = spans.first().map(|s| (s.start, s.end));
// Diffs for the top-level step: this prefix's post-state vs the
// previous prefix's (or the pre-transaction state for k == 0).
let post: Option<HashMap<Address, Account>> =
run.post.as_ref().map(|p| p.iter().cloned().collect());
let mut diffs = Vec::new();
if let Some(post) = &post {
let mut raw = Vec::new();
for key in &keys {
let Ok(addr) = Address::from_str(key) else {
continue;
};
let before = prev_post
.as_ref()
.and_then(|m| m.get(&addr).cloned())
.or_else(|| self.ctx.pre_account_owned(key));
let after = post.get(&addr).cloned().or_else(|| before.clone());
let (Some(b), Some(a)) = (&before, &after) else {
continue;
};
if b.lamports == a.lamports && b.data == a.data && b.owner == a.owner {
continue;
}
raw.push(crate::replay::RawAccountDiff {
address: key.clone(),
owner: a.owner.to_string(),
lamports_before: b.lamports,
lamports_after: a.lamports,
data_before: b.data.clone(),
data_after: a.data.clone(),
});
}
diffs = decode_diffs(raw, idls);
}
// State after this prefix, for the accounts each node names.
let changed: std::collections::HashSet<String> =
diffs.iter().map(|d| d.address.clone()).collect();
let state_of =
|addr: &str, role: Option<String>, decode_fields: bool| -> StepAccountState {
let acc = post
.as_ref()
.and_then(|m| {
Address::from_str(addr)
.ok()
.and_then(|a| m.get(&a).cloned())
})
.or_else(|| self.ctx.pre_account_owned(addr));
match acc {
Some(a) => {
let owner = a.owner.to_string();
let decoded = if decode_fields || changed.contains(addr) {
decode::decode_bytes(&owner, &a.data).or_else(|| {
idls.get(&owner)
.and_then(|i| idl::decode_with_idl(i, &a.data))
})
} else {
None
};
StepAccountState {
address: addr.to_string(),
role,
owner,
lamports: a.lamports,
data_len: a.data.len(),
type_name: decoded.as_ref().map(|d| d.type_name.clone()),
fields: decoded.map(|d| d.fields).unwrap_or_default(),
changed: changed.contains(addr),
exists: true,
}
}
None => StepAccountState {
address: addr.to_string(),
role,
owner: String::new(),
lamports: 0,
data_len: 0,
type_name: None,
fields: Vec::new(),
changed: changed.contains(addr),
exists: false,
},
}
};
let return_data = (!meta.return_data.data.is_empty()).then(|| ReturnData {
program: meta.return_data.program_id.to_string(),
data_base64: base64::engine::general_purpose::STANDARD
.encode(&meta.return_data.data),
});
// Emit the nodes.
let base_index = steps.len();
let mut path_stack: Vec<usize> = Vec::new(); // child counters per depth
let mut innermost_failure: Option<usize> = None;
for (i, (depth, ix)) in nodes.iter().enumerate() {
let program = keys
.get(ix.program_id_index as usize)
.cloned()
.unwrap_or_default();
let account_indexes: Vec<usize> = ix.accounts.iter().map(|&a| a as usize).collect();
let (name, args, accounts) =
ixname::enrich_offline(idls, &program, &ix.data, &account_indexes, &keys);
// Path: "k" for the top, then "k.c0", "k.c0.c1", …
let d = *depth as usize;
path_stack.truncate(d.saturating_sub(1));
while path_stack.len() < d.saturating_sub(1) {
path_stack.push(0);
}
let path = if d <= 1 {
k.to_string()
} else {
let mut p = k.to_string();
for c in &path_stack {
p.push('.');
p.push_str(&c.to_string());
}
p
};
if d >= 2 {
if let Some(last) = path_stack.last_mut() {
*last += 1;
}
}
// Per-node state: the accounts this instruction names, capped so a
// 40-account Jupiter route doesn't dump megabytes of fields.
let mut seen = std::collections::HashSet::new();
let state: Vec<StepAccountState> = accounts
.iter()
.filter(|a| seen.insert(a.address.clone()))
.take(96)
.enumerate()
.map(|(n, a)| state_of(&a.address, a.name.clone(), n < 32))
.collect();
let (logs, cu, success) = if aligned {
let s = &spans[i];
((s.start, s.end), s.cu_consumed, s.success)
} else if i == 0 {
let r = top_range.unwrap_or((result.logs.len(), result.logs.len()));
(r, spans.first().and_then(|s| s.cu_consumed), !run_failed)
} else {
let r = top_range.unwrap_or((result.logs.len(), result.logs.len()));
(r, None, !run_failed)
};
if aligned && !success {
innermost_failure = Some(base_index + i);
}
// Events: `Program data: <b64>` lines inside this node's own log
// range, decoded against its program's IDL.
let events: Vec<DecodedEvent> = idls
.get(&program)
.map(|idl| {
let (a, b) = logs;
result.logs[a.min(result.logs.len())..b.min(result.logs.len())]
.iter()
.filter_map(|l| l.strip_prefix("Program data: "))
.filter_map(|b64| {
base64::engine::general_purpose::STANDARD
.decode(b64.trim())
.ok()
})
.filter_map(|bytes| idl::decode_event(idl, &bytes))
.map(|d| DecodedEvent {
name: d.type_name,
fields: d.fields,
})
.collect()
})
.unwrap_or_default();
let node_return = return_data
.as_ref()
.filter(|r| r.program == program && i == 0 || r.program == program)
.cloned();
steps.push(Step {
path,
depth: *depth,
index: k,
program,
name,
args,
accounts,
cu_consumed: cu,
logs,
diffs: if i == 0 {
std::mem::take(&mut diffs)
} else {
Vec::new()
},
state_known: i == 0 && post.is_some() && !halted,
success: if halted { false } else { success },
error: None,
return_data: node_return,
events,
state,
prefix_artifact: artifact,
});
}
if run_failed && !artifact && !halted {
// Attribute the error to the innermost failing invocation, or
// the top-level step when logs could not be aligned.
let target = innermost_failure.unwrap_or(base_index);
let raw = match &run.result {
Err(f) => format!("{:?}", f.err),
Ok(_) => String::new(),
};
let r = replay_result_of(&run.result);
steps[target].error = Some(StepError {
raw,
explain: explain_error(&r, idls),
});
steps[target].success = false;
failed_step = Some(target);
halted = true;
}
if !run_failed {
prev_post = post;
}
}
Ok(Trace {
signature: self.ctx.signature().to_string(),
fee_payer: keys.first().cloned().unwrap_or_default(),
steps,
result,
explain,
failed_step,
clock: (!self.time_travel.is_noop()).then(|| self.ctx.describe_clock()),
fidelity: self.fidelity.label().to_string(),
onchain_success: self.recorded.as_ref().map(|r| r.success),
})
}
/// Replay with `mutations` and read one account's raw post-execution state.
/// The building block of historical reconstruction (see the [`reconstruct`]
/// module): chain it by injecting an account's reconstructed bytes, replaying
/// its next write, and reading it out again. `None` if the account does not
/// exist after the replay.
///
/// [`reconstruct`]: crate::reconstruct
pub fn account_after(
&self,
mutations: &[Mutation],
address: &str,
) -> Result<Option<AccountState>> {
let (_result, acc) = self.ctx.run_and_read_account(mutations, address)?;
Ok(acc.map(|a| AccountState {
data: a.data,
lamports: a.lamports,
owner: a.owner.to_string(),
}))
}
// --- counterfactual search -----------------------------------------------
/// Binary-search a numeric knob for the value at which the outcome flips —
/// "at what oracle price does this stop succeeding?", "what is the minimum
/// balance that avoids the revert?". `mutate(v)` builds the mutation(s) that
/// set the knob to candidate `v`; the search runs over the inclusive range
/// `[lo, hi]` and returns the boundary (or `None` if the outcome is the same
/// at both bounds). Every candidate is a fresh, independent replay, so the
/// search never mutates shared state. Assumes a single crossing.
///
/// ```no_run
/// # use svmscope::{Mutation, Scope};
/// # let replay = Scope::new("").replay("")?;
/// // Lowest fee-payer balance at which the transaction still lands:
/// let payer = "…".to_string();
/// let boundary = replay.find_threshold(0, 5_000_000_000, |v| {
/// vec![Mutation::lamports(payer.clone(), v)]
/// })?;
/// # Ok::<(), svmscope::Error>(())
/// ```
pub fn find_threshold(
&self,
lo: u64,
hi: u64,
mutate: impl Fn(u64) -> Vec<Mutation>,
) -> Result<Option<Threshold>> {
search_threshold(lo, hi, |v| Ok(self.simulate(&mutate(v))?.result.success))
}
/// Shrink a set of mutations to a minimal subset that still flips the
/// outcome — "which of these changes actually caused the difference?".
///
/// "Flips" means the subset's success differs from the un-mutated baseline.
/// Runs a greedy delta-debugging pass: drop each mutation whose removal keeps
/// the outcome flipped. Returns the minimal subset (input order preserved),
/// or an empty vec if the full set doesn't change the baseline outcome at all.
pub fn minimize_mutations(&self, mutations: &[Mutation]) -> Result<Vec<Mutation>> {
let baseline = self.run()?.result.success;
let target = self.simulate(mutations)?.result.success;
if target == baseline {
return Ok(Vec::new());
}
let mut keep = mutations.to_vec();
let mut i = 0;
while i < keep.len() {
let mut trial = keep.clone();
trial.remove(i);
if self.simulate(&trial)?.result.success == target {
keep = trial; // mutation i wasn't needed to keep the flip
} else {
i += 1; // it's load-bearing; keep it and move on
}
}
Ok(keep)
}
// --- patch lab -----------------------------------------------------------
/// Replace a program's ELF bytecode in this replay's world, for A/B patch
/// testing. Returns the previous ELF (restore it by calling again with that).
/// Errors if `program_id` isn't loaded as a program in this replay.
pub fn replace_program(&mut self, program_id: &str, elf: Vec<u8>) -> Result<Vec<u8>> {
self.ctx.replace_program(program_id, elf).ok_or_else(|| {
Error::InvalidSpec(format!(
"{program_id} is not a loaded program in this replay"
))
})
}
/// Replay the transaction against the original program and against
/// `patched_elf`, and report the difference — the pre-deployment gate "does
/// this patch change what really happened?". `mutations` apply to both runs.
/// `self` is left unchanged: the patch is swapped in for the comparison, then
/// the original restored.
pub fn compare_patch(
&mut self,
program_id: &str,
patched_elf: Vec<u8>,
mutations: &[Mutation],
) -> Result<PatchComparison> {
let before = self.simulate(mutations)?.result;
let original = self.replace_program(program_id, patched_elf)?;
let after = self.simulate(mutations)?.result;
// Restore the original ELF so the replay is reusable afterwards.
self.ctx.replace_program(program_id, original);
Ok(PatchComparison {
program: program_id.to_string(),
before,
after,
})
}
/// Run a suite of scenarios, each against a fresh copy of the state.
/// Mutations across the whole suite are validated before anything executes.
pub fn run_suite(&self, scenarios: &[Scenario]) -> Result<Vec<ScenarioOutcome>> {
crate::replay::run_suite(&self.ctx, self.recorded.as_ref(), scenarios)
}
/// Run one named scenario — mutations plus the checks that must hold —
/// and report it. Sugar over [`Replay::run_suite`] for the single case.
pub fn verify(
&self,
name: impl Into<String>,
mutations: &[Mutation],
checks: &[Check],
) -> Result<ScenarioOutcome> {
let scenario = Scenario {
name: name.into(),
mutations: mutations.to_vec(),
checks: checks.to_vec(),
};
let mut outcomes = self.run_suite(std::slice::from_ref(&scenario))?;
Ok(outcomes.remove(0))
}
/// Freeze this world into a portable [`Fixture`] for offline CI replay.
/// Captures the loaded IDLs and the recorded on-chain outcome, so field
/// asserts and [`Check::matches_onchain`] work offline too.
pub fn to_fixture(&self) -> Result<Fixture> {
let mut fx = self.ctx.to_fixture()?;
fx.recorded = self.recorded.clone();
Ok(fx)
}
/// Generate a self-contained Rust regression test that freezes this incident
/// permanently: it loads the fixture at `fixture_path` (write
/// `to_fixture()?.to_json()?` there next to your test), rebuilds the replay
/// fully offline, and asserts the same outcome this replay produces now — a
/// reverting incident also pins the exact error. Returns the test source.
pub fn regression_test(&self, test_name: &str, fixture_path: &str) -> Result<String> {
let outcome = self.run()?;
Ok(crate::report::rust_regression_test(
test_name,
fixture_path,
outcome.result.success,
outcome.result.error.as_deref(),
))
}
}
/// The outcome of one local replay: the result itself, what changed, and — on
/// failure — a plain-language explanation.
#[derive(Debug, Serialize)]
pub struct Replayed {
/// The replay's outcome (success, error, logs, CU).
pub result: ReplayResult,
/// Every account the transaction changed, before → after, with named
/// fields where the layout (or an IDL) is known.
pub diffs: Vec<AccountDiff>,
/// Where the clock was warped to, when time travel was requested.
pub clock: Option<String>,
/// The failure in plain language, when the replay failed.
pub explain: Option<Explanation>,
}
impl Replayed {
/// The wire shape the HTTP API serves (`SimulationReport`) — same JSON as v0.1.
pub fn into_report(self) -> SimulationReport {
SimulationReport {
replay: self.result,
clock: self.clock,
explain: self.explain,
diffs: self.diffs,
preflight: None,
}
}
}
/// Decode base64 into an unsigned transaction for preflight. Accepts either a
/// full serialized `VersionedTransaction`, or a bare serialized message — the
/// "Base64 message" wallets in developer mode show on the approval screen (and
/// what Solana Explorer's inspector takes). A bare message is wrapped with
/// placeholder signatures, which is fine for simulation: sigverify is off.
fn parse_unsigned(tx_b64: &str) -> Result<solana_transaction::versioned::VersionedTransaction> {
use base64::Engine;
use bincode::Options;
let bytes = base64::engine::general_purpose::STANDARD
.decode(tx_b64.trim())
.map_err(|e| Error::TxDecode(format!("bad base64: {e}")))?;
// Strict parse: Solana's wire format is bincode fixint, and rejecting
// trailing bytes matters here — the two shapes are prefix-ambiguous (a bare
// message's first byte can read as a signature count), so a lax parse can
// "succeed" wrongly. Full consumption plus the signatures==header invariant
// disambiguates in practice.
let strict = bincode::DefaultOptions::new()
.with_fixint_encoding()
.reject_trailing_bytes();
let as_tx = strict.deserialize::<solana_transaction::versioned::VersionedTransaction>(&bytes);
if let Ok(tx) = &as_tx {
if tx.signatures.len() == tx.message.header().num_required_signatures as usize {
return Ok(as_tx.unwrap());
}
}
if let Ok(message) = strict.deserialize::<solana_message::VersionedMessage>(&bytes) {
// The "Base64 message" a wallet in developer mode shows pre-signing.
let n = message.header().num_required_signatures as usize;
return Ok(solana_transaction::versioned::VersionedTransaction {
signatures: vec![Default::default(); n],
message,
});
}
// A transaction whose signature count disagrees with its header is unusual
// but parseable — accept it rather than refuse (sigverify is off anyway).
match as_tx {
Ok(tx) => Ok(tx),
Err(tx_err) => Err(Error::TxDecode(format!(
"not a serialized transaction ({tx_err}) and not a bare message either — paste \
either Buffer.from(tx.serialize()).toString('base64') or a wallet's base64 message"
))),
}
}
/// Turn a program error into a human explanation using the loaded IDLs.
/// (Same logic the v0.1 library ran with live RPC — now resolved offline
/// against the IDLs preloaded into the replay context.)
fn explain_error(
r: &ReplayResult,
idls: &HashMap<String, serde_json::Value>,
) -> Option<Explanation> {
let raw = r.error.as_ref()?;
// Which program failed? The last "Program <id> failed" line names it.
let program = r
.logs
.iter()
.rev()
.find_map(|l| {
l.strip_prefix("Program ")
.and_then(|s| s.split(" failed").next())
})
.map(|s| s.trim().to_string())
.filter(|s| Address::from_str(s).is_ok());
// Anchor prints the resolved error itself — prefer that, it's already human.
if let Some(line) = r.logs.iter().rev().find(|l| l.contains("Error Message:")) {
let detail = line
.split("Error Message:")
.nth(1)
.unwrap_or("")
.trim()
.to_string();
let title = line
.split("Error Code:")
.nth(1)
.and_then(|s| s.split('.').next())
.map(|s| s.trim().to_string())
.unwrap_or_else(|| "Program error".into());
return Some(Explanation {
title,
detail,
program,
raw: raw.clone(),
});
}
// Native programs define their errors in code, not an IDL. Name the common ones.
if let (Some(p), Some(code)) = (
program.as_deref(),
raw.split("Custom(")
.nth(1)
.and_then(|s| s.split(')').next())
.and_then(|s| s.parse::<u64>().ok()),
) {
if let Some((title, detail)) = native_error(p, code) {
return Some(Explanation {
title: title.into(),
detail: detail.into(),
program,
raw: raw.clone(),
});
}
}
// Otherwise resolve the custom code against the program's IDL.
if let Some(code) = raw
.split("Custom(")
.nth(1)
.and_then(|s| s.split(')').next())
.and_then(|s| s.parse::<u64>().ok())
{
if let Some(e) = program
.as_ref()
.and_then(|p| idls.get(p))
.and_then(|i| idl::error_for_code(i, code))
{
return Some(Explanation {
title: e.name,
detail: e.msg,
program,
raw: raw.clone(),
});
}
}
// Fall back to a friendly reading of the common runtime errors.
let (title, detail) = if let Some(named) = runtime_error(raw) {
named
} else if raw.contains("AccountNotFound") {
("Account not found", "An account the transaction needs doesn't exist (an account with zero lamports is treated as deleted).")
} else if raw.contains("InsufficientFunds") {
(
"Insufficient funds",
"An account didn't have enough lamports for the transfer plus rent.",
)
} else if raw.contains("InvalidAddressLookupTableIndex") {
("Lookup table index invalid", "The transaction referenced an address lookup table entry that isn't active at this slot.")
} else if let Some(code) = raw
.split("Custom(")
.nth(1)
.and_then(|s| s.split(')').next())
.and_then(|s| s.parse::<u64>().ok())
{
let who = program
.as_deref()
.map(|p| format!("Program {p}"))
.unwrap_or_else(|| "The program".to_string());
let has_idl = program
.as_ref()
.map(|p| idls.contains_key(p))
.unwrap_or(false);
let detail = if has_idl {
format!(
"{who} returned custom error {code} (0x{code:x}), which its IDL does not define. Check the program's source for the code."
)
} else {
format!(
"{who} returned custom error {code} (0x{code:x}). It publishes no IDL, so the error has no name here; the meaning is in the program's source."
)
};
return Some(Explanation {
title: format!("Custom error {code}"),
detail,
program,
raw: raw.clone(),
});
} else {
(
"Transaction failed",
"The program returned an error. See the logs below for the failing instruction.",
)
};
Some(Explanation {
title: title.into(),
detail: detail.into(),
program,
raw: raw.clone(),
})
}
/// Plain-language readings of the runtime's own `InstructionError` /
/// `TransactionError` variants, matched on the formatted error string.
fn runtime_error(raw: &str) -> Option<(&'static str, &'static str)> {
const TABLE: &[(&str, &str, &str)] = &[
("ProgramFailedToComplete", "Program failed to complete", "The program aborted: a panic, an out-of-bounds access, or an exceeded compute budget. Check the last log lines of the failing step."),
("ComputationalBudgetExceeded", "Compute budget exceeded", "The transaction used more compute units than it requested. Raise the compute unit limit."),
("InvalidAccountData", "Invalid account data", "An account's data was not what the program expected: wrong layout, uninitialized, or owned by a different program."),
("AccountDataTooSmall", "Account data too small", "An account is smaller than the program requires."),
("MissingRequiredSignature", "Missing required signature", "An account that must sign did not."),
("IncorrectProgramId", "Incorrect program id", "An account is owned by a different program than expected."),
("InvalidArgument", "Invalid argument", "The program rejected an instruction argument."),
("InvalidInstructionData", "Invalid instruction data", "The instruction data did not decode."),
("PrivilegeEscalation", "Privilege escalation", "A CPI tried to use an account as a signer or writable when the caller could not."),
("ExternalAccountLamportSpend", "External account lamport spend", "A program debited lamports from an account it does not own."),
("ReadonlyLamportChange", "Read-only lamport change", "A program changed the balance of an account passed as read-only."),
("ReadonlyDataModified", "Read-only data modified", "A program wrote to an account passed as read-only."),
("ExecutableDataModified", "Executable data modified", "A program tried to write to an executable account."),
("AccountBorrowFailed", "Account borrow failed", "The same account was borrowed mutably twice in one instruction."),
("UnbalancedInstruction", "Unbalanced instruction", "Lamports were created or destroyed: the sums before and after differ."),
("MaxSeedLengthExceeded", "Max seed length exceeded", "A PDA seed is longer than 32 bytes."),
("InvalidSeeds", "Invalid seeds", "The seeds do not derive the given program address."),
("InvalidRealloc", "Invalid realloc", "The account resize was rejected."),
("AccountAlreadyInitialized", "Account already initialized", "The account was already initialized."),
("UninitializedAccount", "Uninitialized account", "The account has not been initialized."),
("NotEnoughAccountKeys", "Not enough account keys", "The instruction was given fewer accounts than it needs."),
("InsufficientFundsForRent", "Insufficient funds for rent", "An account would be left below the rent-exempt minimum."),
("InsufficientFundsForFee", "Insufficient funds for fee", "The fee payer cannot cover the transaction fee."),
("BlockhashNotFound", "Blockhash not found", "The transaction's blockhash is not recent."),
("AlreadyProcessed", "Already processed", "This exact transaction was already executed."),
("TooManyAccountLocks", "Too many account locks", "The transaction references more accounts than allowed."),
("MaxLoadedAccountsDataSizeExceeded", "Loaded accounts too large", "The accounts loaded exceed the requested data size limit."),
("InvalidAddressLookupTableIndex", "Lookup table index invalid", "The transaction referenced an address lookup table entry that isn't active at this slot."),
("AccountNotFound", "Account not found", "An account the transaction needs doesn't exist (an account with zero lamports is treated as deleted)."),
];
TABLE
.iter()
.find(|(needle, _, _)| raw.contains(needle))
.map(|(_, t, d)| (*t, *d))
}
/// Error names for the native programs that have no IDL (System, SPL Token,
/// Token-2022, Associated Token). Codes follow `SystemError` / `TokenError`.
fn native_error(program: &str, code: u64) -> Option<(&'static str, &'static str)> {
const SYSTEM: &str = "11111111111111111111111111111111";
const TOKEN: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const TOKEN_2022: &str = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
const ATA: &str = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
Some(match (program, code) {
(SYSTEM, 0) => (
"Account already in use",
"The account to create already exists.",
),
(SYSTEM, 1) => (
"Insufficient funds",
"The transfer would leave the source account with a negative balance.",
),
(SYSTEM, 2) => (
"Invalid program id",
"The account cannot be assigned to that program.",
),
(SYSTEM, 3) => (
"Invalid account data length",
"The requested allocation size is not allowed.",
),
(SYSTEM, 4) => (
"Max seed length exceeded",
"A seed for a derived address is too long.",
),
(SYSTEM, 5) => (
"Address with seed mismatch",
"The address does not derive from the given base and seed.",
),
(SYSTEM, 6) => (
"Nonce has no recent blockhashes",
"The durable nonce could not be advanced.",
),
(SYSTEM, 7) => (
"Nonce blockhash not expired",
"The stored nonce is still valid, so it cannot be advanced yet.",
),
(SYSTEM, 8) => (
"Unexpected nonce value",
"The transaction's blockhash does not match the nonce account.",
),
(TOKEN | TOKEN_2022, 0) => (
"Not rent exempt",
"The account lacks the lamports to be rent-exempt.",
),
(TOKEN | TOKEN_2022, 1) => (
"Insufficient funds",
"The token account holds fewer tokens than the instruction moves.",
),
(TOKEN | TOKEN_2022, 2) => ("Invalid mint", "The mint account is not valid."),
(TOKEN | TOKEN_2022, 3) => (
"Mint mismatch",
"The token account belongs to a different mint.",
),
(TOKEN | TOKEN_2022, 4) => (
"Owner mismatch",
"The signer is not the token account's owner or delegate.",
),
(TOKEN | TOKEN_2022, 5) => ("Fixed supply", "The mint has no mint authority."),
(TOKEN | TOKEN_2022, 6) => ("Already in use", "The account is already initialized."),
(TOKEN | TOKEN_2022, 7) => (
"Invalid number of provided signers",
"A multisig received the wrong number of signers.",
),
(TOKEN | TOKEN_2022, 8) => (
"Invalid number of required signers",
"The multisig threshold is out of range.",
),
(TOKEN | TOKEN_2022, 9) => (
"Uninitialized state",
"The account has not been initialized.",
),
(TOKEN | TOKEN_2022, 10) => (
"Native not supported",
"This instruction does not apply to a native (wrapped SOL) account.",
),
(TOKEN | TOKEN_2022, 11) => (
"Non-native has balance",
"A non-native account cannot be closed while it holds tokens.",
),
(TOKEN | TOKEN_2022, 12) => (
"Invalid instruction",
"The instruction data did not decode.",
),
(TOKEN | TOKEN_2022, 13) => (
"Invalid state",
"The account is in a state that does not allow this operation.",
),
(TOKEN | TOKEN_2022, 14) => ("Overflow", "An arithmetic operation overflowed."),
(TOKEN | TOKEN_2022, 15) => (
"Authority type not supported",
"The mint or account has no such authority.",
),
(TOKEN | TOKEN_2022, 16) => ("Mint cannot freeze", "The mint has no freeze authority."),
(TOKEN | TOKEN_2022, 17) => ("Account frozen", "The token account is frozen."),
(TOKEN | TOKEN_2022, 18) => (
"Mint decimals mismatch",
"The decimals passed do not match the mint.",
),
(TOKEN | TOKEN_2022, 19) => (
"Non-native not supported",
"This instruction only applies to native (wrapped SOL) accounts.",
),
(ATA, 0) => (
"Invalid owner",
"The associated token account's owner does not match.",
),
_ => return None,
})
}
/// Decode raw before/after bytes into named field changes, using built-in
/// layouts first and the preloaded IDLs second.
fn decode_diffs(
raw: Vec<crate::replay::RawAccountDiff>,
idls: &HashMap<String, serde_json::Value>,
) -> Vec<AccountDiff> {
raw.into_iter()
.map(|d| {
let idl = idls.get(&d.owner);
let decode_side = |bytes: &[u8]| -> Option<decode::DecodedAccount> {
decode::decode_bytes(&d.owner, bytes)
.or_else(|| idl.and_then(|i| idl::decode_with_idl(i, bytes)))
};
let (before, after) = (decode_side(&d.data_before), decode_side(&d.data_after));
let mut fields = Vec::new();
if let (Some(b), Some(a)) = (&before, &after) {
for (fb, fa) in b.fields.iter().zip(a.fields.iter()) {
if fb.value != fa.value {
fields.push(FieldDiff {
name: fa.name.clone(),
ty: fa.ty.clone(),
before: fb.value.clone(),
after: fa.value.clone(),
});
}
}
}
let raw_data_changed = d.data_before != d.data_after && fields.is_empty();
AccountDiff {
address: d.address,
owner: d.owner,
lamports_before: d.lamports_before,
lamports_after: d.lamports_after,
fields,
raw_data_changed,
}
})
.collect()
}
#[cfg(test)]
mod wait_tests {
use super::*;
use serde_json::json;
#[test]
fn confirmed_success_is_landed() {
let status = json!({
"confirmationStatus": "confirmed",
"err": null
});
assert!(status_is_confirmed(&status));
}
#[test]
fn fidelity_labels_are_honest() {
assert_eq!(Fidelity::Current.label(), "current");
assert_eq!(
Fidelity::Reconstructed { slot: 442384762 }.label(),
"reconstructed@442384762"
);
assert_eq!(Fidelity::Exact { slot: 100 }.label(), "exact@100");
}
#[test]
fn patch_comparison_reports_what_changed() {
let mk = |success: bool, err: Option<&str>, cu: u64| ReplayResult {
success,
error: err.map(String::from),
error_name: None,
logs: Vec::new(),
compute_units: cu,
};
let fixed = PatchComparison {
program: "P".to_string(),
before: mk(false, Some("Custom(6001)"), 100),
after: mk(true, None, 120),
};
assert!(fixed.success_changed());
assert!(fixed.changed());
assert_eq!(fixed.compute_delta(), 20);
assert!(
fixed.summary().contains("revert → success"),
"{}",
fixed.summary()
);
let unchanged = PatchComparison {
program: "P".to_string(),
before: mk(true, None, 100),
after: mk(true, None, 100),
};
assert!(!unchanged.changed());
assert!(unchanged.summary().contains("no observable change"));
}
#[test]
fn certificate_summary_discloses_drift_and_verifiability() {
let drifted = FidelityCertificate {
fidelity: Fidelity::Reconstructed { slot: 442384762 },
clock: "slot 442384762".to_string(),
accounts: Vec::new(),
drifted: vec!["AccA".to_string(), "AccB".to_string()],
verifiable: true,
};
let s = drifted.summary();
assert!(s.contains("reconstructed@442384762"), "{s}");
assert!(s.contains("2 may have drifted"), "{s}");
assert!(s.contains("verifiable against mainnet"), "{s}");
let clean = FidelityCertificate {
fidelity: Fidelity::Exact { slot: 5 },
clock: String::new(),
accounts: Vec::new(),
drifted: Vec::new(),
verifiable: false,
};
let s = clean.summary();
assert!(s.contains("none drifted"), "{s}");
assert!(s.contains("no recorded outcome"), "{s}");
}
#[test]
fn confirmed_program_failure_is_still_landed() {
let status = json!({
"confirmationStatus": "confirmed",
"err": {
"InstructionError": [0, {"Custom": 6001}]
}
});
assert!(status_is_confirmed(&status));
}
#[test]
fn finalized_is_landed() {
let status = json!({
"confirmationStatus": "finalized",
"err": null
});
assert!(status_is_confirmed(&status));
}
#[test]
fn processed_is_not_confirmed() {
let status = json!({
"confirmationStatus": "processed",
"err": null
});
assert!(!status_is_confirmed(&status));
}
#[test]
fn legacy_rooted_status_is_confirmed() {
let status = json!({
"confirmationStatus": null,
"confirmations": null,
"err": null
});
assert!(status_is_confirmed(&status));
}
}
#[cfg(test)]
mod preflight_input_tests {
use super::*;
use base64::Engine;
use solana_message::{Message, VersionedMessage};
use solana_signer::Signer;
use solana_transaction::versioned::VersionedTransaction;
fn b64(bytes: &[u8]) -> String {
base64::engine::general_purpose::STANDARD.encode(bytes)
}
fn transfer_message() -> VersionedMessage {
let from = solana_keypair::Keypair::new();
let to = solana_keypair::Keypair::new();
let ix =
solana_system_interface::instruction::transfer(&from.pubkey(), &to.pubkey(), 1_000_000);
VersionedMessage::Legacy(Message::new(&[ix], Some(&from.pubkey())))
}
#[test]
fn accepts_a_full_serialized_transaction() {
let message = transfer_message();
let tx = VersionedTransaction {
signatures: vec![Default::default(); 1],
message,
};
let parsed = parse_unsigned(&b64(&bincode::serialize(&tx).unwrap())).unwrap();
assert_eq!(parsed.message, tx.message);
}
#[test]
fn accepts_a_bare_wallet_message_and_wraps_it() {
// What a wallet's developer-mode "Base64 message" is: the serialized
// message alone, no signatures.
let message = transfer_message();
let parsed = parse_unsigned(&b64(&bincode::serialize(&message).unwrap())).unwrap();
assert_eq!(parsed.message, message);
assert_eq!(
parsed.signatures.len(),
message.header().num_required_signatures as usize
);
}
#[test]
fn rejects_garbage_with_a_helpful_error() {
let err = parse_unsigned(&b64(b"not a transaction at all")).unwrap_err();
assert!(err.to_string().contains("base64 message"), "got: {err}");
// Not base64 at all.
assert!(parse_unsigned("%%%not-base64%%%").is_err());
}
}