surfpool-core 1.5.0

Where you train before surfing Solana
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
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
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
use std::{str::FromStr, sync::Arc, time::Duration};

use base64::Engine;
use crossbeam_channel::{unbounded, unbounded as crossbeam_unbounded};
use ed25519_dalek::Signer as DalekSigner;
use jsonrpc_core::{
    Error, Result as JsonRpcResult,
    futures::future::{self, join_all},
};
use jsonrpc_core_client::transports::http;
use p256::ecdsa::{
    Signature as P256Signature, SigningKey, VerifyingKey, signature::Signer as P256Signer,
};
use solana_account::Account;
use solana_account_decoder::{UiAccountData, UiAccountEncoding, parse_account_data::ParsedAccount};
use solana_address_lookup_table_interface::{
    instruction as address_lookup_table_instruction,
    state::{AddressLookupTable, LookupTableMeta},
};
use solana_client::{
    nonblocking::rpc_client::RpcClient,
    rpc_config::{RpcSendTransactionConfig, RpcSimulateTransactionConfig},
    rpc_response::RpcLogsResponse,
};
use solana_clock::{Clock, Slot};
use solana_commitment_config::{CommitmentConfig, CommitmentLevel};
use solana_compute_budget_interface::ComputeBudgetInstruction;
use solana_ed25519_program::new_ed25519_instruction_with_signature;
use solana_epoch_info::EpochInfo;
use solana_epoch_schedule::EpochSchedule;
use solana_hash::Hash;
use solana_instruction::{AccountMeta, Instruction};
use solana_keypair::Keypair;
use solana_message::{
    AddressLookupTableAccount, Message, MessageHeader, VersionedMessage, legacy,
    v0::{self, MessageAddressTableLookup},
};
use solana_pubkey::Pubkey;
use solana_rpc_client_api::response::{Response as RpcResponse, SlotUpdate};
use solana_secp256k1_program::{
    eth_address_from_pubkey, new_secp256k1_instruction_with_signature,
    sign_message as sign_secp256k1_message,
};
use solana_secp256r1_program::new_secp256r1_instruction_with_signature;
use solana_signer::Signer;
use solana_system_interface::{
    instruction as system_instruction, instruction::transfer, program as system_program,
};
use solana_transaction::{Transaction, versioned::VersionedTransaction};
use spl_token_2022_interface::{
    extension::{
        BaseStateWithExtensions, ExtensionType, StateWithExtensions, pausable::PausableConfig,
    },
    pod::PodMint,
};
use surfpool_types::{
    AccountSnapshot, CheatcodeConfig, CheatcodeControlConfig, CheatcodeFilter,
    DEFAULT_SLOT_TIME_MS, Idl, RpcProfileDepth, RpcProfileResultConfig, SimnetCommand, SimnetEvent,
    SurfpoolConfig, UiAccountChange, UiAccountProfileState, UiKeyedProfileResult,
    types::{
        BlockProductionMode, RpcConfig, SimnetConfig, SubgraphConfig, TransactionStatusEvent,
        UuidOrSignature,
    },
};
use test_case::test_case;
use tokio::{sync::RwLock, task};
use uuid::Uuid;
pub const LAMPORTS_PER_SOL: u64 = 1_000_000_000;

use crate::{
    error::SurfpoolError,
    rpc::{
        RunloopContext,
        full::{FullClient, SurfpoolRpcSendTransactionConfig},
        minimal::MinimalClient,
        surfnet_cheatcodes::{SurfnetCheatcodes, SurfnetCheatcodesRpc},
    },
    runloops::start_local_surfnet_runloop,
    storage::tests::TestType,
    surfnet::{
        FINALIZATION_SLOT_THRESHOLD, PluginCommand, SignatureSubscriptionType,
        locker::SurfnetSvmLocker, svm::SurfnetSvm,
    },
    tests::helpers::get_free_port,
    types::{TimeTravelConfig, TransactionLoadedAddresses},
};

fn wait_for_ready_and_connected(simnet_events_rx: &crossbeam_channel::Receiver<SimnetEvent>) {
    let mut ready = false;
    let mut connected = false;
    loop {
        match simnet_events_rx.recv() {
            Ok(SimnetEvent::Ready(_)) => {
                println!("Simnet is ready");
                ready = true;
            }
            Ok(SimnetEvent::Connected(_)) => {
                println!("Simnet is connected");
                connected = true;
            }
            _ => (),
        }
        if ready && connected {
            break;
        }
    }
}

#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test]
async fn test_simnet_ready(test_type: TestType) {
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            block_production_mode: BlockProductionMode::Manual, // Prevent ticks
            ..SimnetConfig::default()
        }],
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);

    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            svm_locker,
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });

    loop {
        match simnet_events_rx.recv() {
            Ok(SimnetEvent::Ready(_))
            | Ok(SimnetEvent::Connected(_))
            | Ok(SimnetEvent::EpochInfoUpdate(_)) => break,
            e => panic!("Expected startup event: {e:?}"),
        }
    }
}

#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test]
async fn test_simnet_ticks(test_type: TestType) {
    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let (test_tx, test_rx) = unbounded();
    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);

    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            svm_locker,
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });

    let _ = hiro_system_kit::thread_named("ticks").spawn(move || {
        let mut ticks = 0;
        loop {
            match simnet_events_rx.recv() {
                Ok(SimnetEvent::SystemClockUpdated(_)) => ticks += 1,
                _ => (),
            }

            if ticks > 100 {
                let _ = test_tx.send(true);
            }
        }
    });

    match test_rx.recv_timeout(Duration::from_secs(20)) {
        Ok(_) => (),
        Err(e) => panic!("not enough ticks: {e:?}"),
    }
}

#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test]
async fn test_simnet_some_sol_transfers(test_type: TestType) {
    let n_addresses = 10;
    let airdrop_keypairs = (0..n_addresses).map(|_| Keypair::new()).collect::<Vec<_>>();
    let airdrop_addresses: Vec<Pubkey> = airdrop_keypairs.iter().map(|kp| kp.pubkey()).collect();
    let airdrop_token_amount = LAMPORTS_PER_SOL;
    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            airdrop_addresses: airdrop_addresses.clone(),
            airdrop_token_amount,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);

    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            svm_locker,
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });

    wait_for_ready_and_connected(&simnet_events_rx);

    let minimal_client =
        http::connect::<MinimalClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");
    let full_client =
        http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");

    let recent_blockhash = full_client
        .get_latest_blockhash(None)
        .await
        .map(|r| {
            Hash::from_str(r.value.blockhash.as_str()).expect("Failed to deserialize blockhash")
        })
        .expect("Failed to get blockhash");

    let balances = join_all(
        airdrop_addresses
            .iter()
            .map(|pk| minimal_client.get_balance(pk.to_string(), None)),
    )
    .await
    .into_iter()
    .collect::<Result<Vec<_>, _>>()
    .expect("Failed to fetch balances");

    assert!(
        balances.iter().all(|b| b.value == airdrop_token_amount),
        "All addresses did not receive the airdrop"
    );

    let _transfers = join_all(airdrop_keypairs.iter().map(|kp| {
        let msg = Message::new_with_blockhash(
            &[system_instruction::transfer(
                &kp.pubkey(),
                &airdrop_addresses[0],
                airdrop_token_amount / 2,
            )],
            Some(&kp.pubkey()),
            &recent_blockhash,
        );

        let Ok(tx) = VersionedTransaction::try_new(
            VersionedMessage::Legacy(msg),
            &vec![kp.insecure_clone()],
        ) else {
            return Box::pin(future::err(Error::invalid_params("tx")));
        };

        let Ok(encoded) = bincode::serialize(&tx) else {
            return Box::pin(future::err(Error::invalid_params("encoded")));
        };
        let data = bs58::encode(encoded).into_string();

        Box::pin(future::ready(Ok(full_client.send_transaction(data, None))))
    }))
    .await
    .into_iter()
    .collect::<Result<Vec<_>, _>>()
    .expect("Transfers failed");

    // Wait for all transactions to be received
    let expected = airdrop_addresses.len();
    let _ = task::spawn_blocking(move || {
        let mut processed = 0;
        loop {
            match simnet_events_rx.recv() {
                Ok(SimnetEvent::TransactionProcessed(..)) => processed += 1,
                _ => (),
            }

            if processed == expected {
                break;
            }
        }
    })
    .await;

    let final_balances = join_all(
        airdrop_addresses
            .iter()
            .map(|pk| minimal_client.get_balance(pk.to_string(), None)),
    )
    .await
    .into_iter()
    .collect::<Result<Vec<_>, _>>()
    .expect("Failed to fetch final balances");

    assert!(
        final_balances.iter().enumerate().all(|(i, b)| {
            if i == 0 {
                b.value > airdrop_token_amount
            } else {
                b.value < airdrop_token_amount / 2
            }
        }), // TODO: compute fee
        "Some transfers failed"
    );
}

// This test is pretty minimal for lookup tables at this point.
// We are creating a v0 transaction with a lookup table that does exist on mainnet,
// and sending that tx to surfpool. We are verifying that the transaction is processed
// and that the lookup table and its entries are fetched from mainnet and added to the accounts in the SVM.
// However, we are not actually setting up a tx that will use the lookup table internally,
// we are kind of just trusting that LiteSVM will do its job here.
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_add_alt_entries_fetching(test_type: TestType) {
    let payer = Keypair::new();
    let pk = payer.pubkey();

    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();
    let airdrop_token_amount = LAMPORTS_PER_SOL;
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            airdrop_addresses: vec![pk], // just one
            airdrop_token_amount,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    println!("Initializing SVM, binding to port {}", bind_port);
    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = Arc::new(RwLock::new(surfnet_svm));

    let moved_svm_locker = svm_locker.clone();
    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            SurfnetSvmLocker(moved_svm_locker),
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });
    let svm_locker = SurfnetSvmLocker(svm_locker);

    wait_for_ready_and_connected(&simnet_events_rx);

    let full_client =
        http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");

    let recent_blockhash = full_client
        .get_latest_blockhash(None)
        .await
        .map(|r| {
            Hash::from_str(r.value.blockhash.as_str()).expect("Failed to deserialize blockhash")
        })
        .expect("Failed to get blockhash");

    let random_address = Pubkey::from_str_const("7zdYkYf7yD83j3TLXmkhxn6LjQP9y9bQ4pjfpquP8Hqw");

    let instruction = transfer(&pk, &random_address, 100);

    let alt_address = Pubkey::from_str_const("5KcPJehcpBLcPde2UhmY4dE9zCrv2r9AKFmW5CGtY1io"); // a mainnet lookup table

    let address_lookup_table_account = AddressLookupTableAccount {
        key: alt_address,
        addresses: vec![random_address],
    };

    let tx = VersionedTransaction::try_new(
        VersionedMessage::V0(
            v0::Message::try_compile(
                &payer.pubkey(),
                &[instruction],
                &[address_lookup_table_account],
                recent_blockhash,
            )
            .expect("Failed to compile message"),
        ),
        &[payer],
    )
    .expect("Failed to create transaction");

    let Ok(encoded) = bincode::serialize(&tx) else {
        panic!("Failed to serialize transaction");
    };
    let data = bs58::encode(encoded).into_string();

    // Wait for all transactions to be received
    let _ = match full_client.send_transaction(data, None).await {
        Ok(res) => println!("Send transaction result: {}", res),
        Err(err) => println!("Send transaction error result: {}", err),
    };

    let mut processed = 0;
    let expected = 1;
    let mut alt_updated = false;
    loop {
        match simnet_events_rx.recv() {
            Ok(SimnetEvent::TransactionProcessed(..)) => processed += 1,
            Ok(SimnetEvent::AccountUpdate(_, account)) => {
                if account == alt_address {
                    alt_updated = true;
                }
            }
            Ok(SimnetEvent::ClockUpdate(_)) => {
                // do nothing
            }
            Ok(SimnetEvent::SystemClockUpdated(_)) => {
                // do nothing - clock ticks from time travel or normal progression
            }
            other => println!("Unexpected event: {:?}", other),
        }

        if processed == expected && alt_updated {
            break;
        }
    }

    // get all the account keys + the address lookup tables + table_entries from the txn
    let alts = tx.message.address_table_lookups().clone().unwrap();
    let mut acc_keys = tx.message.static_account_keys().to_vec();
    let mut alt_pubkeys = alts.iter().map(|msg| msg.account_key).collect::<Vec<_>>();
    let mut table_entries = join_all(alts.iter().map(|msg| async {
        let mut loaded_addresses = TransactionLoadedAddresses::new();
        svm_locker
            .get_lookup_table_addresses(&None, msg, &mut loaded_addresses)
            .await?;
        Ok::<_, SurfpoolError>(
            loaded_addresses
                .all_loaded_addresses()
                .into_iter()
                .map(|p| *p)
                .collect::<Vec<Pubkey>>(),
        )
    }))
    .await
    .into_iter()
    .collect::<Result<Vec<Vec<Pubkey>>, SurfpoolError>>()
    .unwrap()
    .into_iter()
    .flatten()
    .collect();

    acc_keys.append(&mut alt_pubkeys);
    acc_keys.append(&mut table_entries);

    assert!(
        acc_keys.iter().all(|key| {
            svm_locker
                .get_account_local(key)
                .inner
                .map_account()
                .is_ok()
        }),
        "account not found"
    );
}

// This test is pretty minimal for lookup tables at this point.
// We are creating a v0 transaction with a lookup table that does exist on mainnet,
// and sending that tx to surfpool. We are verifying that the transaction is processed
// and that the lookup table and its entries are fetched from mainnet and added to the accounts in the SVM.
// However, we are not actually setting up a tx that will use the lookup table internally,
// we are kind of just trusting that LiteSVM will do its job here.
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_simulate_add_alt_entries_fetching(test_type: TestType) {
    let payer = Keypair::new();
    let pk = payer.pubkey();

    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();
    let airdrop_token_amount = LAMPORTS_PER_SOL;
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            airdrop_addresses: vec![pk], // just one
            airdrop_token_amount,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = Arc::new(RwLock::new(surfnet_svm));

    let moved_svm_locker = svm_locker.clone();
    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            SurfnetSvmLocker(moved_svm_locker),
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });
    let svm_locker = SurfnetSvmLocker(svm_locker);

    wait_for_ready_and_connected(&simnet_events_rx);

    let full_client =
        http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");

    let random_address = Pubkey::from_str_const("7zdYkYf7yD83j3TLXmkhxn6LjQP9y9bQ4pjfpquP8Hqw");

    let instruction = transfer(&pk, &random_address, 100);
    let recent_blockhash = svm_locker.with_svm_reader(|svm_reader| svm_reader.latest_blockhash());

    let alt_address = Pubkey::from_str_const("5KcPJehcpBLcPde2UhmY4dE9zCrv2r9AKFmW5CGtY1io"); // a mainnet lookup table

    let address_lookup_table_account = AddressLookupTableAccount {
        key: alt_address,
        addresses: vec![random_address],
    };

    let tx = VersionedTransaction::try_new(
        VersionedMessage::V0(
            v0::Message::try_compile(
                &payer.pubkey(),
                &[instruction],
                &[address_lookup_table_account],
                recent_blockhash,
            )
            .expect("Failed to compile message"),
        ),
        &[payer],
    )
    .expect("Failed to create transaction");

    let Ok(encoded) = bincode::serialize(&tx) else {
        panic!("Failed to serialize transaction");
    };
    let data = bs58::encode(encoded).into_string();

    let simulation_res = full_client
        .simulate_transaction(data.clone(), None)
        .await
        .unwrap();
    assert_eq!(
        simulation_res.value.err, None,
        "Unexpected simulation error"
    );
    assert!(
        simulation_res.value.loaded_accounts_data_size.is_some(),
        "Expected loaded_accounts_data_size to be present"
    );
    assert_eq!(
        simulation_res.value.loaded_accounts_data_size.unwrap(),
        140134,
        "Incorrect loaded_accounts_data_size value"
    );
    let simulation_res2 = full_client
        .simulate_transaction(
            data,
            Some(RpcSimulateTransactionConfig {
                sig_verify: false,
                replace_recent_blockhash: false,
                commitment: Some(CommitmentConfig::confirmed()),
                encoding: None,
                accounts: None,
                min_context_slot: None,
                inner_instructions: false,
            }),
        )
        .await
        .unwrap();
    assert_eq!(
        simulation_res2.value.err, None,
        "Unexpected simulation error"
    );
    assert!(
        simulation_res2.value.loaded_accounts_data_size.is_some(),
        "Expected loaded_accounts_data_size to be present"
    );
    assert!(
        simulation_res2.value.loaded_accounts_data_size.unwrap() > 0,
        "Expected loaded_accounts_data_size to be greater than 0"
    );
}

#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_simulate_transaction_no_signers(test_type: TestType) {
    let payer = Keypair::new();
    let pk = payer.pubkey();
    let lamports = LAMPORTS_PER_SOL;

    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();
    let airdrop_token_amount = LAMPORTS_PER_SOL;
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            airdrop_addresses: vec![pk], // just one
            airdrop_token_amount,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = Arc::new(RwLock::new(surfnet_svm));

    let moved_svm_locker = svm_locker.clone();
    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            SurfnetSvmLocker(moved_svm_locker),
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });
    let svm_locker = SurfnetSvmLocker(svm_locker);

    wait_for_ready_and_connected(&simnet_events_rx);

    let full_client =
        http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");
    let _ = full_client
        .request_airdrop(payer.pubkey().to_string(), 2 * lamports, None)
        .await;

    let recent_blockhash = svm_locker
        .get_latest_blockhash(&CommitmentConfig::confirmed())
        .unwrap();
    //build_legacy_transaction
    let mut msg = legacy::Message::new(
        &[system_instruction::transfer(&payer.pubkey(), &pk, lamports)],
        Some(&payer.pubkey()),
    );
    msg.recent_blockhash = recent_blockhash;
    let tx = Transaction::new_unsigned(msg);

    let simulation_res = full_client
        .simulate_transaction(
            bs58::encode(bincode::serialize(&tx).unwrap()).into_string(),
            Some(RpcSimulateTransactionConfig {
                sig_verify: false,
                replace_recent_blockhash: false,
                commitment: Some(CommitmentConfig::finalized()),
                encoding: None,
                accounts: None,
                min_context_slot: None,
                inner_instructions: false,
            }),
        )
        .await
        .unwrap();

    assert_eq!(
        simulation_res.value.err, None,
        "Unexpected simulation error"
    );
    assert!(
        simulation_res.value.loaded_accounts_data_size.is_some(),
        "Expected loaded_accounts_data_size to be present"
    );
    assert!(
        simulation_res.value.loaded_accounts_data_size.unwrap() > 0,
        "Expected loaded_accounts_data_size to be greater than 0"
    );
}

fn build_secp256k1_precompile_transaction(
    payer: &Keypair,
    recent_blockhash: Hash,
) -> VersionedTransaction {
    let secp256k1_secret_key =
        libsecp256k1::SecretKey::parse_slice(&[1; 32]).expect("valid secp256k1 private key");
    let secp256k1_public_key = libsecp256k1::PublicKey::from_secret_key(&secp256k1_secret_key);
    let eth_address = eth_address_from_pubkey(
        &secp256k1_public_key.serialize()[1..]
            .try_into()
            .expect("valid secp256k1 public key"),
    );
    let message = b"surfpool secp256k1 precompile check";
    let (signature, recovery_id) =
        sign_secp256k1_message(&secp256k1_secret_key.serialize(), message)
            .expect("failed to sign secp256k1 message");
    let secp256k1_ix =
        new_secp256k1_instruction_with_signature(message, &signature, recovery_id, &eth_address);
    let tx_message =
        Message::new_with_blockhash(&[secp256k1_ix], Some(&payer.pubkey()), &recent_blockhash);

    VersionedTransaction::try_new(VersionedMessage::Legacy(tx_message), &[payer])
        .expect("Failed to create secp256k1 transaction")
}

fn build_secp256r1_precompile_transaction(
    payer: &Keypair,
    recent_blockhash: Hash,
) -> VersionedTransaction {
    let message = b"surfpool secp256r1 precompile check";
    let signing_key =
        SigningKey::from_bytes(&[1u8; 32].into()).expect("valid secp256r1 private key");
    let signature: P256Signature = signing_key.sign(message);
    let signature = signature.normalize_s().unwrap_or(signature);
    let signature: [u8; 64] = signature.to_bytes().into();
    let public_key: [u8; 33] = VerifyingKey::from(&signing_key)
        .to_encoded_point(true)
        .as_bytes()
        .try_into()
        .expect("valid compressed secp256r1 public key");
    let secp256r1_ix = new_secp256r1_instruction_with_signature(message, &signature, &public_key);
    let tx_message =
        Message::new_with_blockhash(&[secp256r1_ix], Some(&payer.pubkey()), &recent_blockhash);

    VersionedTransaction::try_new(VersionedMessage::Legacy(tx_message), &[payer])
        .expect("Failed to create secp256r1 transaction")
}

async fn assert_precompile_transaction_succeeds<F>(
    test_type: TestType,
    precompile_name: &str,
    build_tx: F,
) where
    F: FnOnce(&Keypair, Hash) -> VersionedTransaction,
{
    let payer = Keypair::new();
    let (mut svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    svm_instance
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();
    let recent_blockhash = svm_instance.latest_blockhash();
    let tx = build_tx(&payer, recent_blockhash);
    let svm_locker = SurfnetSvmLocker::new(svm_instance);
    let simulation_res = svm_locker.simulate_transaction(tx.clone(), true);

    if let Err(err) = simulation_res {
        panic!(
            "Expected {precompile_name} transaction simulation to succeed, got {:?}",
            err.err
        );
    }

    let (status_tx, status_rx) = unbounded();
    let _ = svm_locker
        .process_transaction(&None, tx, status_tx, true, true)
        .await
        .unwrap();

    match status_rx.recv() {
        Ok(TransactionStatusEvent::Success(_)) => {}
        Ok(TransactionStatusEvent::SimulationFailure((error, _))) => {
            panic!("{precompile_name} transaction simulation failed: {error:?}");
        }
        Ok(TransactionStatusEvent::ExecutionFailure((error, _))) => {
            panic!("{precompile_name} transaction execution failed: {error:?}");
        }
        Ok(TransactionStatusEvent::VerificationFailure(error)) => {
            panic!("{precompile_name} transaction verification failed: {error}");
        }
        Err(e) => {
            panic!("Failed to receive {precompile_name} transaction status: {e:?}");
        }
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn test_load_snapshot_program_is_invokable() {
    let snapshot: std::collections::BTreeMap<String, Option<AccountSnapshot>> =
        serde_json::from_str(include_str!("assets/program_snapshot.json"))
            .expect("program snapshot fixture should deserialize");
    let program_id = Pubkey::from_str_const("11157t3sqMV725NVRLrVQbAu98Jjfk1uCKehJnXXQs");
    let programdata_address =
        Pubkey::from_str_const("4rDReLryR2HcKBK5DrRzuf7N8g8BFTyEeoEpWgs17DXb");
    let payer = Keypair::new();

    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            airdrop_addresses: vec![payer.pubkey()],
            airdrop_token_amount: LAMPORTS_PER_SOL,
            block_production_mode: BlockProductionMode::Manual,
            offline_mode: true,
            snapshot,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..RpcConfig::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = TestType::no_db().initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();
    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);
    let runloop_locker = svm_locker.clone();
    let _handle = hiro_system_kit::thread_named("test_load_snapshot_program_is_invokable")
        .spawn(move || {
            let future = start_local_surfnet_runloop(
                runloop_locker,
                config,
                simnet_commands_tx,
                simnet_commands_rx,
                geyser_events_rx,
            );
            if let Err(e) = hiro_system_kit::nestable_block_on(future) {
                panic!("{e:?}");
            }
        })
        .expect("failed to spawn surfnet runloop");

    loop {
        match simnet_events_rx.recv_timeout(Duration::from_secs(5)) {
            Ok(SimnetEvent::Ready(_)) => break,
            Ok(_) => {}
            Err(crossbeam_channel::RecvTimeoutError::Timeout) => {
                panic!("timed out waiting for surfnet runloop to become ready");
            }
            Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
                panic!("surfnet runloop exited before becoming ready");
            }
        }
    }

    let program_account = svm_locker
        .with_svm_reader(|svm| svm.get_account(&program_id))
        .unwrap()
        .expect("program account should be loaded from snapshot");
    assert!(
        program_account.executable,
        "snapshot program account should be executable"
    );
    assert!(
        svm_locker
            .with_svm_reader(|svm| svm.get_account(&programdata_address))
            .unwrap()
            .is_some(),
        "programdata account should be loaded from snapshot"
    );

    let full_client =
        http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");
    let recent_blockhash = full_client
        .get_latest_blockhash(None)
        .await
        .map(|r| {
            Hash::from_str(r.value.blockhash.as_str()).expect("Failed to deserialize blockhash")
        })
        .expect("Failed to get blockhash");
    let invoke_snapshot_program = Instruction {
        program_id,
        accounts: vec![
            AccountMeta::new(payer.pubkey(), true),
            AccountMeta::new_readonly(system_program::id(), false),
        ],
        data: vec![0],
    };
    let tx = Transaction::new_signed_with_payer(
        &[invoke_snapshot_program],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );

    let encoded = bincode::serialize(&VersionedTransaction::from(tx))
        .map(bs58::encode)
        .map(|encoded| encoded.into_string())
        .expect("transaction should serialize");
    let result = full_client.send_transaction(encoded, None).await;
    assert!(
        result.is_ok(),
        "snapshot-loaded program should be invokable, got {result:?}"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_transaction_with_secp256k1_instruction(test_type: TestType) {
    assert_precompile_transaction_succeeds(
        test_type,
        "secp256k1",
        build_secp256k1_precompile_transaction,
    )
    .await;
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_transaction_with_secp256r1_instruction(test_type: TestType) {
    assert_precompile_transaction_succeeds(
        test_type,
        "secp256r1",
        build_secp256r1_precompile_transaction,
    )
    .await;
}

async fn assert_rpc_precompile_simulation_succeeds<F>(precompile_name: &str, build_tx: F)
where
    F: FnOnce(&Keypair, Hash) -> VersionedTransaction,
{
    use crate::{
        rpc::full::{Full, SurfpoolFullRpc},
        tests::helpers::TestSetup,
    };

    let payer = Keypair::new();
    let setup = TestSetup::new(SurfpoolFullRpc);
    setup
        .rpc
        .request_airdrop(
            Some(setup.context.clone()),
            payer.pubkey().to_string(),
            LAMPORTS_PER_SOL,
            None,
        )
        .expect("failed to airdrop test payer");
    let recent_blockhash = setup
        .context
        .svm_locker
        .with_svm_reader(|svm_reader| svm_reader.latest_blockhash());
    let tx = build_tx(&payer, recent_blockhash);
    let simulation_res = setup
        .rpc
        .simulate_transaction(
            Some(setup.context),
            bs58::encode(bincode::serialize(&tx).expect("failed to serialize transaction"))
                .into_string(),
            Some(RpcSimulateTransactionConfig {
                sig_verify: true,
                replace_recent_blockhash: false,
                commitment: Some(CommitmentConfig::confirmed()),
                encoding: None,
                accounts: None,
                min_context_slot: None,
                inner_instructions: false,
            }),
        )
        .await
        .expect("simulateTransaction RPC failed");

    assert_eq!(
        simulation_res.value.err, None,
        "{precompile_name} simulateTransaction returned an unexpected error"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn test_rpc_simulate_transaction_with_secp256k1_instruction() {
    assert_rpc_precompile_simulation_succeeds("secp256k1", build_secp256k1_precompile_transaction)
        .await;
}

#[tokio::test(flavor = "multi_thread")]
async fn test_rpc_simulate_transaction_with_secp256r1_instruction() {
    assert_rpc_precompile_simulation_succeeds("secp256r1", build_secp256r1_precompile_transaction)
        .await;
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_transaction_with_ed25519_instruction(test_type: TestType) {
    let payer = Keypair::new();
    let (mut svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    svm_instance
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();
    let recent_blockhash = svm_instance.latest_blockhash();

    // Issue #587 previously failed here with:
    // "Transaction simulation failed: Error processing Instruction 2: Unsupported program id".
    let tx = {
        let payer_dalek =
            ed25519_dalek::Keypair::from_bytes(&payer.to_bytes()).expect("invalid dalek keypair");
        let message = b"surfpool ed25519 precompile integration test";
        let signature = payer_dalek.sign(message);
        let ed25519_ix = new_ed25519_instruction_with_signature(
            message,
            &signature.to_bytes(),
            payer.pubkey().as_array(),
        );
        let compute_budget_ixs = [
            ComputeBudgetInstruction::set_compute_unit_limit(100_000),
            ComputeBudgetInstruction::set_compute_unit_price(1),
        ];
        let tx_message = Message::new_with_blockhash(
            &[
                compute_budget_ixs[0].clone(),
                compute_budget_ixs[1].clone(),
                ed25519_ix,
            ],
            Some(&payer.pubkey()),
            &recent_blockhash,
        );

        VersionedTransaction::try_new(VersionedMessage::Legacy(tx_message), &[payer])
            .expect("Failed to create ed25519 transaction")
    };
    let svm_locker = SurfnetSvmLocker::new(svm_instance);
    let simulation_res = svm_locker.simulate_transaction(tx.clone(), true);

    assert!(
        simulation_res.is_ok(),
        "Expected ed25519 transaction simulation to succeed"
    );

    let (status_tx, status_rx) = unbounded();
    let _ = svm_locker
        .process_transaction(&None, tx, status_tx, true, true)
        .await
        .unwrap();

    // Wait for transaction processing
    match status_rx.recv() {
        Ok(TransactionStatusEvent::Success(_)) => {
            println!("Transaction processed successfully");
        }
        Ok(TransactionStatusEvent::SimulationFailure((error, _))) => {
            panic!("Transaction simulation failed: {:?}", error);
        }
        Ok(TransactionStatusEvent::ExecutionFailure((error, _))) => {
            panic!("Transaction execution failed: {:?}", error);
        }
        Ok(TransactionStatusEvent::VerificationFailure(error)) => {
            panic!("Transaction verification failed: {}", error);
        }
        Err(e) => {
            panic!("Failed to receive transaction status: {:?}", e);
        }
    }
}

#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_surfnet_estimate_compute_units(test_type: TestType) {
    let (mut svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let rpc_server = crate::rpc::surfnet_cheatcodes::SurfnetCheatcodesRpc::empty();

    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = 1_000_000;

    svm_instance
        .airdrop(&payer.pubkey(), lamports_to_send * 2)
        .unwrap()
        .unwrap();

    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_instance.latest_blockhash();
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message.clone()), &[&payer])
        .unwrap();

    let tx_bytes = bincode::serialize(&tx).unwrap();
    let tx_b64 = base64::engine::general_purpose::STANDARD.encode(&tx_bytes);

    // Manually construct RunloopContext
    let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance);
    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker_for_context.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Test with None tag
    let response_no_tag_initial: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
        .profile_transaction(Some(runloop_context.clone()), tx_b64.clone(), None, None)
        .await;

    assert!(
        response_no_tag_initial.is_ok(),
        "RPC call with None tag failed: {:?}",
        response_no_tag_initial.err()
    );
    let rpc_response_value_no_tag = response_no_tag_initial.unwrap().value;

    assert!(
        rpc_response_value_no_tag
            .transaction_profile
            .error_message
            .is_none(),
        "CU estimation with None tag failed"
    );

    assert!(
        rpc_response_value_no_tag
            .transaction_profile
            .compute_units_consumed
            > 0,
        "Invalid compute units consumed for None tag"
    );

    assert!(
        rpc_response_value_no_tag
            .transaction_profile
            .log_messages
            .is_some(),
        "Log messages should be present for None tag"
    );

    // Test 1: Estimate with a tag and retrieve
    let tag1 = "test_tag_1".to_string();
    println!("\nTesting with tag: {}", tag1);
    let response_tagged_1: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
        .profile_transaction(
            Some(runloop_context.clone()),
            tx_b64.clone(),
            Some(tag1.clone()),
            None,
        )
        .await;
    assert!(
        response_tagged_1.is_ok(),
        "RPC call with tag1 failed: {:?}",
        response_tagged_1.err()
    );
    let rpc_response_tagged_1_value = response_tagged_1.unwrap().value;
    assert!(
        rpc_response_tagged_1_value
            .transaction_profile
            .error_message
            .is_none(),
        "CU estimation with tag1 failed"
    );

    println!("Retrieving profile results for tag: {}", tag1);
    let results_vec_tag1 = rpc_server
        .get_profile_results_by_tag(Some(runloop_context.clone()), tag1.clone(), None)
        .unwrap()
        .value
        .unwrap_or_default();
    assert_eq!(results_vec_tag1.len(), 1, "Expected 1 result for tag1");

    assert_eq!(
        results_vec_tag1[0]
            .transaction_profile
            .compute_units_consumed,
        rpc_response_tagged_1_value
            .transaction_profile
            .compute_units_consumed
    );
    assert_eq!(
        results_vec_tag1[0]
            .transaction_profile
            .error_message
            .is_none(),
        rpc_response_tagged_1_value
            .transaction_profile
            .error_message
            .is_none()
    );

    // Test 2: Retrieve with a non-existent tag
    let tag_non_existent = "non_existent_tag".to_string();
    println!(
        "\nTesting retrieval with non-existent tag: {}",
        tag_non_existent
    );
    let results_non_existent_vec = rpc_server
        .get_profile_results_by_tag(
            Some(runloop_context.clone()),
            tag_non_existent.clone(),
            None,
        )
        .unwrap()
        .value
        .unwrap_or_default();

    assert!(
        results_non_existent_vec.is_empty(),
        "Expected empty vec for non-existent tag"
    );

    // Test 3: Estimate multiple times with the same tag
    let tag2 = "test_tag_2".to_string();
    println!("\nTesting multiple estimations with tag: {}", tag2);
    let response_tagged_2a: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
        .profile_transaction(
            Some(runloop_context.clone()),
            tx_b64.clone(),
            Some(tag2.clone()),
            None,
        )
        .await;
    assert!(response_tagged_2a.is_ok(), "First call with tag2 failed");
    let cu_2a_profile_result = response_tagged_2a.unwrap().value;
    println!(
        "CU estimation 1 (tag: {}): consumed = {}, success = {}",
        tag2,
        cu_2a_profile_result
            .transaction_profile
            .compute_units_consumed,
        cu_2a_profile_result
            .transaction_profile
            .error_message
            .is_none()
    );

    let response_tagged_2b: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
        .profile_transaction(
            Some(runloop_context.clone()),
            tx_b64.clone(),
            Some(tag2.clone()),
            None,
        )
        .await;
    assert!(response_tagged_2b.is_ok(), "Second call with tag2 failed");
    let cu_2b_profile_result = response_tagged_2b.unwrap().value;

    println!("Retrieving profile results for tag: {}", tag2);
    let results_response_tag2 =
        rpc_server.get_profile_results_by_tag(Some(runloop_context.clone()), tag2.clone(), None);

    assert!(
        results_response_tag2.is_ok(),
        "get_profile_results for tag2 failed"
    );
    let results_vec_tag2 = results_response_tag2.unwrap().value.unwrap_or_default();
    assert_eq!(results_vec_tag2.len(), 2, "Expected 2 results for tag2");

    assert_eq!(
        results_vec_tag2[0]
            .transaction_profile
            .compute_units_consumed,
        cu_2a_profile_result
            .transaction_profile
            .compute_units_consumed
    );

    assert_eq!(
        results_vec_tag2[1]
            .transaction_profile
            .compute_units_consumed,
        cu_2b_profile_result
            .transaction_profile
            .compute_units_consumed
    );

    // Test 4: Estimate with another None tag, ensure it doesn't affect tagged results for tag1
    println!(
        "\nTesting None tag again to ensure no interference with tag: {}",
        tag1
    );
    let response_no_tag_again: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
        .profile_transaction(Some(runloop_context.clone()), tx_b64.clone(), None, None)
        .await;
    assert!(
        response_no_tag_again.is_ok(),
        "RPC call with None tag (again) failed"
    );
    let _rpc_response_no_tag_again_value = response_no_tag_again.unwrap().value;

    println!("Retrieving profile results for tag: {} again", tag1);
    let results_response_tag1_again =
        rpc_server.get_profile_results_by_tag(Some(runloop_context), tag1.clone(), None);
    assert!(
        results_response_tag1_again.is_ok(),
        "get_profile_results for tag1 (again) failed"
    );
    let results_vec_tag1_again = results_response_tag1_again
        .unwrap()
        .value
        .unwrap_or_default();
    assert_eq!(
        results_vec_tag1_again.len(),
        1,
        "Expected 1 result for tag1 after another None tag call, was {}",
        results_vec_tag1_again.len()
    );
    assert_eq!(
        results_vec_tag1_again[0]
            .transaction_profile
            .compute_units_consumed,
        rpc_response_tagged_1_value
            .transaction_profile
            .compute_units_consumed
    );

    // Test send_transaction with cu_analysis_enabled = true
    // Create a new SVM instance
    let (mut svm_for_send, simnet_rx_for_send, _geyser_rx_for_send) = test_type.initialize_svm();
    svm_for_send
        .airdrop(&payer.pubkey(), lamports_to_send * 2)
        .unwrap()
        .unwrap();

    let latest_blockhash_for_send = svm_for_send.latest_blockhash();
    let message_for_send = Message::new_with_blockhash(
        &[transfer(&payer.pubkey(), &recipient, lamports_to_send)],
        Some(&payer.pubkey()),
        &latest_blockhash_for_send,
    );
    let tx_for_send =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message_for_send), &[&payer])
            .unwrap();

    let _send_result = svm_for_send.send_transaction(tx_for_send, true, true);

    let mut found_cu_event = false;
    for _ in 0..10 {
        if let Ok(event) = simnet_rx_for_send.try_recv() {
            if let surfpool_types::SimnetEvent::InfoLog(_, msg) = event {
                if msg.starts_with("CU Estimation for tx") {
                    println!("Found CU estimation event: {}", msg);
                    found_cu_event = true;
                    break;
                }
            }
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
    }
    assert!(found_cu_event, "Did not find CU estimation SimnetEvent");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_enable_and_disable_cheatcodes(test_type: TestType) {
    let valid_cheatcode_method = "surfnet_getActiveIdl".to_string();
    let enable_cheatcode_method = "surfnet_enableCheatcode".to_string();
    let disable_cheatcode_method = "surfnet_disableCheatcode".to_string();
    let invalid_cheatcode_method = "surfnet_invalidCheatcode".to_string();
    let available_methods = vec![
        valid_cheatcode_method.clone(),
        enable_cheatcode_method.clone(),
        disable_cheatcode_method.clone(),
    ];
    let rpc_server = SurfnetCheatcodesRpc {
        registered_methods: Arc::new(std::sync::RwLock::new(available_methods.clone())),
    };
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance);
    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker_for_context.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Test disable works properly
    let disable_cheatcode_pass_result = rpc_server.disable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::List(vec![valid_cheatcode_method.clone()]),
        None,
    );

    assert!(
        disable_cheatcode_pass_result.is_ok(),
        "Expected surfnet_disableCheatcode to pass"
    );

    assert!(
        runloop_context
            .cheatcode_config
            .lock()
            .unwrap()
            .is_cheatcode_disabled(&valid_cheatcode_method),
        "Expected cheatcode to be disabled"
    );

    let disable_enable_cheatcode_lockout_false_fails = rpc_server.disable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::List(vec![enable_cheatcode_method.clone()]),
        None,
    );

    let expected_error: jsonrpc_core::Result<()> = Err(SurfpoolError::disable_cheatcode(
        "Cannot disable surfnet_enableCheatcode or surfnet_disableCheatcode rpc method when lockout is not enabled".to_string(),
    )
    .into());

    assert!(
        disable_enable_cheatcode_lockout_false_fails.is_err(),
        "Expected surfnet_disableCheatcode to fail when disabling surfnet_enableCheatcode with lockout == false"
    );
    assert_eq!(
        disable_enable_cheatcode_lockout_false_fails.err().unwrap(),
        expected_error.err().unwrap(),
        "Expected error did not match the resulting error"
    );

    // Test that surfnet_disableCheatcode cannot be disabled without lockout
    let disable_disable_cheatcode_lockout_false_fails = rpc_server.disable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::List(vec![disable_cheatcode_method.clone()]),
        None,
    );

    let expected_error_disable_self: jsonrpc_core::Result<()> = Err(SurfpoolError::disable_cheatcode(
        "Cannot disable surfnet_enableCheatcode or surfnet_disableCheatcode rpc method when lockout is not enabled".to_string(),
    )
    .into());

    assert!(
        disable_disable_cheatcode_lockout_false_fails.is_err(),
        "Expected surfnet_disableCheatcode to fail when disabling surfnet_disableCheatcode with lockout == false"
    );
    assert_eq!(
        disable_disable_cheatcode_lockout_false_fails.err().unwrap(),
        expected_error_disable_self.err().unwrap(),
        "Expected error did not match the resulting error"
    );

    let disable_cheatcode_fails_on_invalid_cheatcode = rpc_server.disable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::List(vec![invalid_cheatcode_method.clone()]),
        None,
    );

    let expected_error_disable_invalid_cheatcode: jsonrpc_core::Result<()> =
        Err(SurfpoolError::disable_cheatcode("Invalid cheatcode rpc method".to_string()).into());

    assert!(
        disable_cheatcode_fails_on_invalid_cheatcode.is_err(),
        "Expected surfnet_disableCheatcode to fail on providing invalid cheatcode method"
    );

    assert_eq!(
        expected_error_disable_invalid_cheatcode.err().unwrap(),
        disable_cheatcode_fails_on_invalid_cheatcode.err().unwrap(),
        "Resulting error does not match the expected error"
    );

    let disable_all_cheatcodes_fails_with_invalid_config = rpc_server.disable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::All("not_all".to_string()),
        None,
    );
    let expected_error_disable_all_with_invalid_config: jsonrpc_core::Result<()> =
        Err(SurfpoolError::disable_cheatcode(
            "Invalid option provided for disabling all cheatcodes. Try using 'all' or providing an array of specific cheatcodes".to_string(),
        )
        .into());

    assert!(
        disable_all_cheatcodes_fails_with_invalid_config.is_err(),
        "Expected surfnet_disableCheatcode to fail when config is wrong"
    );
    assert_eq!(
        disable_all_cheatcodes_fails_with_invalid_config
            .err()
            .unwrap(),
        expected_error_disable_all_with_invalid_config
            .err()
            .unwrap(),
        "Expected error did not match the resulting error"
    );

    let disabled_all_cheatcode_passes_result = rpc_server.disable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::All("all".to_string()),
        None,
    );

    assert!(
        disabled_all_cheatcode_passes_result.is_ok(),
        "Expected surfnet_disableCheatcode to pass with valid config"
    );

    assert_eq!(
        runloop_context.cheatcode_config.lock().unwrap().filter,
        CheatcodeConfig::filter_all_list(false, available_methods.clone()),
        "The disabled cheatcodes list doesn't match the expected one"
    );

    let disable_fails_if_cheatcode_already_disabled_result = rpc_server.disable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::List(vec![valid_cheatcode_method.clone()]),
        None,
    );

    let expected_error_if_cheatcode_already_disabled: jsonrpc_core::Result<()> =
        Err(SurfpoolError::disable_cheatcode("Cheatcode already disabled".to_string()).into());

    assert!(
        disable_fails_if_cheatcode_already_disabled_result.is_err(),
        "Expected surfnet_disableCheatcode to fail if cheatcode already disabled"
    );

    assert_eq!(
        disable_fails_if_cheatcode_already_disabled_result
            .err()
            .unwrap(),
        expected_error_if_cheatcode_already_disabled.err().unwrap(),
        "The expected error does not match the resulting error"
    );

    // test enable works properly
    let enable_cheatcode_works_properly_result = rpc_server.enable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::List(vec![valid_cheatcode_method.clone()]),
    );

    assert!(
        enable_cheatcode_works_properly_result.is_ok(),
        "expected surfnet_enableCheatcode to pass"
    );
    assert!(
        !runloop_context
            .cheatcode_config
            .lock()
            .unwrap()
            .is_cheatcode_disabled(&valid_cheatcode_method),
        "Expected the cheatcode to be enabled after surnet_enableCheatcode rpc method"
    );

    let enable_cheatcode_fails_on_invalid_cheatcode = rpc_server.enable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::List(vec![invalid_cheatcode_method]),
    );

    let expected_error_enable_invalid_cheatcode: jsonrpc_core::Result<()> =
        Err(SurfpoolError::enable_cheatcode("Invalid cheatcode rpc method".to_string()).into());

    assert!(
        enable_cheatcode_fails_on_invalid_cheatcode.is_err(),
        "Expected surfnet_disableCheatcode to fail on providing invalid cheatcode method"
    );

    assert_eq!(
        enable_cheatcode_fails_on_invalid_cheatcode.err().unwrap(),
        expected_error_enable_invalid_cheatcode.err().unwrap(),
        "Resulting error does not match the expected error"
    );

    let enable_all_cheatcodes_fails_with_invalid_config = rpc_server.enable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::All("not_all".to_string()),
    );
    let expected_error_enable_all_with_invalid_config: jsonrpc_core::Result<()> =
        Err(SurfpoolError::enable_cheatcode(
            "Invalid option provided for enabling all cheatcodes. Try using 'all' or providing an array of specific cheatcodes".to_string(),
        )
        .into());

    assert!(
        enable_all_cheatcodes_fails_with_invalid_config.is_err(),
        "Expected surfnet_disableCheatcode to fail when config is wrong"
    );
    assert_eq!(
        enable_all_cheatcodes_fails_with_invalid_config
            .err()
            .unwrap(),
        expected_error_enable_all_with_invalid_config.err().unwrap(),
        "Expected error did not match the resulting error"
    );

    let enable_all_cheatcodes_pass_result = rpc_server.enable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::All("all".to_string()),
    );

    assert!(
        enable_all_cheatcodes_pass_result.is_ok(),
        "Expected surnet_enableCheatcode with correct config to pass"
    );

    assert_eq!(
        runloop_context.cheatcode_config.lock().unwrap().filter,
        CheatcodeFilter::List(vec![]),
        "Expected all the cheatcodes to be enabled"
    );

    let disable_all_with_lockout_passes = rpc_server.disable_cheatcode(
        Some(runloop_context.clone()),
        CheatcodeFilter::All("all".to_string()),
        Some(CheatcodeControlConfig {
            lockout: Some(true),
        }),
    );

    assert!(
        disable_all_with_lockout_passes.is_ok(),
        "Expected surfnet_disableCheatcode with lockout == true to pass"
    );

    assert_eq!(
        runloop_context.cheatcode_config.lock().unwrap().filter,
        CheatcodeConfig::filter_all_list(true, vec![]),
        "Expected all the features to be disabled"
    );

    // assert that surfnet_enableCheatcode and surfnet_disableCheatcode both are disabled so that on_request Middleware sucessfully filters them
    for ref cheatcode in [enable_cheatcode_method, disable_cheatcode_method] {
        assert!(
            runloop_context
                .cheatcode_config
                .lock()
                .unwrap()
                .is_cheatcode_disabled(cheatcode),
            "Expected {} to be disabled",
            cheatcode
        );
    }
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_get_transaction_profile(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (mut svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();

    // Set up test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = 1_000_000;

    svm_instance
        .airdrop(&payer.pubkey(), lamports_to_send * 2)
        .unwrap()
        .unwrap();

    // Create a transaction to profile
    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_instance.latest_blockhash();
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message.clone()), &[&payer])
        .unwrap();

    let tx_bytes = bincode::serialize(&tx).unwrap();
    let tx_b64 = base64::engine::general_purpose::STANDARD.encode(&tx_bytes);

    // Manually construct RunloopContext
    let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance);
    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker_for_context.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Test 1: Profile a transaction with a tag and retrieve by UUID
    let tag = "test_get_transaction_profile_tag".to_string();
    println!("Testing transaction profiling with tag: {}", tag);

    let profile_response: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
        .profile_transaction(
            Some(runloop_context.clone()),
            tx_b64.clone(),
            Some(tag.clone()),
            None,
        )
        .await;

    assert!(
        profile_response.is_ok(),
        "Profile transaction failed: {:?}",
        profile_response.err()
    );

    let profile_result = profile_response.unwrap().value;
    assert!(
        profile_result.transaction_profile.error_message.is_none(),
        "Transaction profiling failed"
    );

    let UuidOrSignature::Uuid(uuid) = profile_result.key else {
        panic!(
            "Expected a UUID from the profile result, got: {:?}",
            profile_result.key
        );
    };
    println!("Generated UUID: {}", uuid);

    // Test 2: Retrieve profile by UUID
    println!("Testing retrieval by UUID: {}", uuid);
    let uuid_response: JsonRpcResult<RpcResponse<Option<UiKeyedProfileResult>>> = rpc_server
        .get_transaction_profile(
            Some(runloop_context.clone()),
            UuidOrSignature::Uuid(uuid),
            None,
        );

    assert!(
        uuid_response.is_ok(),
        "Get transaction profile by UUID failed: {:?}",
        uuid_response.err()
    );

    let retrieved_profile = uuid_response.unwrap().value;
    assert!(
        retrieved_profile.is_some(),
        "Profile should be found by UUID"
    );

    let retrieved = retrieved_profile.unwrap();
    assert_eq!(
        retrieved.transaction_profile.compute_units_consumed,
        profile_result.transaction_profile.compute_units_consumed,
        "Retrieved profile should match original profile"
    );
    assert_eq!(
        retrieved.transaction_profile.error_message.is_none(),
        profile_result.transaction_profile.error_message.is_none(),
        "Retrieved profile success should match original"
    );
    assert_eq!(
        retrieved.key,
        UuidOrSignature::Uuid(uuid),
        "Retrieved profile should have the same UUID"
    );

    // Test 3: Process the transaction to get a signature and retrieve by signature
    println!("Processing transaction to get signature");
    let (status_tx, status_rx) = crossbeam_unbounded();

    svm_locker_for_context
        .process_transaction(&None, tx.clone(), status_tx, false, true)
        .await
        .unwrap();

    // Wait for transaction processing
    match status_rx.recv() {
        Ok(TransactionStatusEvent::Success(_)) => {
            println!("Transaction processed successfully");
        }
        Ok(TransactionStatusEvent::SimulationFailure((error, _))) => {
            panic!("Transaction simulation failed: {:?}", error);
        }
        Ok(TransactionStatusEvent::ExecutionFailure((error, _))) => {
            panic!("Transaction execution failed: {:?}", error);
        }
        Ok(TransactionStatusEvent::VerificationFailure(error)) => {
            panic!("Transaction verification failed: {}", error);
        }
        Err(e) => {
            panic!("Failed to receive transaction status: {:?}", e);
        }
    }

    let signature = tx.signatures[0];
    println!("Transaction signature: {}", signature);

    // Test 4: Retrieve profile by signature
    println!("Testing retrieval by signature: {}", signature);
    let signature_response: JsonRpcResult<RpcResponse<Option<UiKeyedProfileResult>>> = rpc_server
        .get_transaction_profile(
            Some(runloop_context.clone()),
            UuidOrSignature::Signature(signature),
            None,
        );

    assert!(
        signature_response.is_ok(),
        "Get transaction profile by signature failed: {:?}",
        signature_response.err()
    );

    let retrieved_by_signature = signature_response.unwrap().value;
    assert!(
        retrieved_by_signature.is_some(),
        "Profile should be found by signature"
    );

    let retrieved_sig = retrieved_by_signature.unwrap();
    assert!(
        retrieved_sig.transaction_profile.error_message.is_none(),
        "Retrieved profile by signature should be successful"
    );
    assert!(
        retrieved_sig.transaction_profile.compute_units_consumed > 0,
        "Retrieved profile should have consumed compute units"
    );

    // Test 5: Test retrieval with non-existent UUID
    println!("Testing retrieval with non-existent UUID");
    let non_existent_uuid = uuid::Uuid::new_v4();
    let non_existent_uuid_response: JsonRpcResult<RpcResponse<Option<UiKeyedProfileResult>>> =
        rpc_server.get_transaction_profile(
            Some(runloop_context.clone()),
            UuidOrSignature::Uuid(non_existent_uuid),
            None,
        );

    assert!(
        non_existent_uuid_response.is_ok(),
        "Get transaction profile with non-existent UUID should not fail"
    );

    let non_existent_result = non_existent_uuid_response.unwrap().value;
    assert!(
        non_existent_result.is_none(),
        "Non-existent UUID should return None"
    );

    // Test 6: Test retrieval with non-existent signature
    println!("Testing retrieval with non-existent signature");
    let non_existent_signature = solana_signature::Signature::new_unique();
    let non_existent_sig_response: JsonRpcResult<RpcResponse<Option<UiKeyedProfileResult>>> =
        rpc_server.get_transaction_profile(
            Some(runloop_context.clone()),
            UuidOrSignature::Signature(non_existent_signature),
            None,
        );

    assert!(
        non_existent_sig_response.is_ok(),
        "Get transaction profile with non-existent signature should not fail"
    );

    let non_existent_sig_result = non_existent_sig_response.unwrap().value;
    assert!(
        non_existent_sig_result.is_none(),
        "Non-existent signature should return None"
    );
    println!("All get_transaction_profile tests passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_register_and_get_idl_without_slot(test_type: TestType) {
    let idl: Idl = serde_json::from_slice(include_bytes!("./assets/idl_v1.json")).unwrap();
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();

    let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance);
    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker_for_context.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Test 1: Register IDL without slot

    let register_response: JsonRpcResult<RpcResponse<()>> =
        rpc_server.register_idl(Some(runloop_context.clone()), idl.clone(), None);

    assert!(
        register_response.is_ok(),
        "Register IDL failed: {:?}",
        register_response.err()
    );

    // Test 2: Get IDL without slot

    let get_idl_response: JsonRpcResult<RpcResponse<Option<Idl>>> =
        rpc_server.get_idl(Some(runloop_context.clone()), idl.address.to_string(), None);

    assert!(
        get_idl_response.is_ok(),
        "Get IDL failed: {:?}",
        get_idl_response.err()
    );

    let retrieved_idl = get_idl_response.unwrap().value;
    assert!(retrieved_idl.is_some(), "IDL should be found");
    assert_eq!(
        retrieved_idl.unwrap(),
        idl,
        "Retrieved IDL should match registered IDL"
    );

    println!("All IDL registration and retrieval tests passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_register_and_get_idl_with_slot(test_type: TestType) {
    let idl: Idl = serde_json::from_slice(include_bytes!("./assets/idl_v1.json")).unwrap();
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();

    let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance);
    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker_for_context.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Test 1: Register IDL with slot

    let register_response: JsonRpcResult<RpcResponse<()>> = rpc_server.register_idl(
        Some(runloop_context.clone()),
        idl.clone(),
        Some(Slot::from(
            svm_locker_for_context.get_latest_absolute_slot(),
        )),
    );

    assert!(
        register_response.is_ok(),
        "Register IDL failed: {:?}",
        register_response.err()
    );

    // Test 2: Get IDL with slot

    let get_idl_response: JsonRpcResult<RpcResponse<Option<Idl>>> = rpc_server.get_idl(
        Some(runloop_context.clone()),
        idl.address.to_string(),
        Some(Slot::from(
            svm_locker_for_context.get_latest_absolute_slot(),
        )),
    );

    assert!(
        get_idl_response.is_ok(),
        "Get IDL failed: {:?}",
        get_idl_response.err()
    );

    let retrieved_idl = get_idl_response.unwrap().value;
    assert!(retrieved_idl.is_some(), "IDL should be found");
    assert_eq!(
        retrieved_idl.unwrap(),
        idl,
        "Retrieved IDL should match registered IDL"
    );

    println!("All IDL registration and retrieval tests passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_register_and_get_same_idl_with_different_slots(test_type: TestType) {
    let idl_v1: Idl = serde_json::from_slice(include_bytes!("./assets/idl_v1.json")).unwrap();
    let idl_v2: Idl = serde_json::from_slice(include_bytes!("./assets/idl_v2.json")).unwrap();
    let idl_v3: Idl = serde_json::from_slice(include_bytes!("./assets/idl_v3.json")).unwrap();
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();

    let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance);

    // Prepare slots for registering different IDLs
    let current_slot = svm_locker_for_context.get_latest_absolute_slot();
    let slot_1 = current_slot.saturating_add(10); // First IDL registration
    let slot_2 = current_slot.saturating_add(50); // Second IDL registration
    let slot_3 = current_slot.saturating_add(100); // Third IDL registration

    println!("Current slot: {}", current_slot);
    println!("Slot 1 (IDL v1): {}", slot_1);
    println!("Slot 2 (IDL v2): {}", slot_2);
    println!("Slot 3 (IDL v3): {}", slot_3);

    // Setup runloop context
    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker_for_context.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Step 1: Register IDL v1 at slot_1
    println!("  [1] Registering IDL v1 at slot: {}", slot_1);
    let register_response: JsonRpcResult<RpcResponse<()>> = rpc_server.register_idl(
        Some(runloop_context.clone()),
        idl_v1.clone(),
        Some(Slot::from(slot_1)),
    );

    assert!(
        register_response.is_ok(),
        "Register IDL v1 failed at slot {}: {:?}",
        slot_1,
        register_response.err()
    );

    // Step 2: Register IDL v2 at slot_2
    println!("  [2] Registering IDL v2 at slot: {}", slot_2);
    let register_response: JsonRpcResult<RpcResponse<()>> = rpc_server.register_idl(
        Some(runloop_context.clone()),
        idl_v2.clone(),
        Some(Slot::from(slot_2)),
    );

    assert!(
        register_response.is_ok(),
        "Register IDL v2 failed at slot {}: {:?}",
        slot_2,
        register_response.err()
    );

    // Step 3: Register IDL v3 at slot_3
    println!("  [3] Registering IDL v3 at slot: {}", slot_3);
    let register_response: JsonRpcResult<RpcResponse<()>> = rpc_server.register_idl(
        Some(runloop_context.clone()),
        idl_v3.clone(),
        Some(Slot::from(slot_3)),
    );

    assert!(
        register_response.is_ok(),
        "Register IDL v3 failed at slot {}: {:?}",
        slot_3,
        register_response.err()
    );

    // Step 4: Test retrieval at different points in time
    let test_cases = vec![
        (current_slot + 5, "before any registration", None), // Before slot_1
        (slot_1 + 5, "after v1 registration", Some(&idl_v1)), // After slot_1, before slot_2
        (slot_2 + 5, "after v2 registration", Some(&idl_v2)), // After slot_2, before slot_3
        (slot_3 + 5, "after v3 registration", Some(&idl_v3)), // After slot_3
    ];

    for (i, (query_slot, description, expected_idl)) in test_cases.iter().enumerate() {
        println!(
            "  [{}] Querying IDL at slot {} ({})",
            i + 4,
            query_slot,
            description
        );

        let get_idl_response: JsonRpcResult<RpcResponse<Option<Idl>>> = rpc_server.get_idl(
            Some(runloop_context.clone()),
            idl_v1.address.to_string(),
            Some(Slot::from(*query_slot)),
        );

        assert!(
            get_idl_response.is_ok(),
            "Get IDL failed at slot {}: {:?}",
            query_slot,
            get_idl_response.err()
        );

        let retrieved_idl = get_idl_response.unwrap().value;

        match expected_idl {
            None => {
                // Should not have any IDL before first registration
                assert!(
                    retrieved_idl.is_none(),
                    "IDL should not be available when querying at slot {} (before first registration)",
                    query_slot
                );
                println!(
                    "  [{}] Correctly: No IDL available at slot {} (before first registration)",
                    i + 4,
                    query_slot
                );
            }
            Some(expected) => {
                // Should have the appropriate IDL
                assert!(
                    retrieved_idl.is_some(),
                    "IDL should be available when querying at slot {}",
                    query_slot
                );

                let retrieved = retrieved_idl.unwrap();
                assert_eq!(
                    retrieved, **expected,
                    "Retrieved IDL should match expected IDL at slot {}",
                    query_slot
                );
                println!(
                    "  [{}] Correctly: Expected IDL retrieved at slot {}",
                    i + 4,
                    query_slot
                );
            }
        }
    }

    println!("All IDL registration and retrieval tests at different slots passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_basic(test_type: TestType) {
    // Set up test environment
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = 1_000_000;

    // Airdrop SOL to payer
    svm_locker
        .with_svm_writer(|svm| svm.airdrop(&payer.pubkey(), lamports_to_send * 2))
        .unwrap()
        .unwrap();

    // Create a simple transfer transaction
    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    // Test basic profiling without tag
    println!("Testing basic transaction profiling");
    let profile_uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), None)
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(profile_uuid);
    let profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist");

    // Verify UUID generation
    let UuidOrSignature::Uuid(uuid) = profile_result.key else {
        panic!(
            "Expected a UUID from the profile result, got: {:?}",
            profile_result.key
        );
    };
    println!("Generated UUID: {}", uuid);

    // Verify transaction profile
    assert!(
        profile_result.transaction_profile.error_message.is_none(),
        "Transaction profiling should succeed"
    );
    assert!(
        profile_result.transaction_profile.compute_units_consumed > 0,
        "Transaction should consume compute units"
    );

    // Verify slot and context
    assert_eq!(
        profile_result.slot,
        svm_locker.get_latest_absolute_slot(),
        "Profile slot should match current slot"
    );

    // Verify storage in SVM
    let stored_profile = svm_locker
        .get_profile_result(
            UuidOrSignature::Uuid(uuid),
            &RpcProfileResultConfig::default(),
        )
        .unwrap();
    assert!(stored_profile.is_some(), "Profile should be stored in SVM");

    let stored = stored_profile.unwrap();
    assert_eq!(
        stored.transaction_profile.compute_units_consumed,
        profile_result.transaction_profile.compute_units_consumed,
        "Stored profile should match returned profile"
    );

    println!("Basic transaction profiling test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_multi_instruction_basic(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let lamports_to_send = 1_000_000;

    svm_locker
        .with_svm_writer(|svm| svm.airdrop(&payer.pubkey(), lamports_to_send * 4))
        .unwrap()
        .unwrap();

    // Create a multi-instruction transaction: 3 transfers to different recipients
    let recipient = Pubkey::new_unique();
    let recipient2 = Pubkey::new_unique();
    let recipient3 = Pubkey::new_unique();
    println!("Sender: {}", payer.pubkey());
    println!("Recipient 1: {}", recipient);
    println!("Recipient 2: {}", recipient2);
    println!("Recipient 3: {}", recipient3);

    let transfer_ix = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let transfer_ix2 = transfer(&payer.pubkey(), &recipient2, lamports_to_send);
    let transfer_ix3 = transfer(&payer.pubkey(), &recipient3, lamports_to_send);

    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message = Message::new_with_blockhash(
        &[transfer_ix, transfer_ix2, transfer_ix3],
        Some(&payer.pubkey()),
        &latest_blockhash,
    );
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    let profile_uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), None)
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(profile_uuid);

    // Check profile result with Transaction depth
    {
        let rpc_profile_config = RpcProfileResultConfig {
            encoding: Some(UiAccountEncoding::JsonParsed),
            depth: Some(RpcProfileDepth::Transaction),
        };

        let profile_result = svm_locker
            .get_profile_result(key, &rpc_profile_config)
            .unwrap()
            .expect("Profile result should exist");

        // Verify UUID generation
        let UuidOrSignature::Uuid(uuid) = profile_result.key else {
            panic!(
                "Expected a UUID from the profile result, got: {:?}",
                profile_result.key
            );
        };
        println!("Generated UUID: {}", uuid);

        assert!(profile_result.transaction_profile.error_message.is_none(),);
        assert_eq!(
            profile_result.transaction_profile.compute_units_consumed,
            450
        );
        assert_eq!(
            profile_result.instruction_profiles, None,
            "Instruction profiles should be None for Transaction depth config"
        );

        let account_states = profile_result.transaction_profile.account_states;

        let _ = profile_result
            .readonly_account_states
            .get(&system_program::id())
            .expect("System program should be present in readonly account states");
        let UiAccountProfileState::Readonly = account_states
            .get(&system_program::id())
            .expect("System program state should be present")
        else {
            panic!("Expected system program state to be Readonly");
        };

        // assert payer states
        {
            let UiAccountProfileState::Writable(sender_account_change) = account_states
                .get(&payer.pubkey())
                .expect("Payer account state should be present")
            else {
                panic!("Expected account state to be Writable");
            };

            match sender_account_change {
                UiAccountChange::Update(before, after) => {
                    assert_eq!(
                        after.lamports,
                        before.lamports - (lamports_to_send * 3) - 5000,
                        "Payer account should be original balance minus three transfers and fees"
                    );
                }
                other => {
                    panic!("Expected account state to be an Update, got: {:?}", other);
                }
            }
        }

        // assert recipient 1 states
        {
            let UiAccountProfileState::Writable(recipient_1_change) = account_states
                .get(&recipient)
                .expect("Recipient 1 account state should be present")
            else {
                panic!("Expected recipient 1 account state to be Writable");
            };

            match recipient_1_change {
                UiAccountChange::Create(new) => {
                    assert_eq!(
                        new.lamports, lamports_to_send,
                        "Recipient 1 account should have received the transfer amount"
                    );
                }
                other => {
                    panic!("Expected account state to be an Create, got: {:?}", other);
                }
            }
        }

        // assert recipient 2 states
        {
            let UiAccountProfileState::Writable(recipient_2_change) = account_states
                .get(&recipient2)
                .expect("Recipient 2 account state should be present")
            else {
                panic!("Expected recipient 2 account state to be Writable");
            };

            match recipient_2_change {
                UiAccountChange::Create(new) => {
                    assert_eq!(
                        new.lamports, lamports_to_send,
                        "Recipient 2 account should have received the transfer amount"
                    );
                }
                other => {
                    panic!("Expected account state to be an Update, got: {:?}", other);
                }
            }
        }

        // assert recipient 3 states
        {
            let UiAccountProfileState::Writable(recipient_3_change) = account_states
                .get(&recipient3)
                .expect("Recipient 3 account state should be present")
            else {
                panic!("Expected recipient 3 account state to be Writable");
            };

            match recipient_3_change {
                UiAccountChange::Create(new) => {
                    assert_eq!(
                        new.lamports, lamports_to_send,
                        "Recipient 3 account should have received the transfer amount"
                    );
                }
                other => {
                    panic!("Expected account state to be Create, got: {:?}", other);
                }
            }
        }
    }

    // Check profile result with Instruction depth
    {
        let rpc_profile_config = RpcProfileResultConfig {
            encoding: Some(UiAccountEncoding::JsonParsed),
            depth: Some(RpcProfileDepth::Instruction),
        };
        let profile_result = svm_locker
            .get_profile_result(key, &rpc_profile_config)
            .unwrap()
            .expect("Profile result should exist");

        println!(
            "Profile result with Instruction depth: {}",
            serde_json::to_string_pretty(&profile_result).unwrap()
        );

        let instruction_profiles = profile_result
            .instruction_profiles
            .expect("Instruction profiles should be present for Instruction depth config");

        // assert ix 1 data
        {
            let ix_profile = instruction_profiles
                .get(0)
                .expect("Instruction profile should exist");
            assert_eq!(
                ix_profile.compute_units_consumed, 150,
                "Instruction should consume 150 CU"
            );
            assert!(ix_profile.error_message.is_none());
            let account_states = &ix_profile.account_states;
            // assert account sender states
            {
                let UiAccountProfileState::Writable(sender_account_change) = account_states
                    .get(&payer.pubkey())
                    .expect("Payer account state should be present")
                else {
                    panic!("Expected account state to be Writable");
                };

                match sender_account_change {
                    UiAccountChange::Update(before, after) => {
                        assert_eq!(
                            after.lamports,
                            before.lamports - lamports_to_send - 5000,
                            "Payer account should be original balance minus transfer amount"
                        );
                    }
                    other => {
                        panic!("Expected account state to be an Update, got: {:?}", other);
                    }
                }
            }

            // assert recipient 1 states
            {
                let UiAccountProfileState::Writable(recipient_1_change) = account_states
                    .get(&recipient)
                    .expect("Recipient 1 account state should be present")
                else {
                    panic!("Expected recipient 1 account state to be Writable");
                };

                match recipient_1_change {
                    UiAccountChange::Create(new) => {
                        assert_eq!(
                            new.lamports, lamports_to_send,
                            "Recipient 1 account should have received the transfer amount"
                        );
                    }
                    other => {
                        panic!("Expected account state to be an Update, got: {:?}", other);
                    }
                }
            }

            assert!(
                account_states.get(&recipient2).is_none(),
                "Recipient 2 should not be affected by first instruction"
            );
            assert!(
                account_states.get(&recipient3).is_none(),
                "Recipient 3 should not be affected by first instruction"
            );
        }

        // assert ix 2 data
        {
            let ix_profile = instruction_profiles
                .get(1)
                .expect("Instruction profile should exist");
            assert_eq!(
                ix_profile.compute_units_consumed, 150,
                "Instruction should consume 150 CU"
            );
            assert!(ix_profile.error_message.is_none());
            let account_states = &ix_profile.account_states;
            // assert account sender states
            {
                let UiAccountProfileState::Writable(sender_account_change) = account_states
                    .get(&payer.pubkey())
                    .expect("Payer account state should be present")
                else {
                    panic!("Expected account state to be Writable");
                };

                match sender_account_change {
                    UiAccountChange::Update(before, after) => {
                        assert_eq!(after.lamports, before.lamports - lamports_to_send);
                    }
                    other => {
                        panic!("Expected account state to be an Update, got: {:?}", other);
                    }
                }
            }

            println!(
                "Recipient 1 account state: {:?}",
                account_states.get(&recipient)
            );
            assert!(
                account_states.get(&recipient).is_none(),
                "Recipient 1 should not be affected by second instruction"
            );
            // assert recipient 2 states
            {
                let UiAccountProfileState::Writable(recipient_2_change) = account_states
                    .get(&recipient2)
                    .expect("Recipient 2 account state should be present")
                else {
                    panic!("Expected recipient 2 account state to be Writable");
                };

                match recipient_2_change {
                    UiAccountChange::Create(new) => {
                        assert_eq!(
                            new.lamports, lamports_to_send,
                            "Recipient 2 account should have received the transfer amount"
                        );
                    }
                    other => {
                        panic!("Expected account state to be an Update, got: {:?}", other);
                    }
                }
            }

            assert!(
                account_states.get(&recipient3).is_none(),
                "Recipient 3 should not be affected by first instruction"
            );
        }

        // assert ix 3 data
        {
            let ix_profile = instruction_profiles
                .get(2)
                .expect("Instruction profile should exist");
            assert_eq!(
                ix_profile.compute_units_consumed, 150,
                "Instruction should consume 150 CU"
            );
            assert!(ix_profile.error_message.is_none());
            let account_states = &ix_profile.account_states;
            // assert account sender states
            {
                let UiAccountProfileState::Writable(sender_account_change) = account_states
                    .get(&payer.pubkey())
                    .expect("Payer account state should be present")
                else {
                    panic!("Expected account state to be Writable");
                };

                match sender_account_change {
                    UiAccountChange::Update(before, after) => {
                        assert_eq!(after.lamports, before.lamports - lamports_to_send,);
                    }
                    other => {
                        panic!("Expected account state to be an Update, got: {:?}", other);
                    }
                }
            }

            assert!(
                account_states.get(&recipient).is_none(),
                "Recipient 1 should not be affected by second instruction"
            );

            assert!(
                account_states.get(&recipient2).is_none(),
                "Recipient 2 should not be affected by first instruction"
            );
            // assert recipient 3 states
            {
                let UiAccountProfileState::Writable(recipient_3_change) = account_states
                    .get(&recipient3)
                    .expect("Recipient 3 account state should be present")
                else {
                    panic!("Expected recipient 3 account state to be Writable");
                };

                match recipient_3_change {
                    UiAccountChange::Create(new) => {
                        assert_eq!(
                            new.lamports, lamports_to_send,
                            "Recipient 3 account should have received the transfer amount"
                        );
                    }
                    other => {
                        panic!("Expected account state to be an Update, got: {:?}", other);
                    }
                }
            }
        }
    }
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_with_tag(test_type: TestType) {
    // Set up test environment
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = 1_000_000;

    // Airdrop SOL to payer
    svm_locker
        .with_svm_writer(|svm| svm.airdrop(&payer.pubkey(), lamports_to_send * 3))
        .unwrap()
        .unwrap();

    // Create a simple transfer transaction
    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    // Test profiling with a tag
    let tag = "test_profile_transaction_tag".to_string();
    println!("Testing transaction profiling with tag: {}", tag);

    let profile_uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), Some(tag.clone()))
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(profile_uuid);
    let profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist");

    // Verify transaction profile
    assert!(
        profile_result.transaction_profile.error_message.is_none(),
        "Transaction profiling should succeed"
    );

    // Verify tag-based retrieval
    let tagged_results = svm_locker
        .get_profile_results_by_tag(tag.clone(), &RpcProfileResultConfig::default())
        .unwrap();
    assert!(tagged_results.is_some(), "Tagged results should be found");

    let tagged_profiles = tagged_results.unwrap();
    assert_eq!(
        tagged_profiles.len(),
        1,
        "Should have exactly one profile for this tag"
    );

    let tagged_profile = &tagged_profiles[0];
    assert_eq!(
        tagged_profile.key,
        UuidOrSignature::Uuid(profile_uuid),
        "Tagged profile should have the same UUID"
    );

    // Test multiple profiles with the same tag
    println!("Testing multiple profiles with the same tag");

    // Create another transaction
    let recipient2 = Pubkey::new_unique();
    let instruction2 = transfer(&payer.pubkey(), &recipient2, lamports_to_send);
    let message2 =
        Message::new_with_blockhash(&[instruction2], Some(&payer.pubkey()), &latest_blockhash);
    let transaction2 =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message2), &[&payer]).unwrap();

    let uuid2 = svm_locker
        .profile_transaction(&None, transaction2.clone(), Some(tag.clone()))
        .await
        .unwrap()
        .inner;

    // Verify both profiles are now associated with the tag
    let tagged_results_updated = svm_locker
        .get_profile_results_by_tag(tag.clone(), &RpcProfileResultConfig::default())
        .unwrap();
    assert!(
        tagged_results_updated.is_some(),
        "Tagged results should still be found after adding second profile"
    );

    let tagged_profiles_updated = tagged_results_updated.unwrap();
    assert_eq!(
        tagged_profiles_updated.len(),
        2,
        "Should have exactly two profiles for this tag"
    );

    // Verify both UUIDs are present
    let uuids: Vec<Uuid> = tagged_profiles_updated
        .iter()
        .filter_map(|profile| {
            if let UuidOrSignature::Uuid(uuid) = profile.key {
                Some(uuid)
            } else {
                None
            }
        })
        .collect();

    assert!(
        uuids.contains(&profile_uuid),
        "First UUID should be in tagged results"
    );
    assert!(
        uuids.contains(&uuid2),
        "Second UUID should be in tagged results"
    );

    // Test retrieval with non-existent tag
    let non_existent_tag = "non_existent_tag".to_string();
    let non_existent_results = svm_locker
        .get_profile_results_by_tag(non_existent_tag, &RpcProfileResultConfig::default())
        .unwrap();
    assert!(
        non_existent_results.is_none(),
        "Non-existent tag should return None"
    );

    // Test retrieval by individual UUIDs
    let stored_profile1 = svm_locker
        .get_profile_result(
            UuidOrSignature::Uuid(profile_uuid),
            &RpcProfileResultConfig::default(),
        )
        .unwrap();
    assert!(
        stored_profile1.is_some(),
        "First profile should be retrievable by UUID"
    );

    let stored_profile2 = svm_locker
        .get_profile_result(
            UuidOrSignature::Uuid(uuid2),
            &RpcProfileResultConfig::default(),
        )
        .unwrap();
    assert!(
        stored_profile2.is_some(),
        "Second profile should be retrievable by UUID"
    );

    println!("Tag-based transaction profiling test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_token_transfer(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let mint = Keypair::new();
    let lamports_to_send = 2 * LAMPORTS_PER_SOL;
    println!("Sender: {}", payer.pubkey());
    println!("Recipient: {}", recipient);
    println!("Mint: {}", mint.pubkey());

    // Airdrop SOL to payer
    svm_locker
        .airdrop(&payer.pubkey(), lamports_to_send)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    println!("Recent blockhash after airdrop: {}", recent_blockhash);

    // Create account for mint
    let mint_rent = 1461600;
    let create_account_ix = system_instruction::create_account(
        &payer.pubkey(),
        &mint.pubkey(),
        mint_rent,
        82,
        &spl_token_2022_interface::id(),
    );

    // Initialize mint
    let initialize_mint_ix = spl_token_2022_interface::instruction::initialize_mint2(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer.pubkey(),
        Some(&payer.pubkey()),
        2, // decimals
    )
    .unwrap();

    // Create associated token accounts
    let source_ata = spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
        &payer.pubkey(),
        &mint.pubkey(),
        &spl_token_2022_interface::id(),
    );
    println!("Source ATA: {}", source_ata);
    let _dest_ata = spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
        &recipient,
        &mint.pubkey(),
        &spl_token_2022_interface::id(),
    );

    let create_source_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &payer.pubkey(),
            &payer.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let _create_dest_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &payer.pubkey(),
            &recipient,
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    // Mint tokens
    let mint_amount = 100_00; // 100 tokens with 2 decimals
    let _mint_to_ix = spl_token_2022_interface::instruction::mint_to(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &source_ata,
        &payer.pubkey(),
        &[&payer.pubkey()],
        mint_amount,
    )
    .unwrap();

    // Create setup transaction
    let setup_message = Message::new_with_blockhash(
        &[
            create_account_ix,
            initialize_mint_ix,
            create_source_ata_ix,
            // create_dest_ata_ix,
            // mint_to_ix,
        ],
        Some(&payer.pubkey()),
        &recent_blockhash,
    );
    let setup_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(setup_message), &[&payer, &mint])
            .unwrap();

    {
        let profile_result = svm_locker
            .profile_transaction(&None, setup_tx.clone(), None)
            .await
            .unwrap();

        let rpc_profile_config = RpcProfileResultConfig {
            encoding: Some(UiAccountEncoding::JsonParsed),
            depth: Some(RpcProfileDepth::Instruction),
        };
        let key = UuidOrSignature::Uuid(profile_result.inner);
        let ui_profile_result = svm_locker
            .get_profile_result(key, &rpc_profile_config)
            .unwrap()
            .expect("Profile result should exist");

        assert!(
            ui_profile_result
                .transaction_profile
                .error_message
                .is_none(),
            "Setup transaction should succeed, found error: {}",
            ui_profile_result.transaction_profile.error_message.unwrap()
        );

        // instruction 1: create_account
        {
            let ix_profile = ui_profile_result
                .instruction_profiles
                .as_ref()
                .unwrap()
                .get(0)
                .expect("instruction profile should exist");
            assert!(
                ix_profile.error_message.is_none(),
                "Profile should succeed, found error: {}",
                ix_profile.error_message.as_ref().unwrap()
            );
            assert_eq!(ix_profile.compute_units_consumed, 150);
            assert!(ix_profile.error_message.is_none());
            let account_states = &ix_profile.account_states;

            let UiAccountProfileState::Writable(sender_account_change) = account_states
                .get(&payer.pubkey())
                .expect("Payer account state should be present")
            else {
                panic!("Expected account state to be Writable");
            };

            match sender_account_change {
                UiAccountChange::Update(before, after) => {
                    assert_eq!(
                        after.lamports,
                        before.lamports - mint_rent - (2 * 5000), // two signers, so 2 * 5000 for fees
                        "Payer account should be original balance minus rent"
                    );
                }
                other => {
                    panic!("Expected account state to be an Update, got: {:?}", other);
                }
            }

            let UiAccountProfileState::Writable(mint_account_change) = account_states
                .get(&mint.pubkey())
                .expect("Mint account state should be present")
            else {
                panic!("Expected mint account state to be Writable");
            };
            match mint_account_change {
                UiAccountChange::Create(mint_account) => {
                    assert_eq!(
                        mint_account.lamports, mint_rent,
                        "Mint account should have the correct rent amount"
                    );
                    assert_eq!(
                        mint_account.owner,
                        spl_token_2022_interface::id().to_string(),
                        "Mint account should be owned by the SPL Token program"
                    );
                    // initialized account data should be empty bytes
                    assert_eq!(
                        mint_account.data,
                        UiAccountData::Binary(
                            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==".into(),
                            UiAccountEncoding::Base64
                        ),
                    );
                }
                other => {
                    panic!("Expected account state to be an Update, got: {:?}", other);
                }
            }
        }

        // instruction 2: initialize mint
        {
            let ix_profile = ui_profile_result
                .instruction_profiles
                .as_ref()
                .unwrap()
                .get(1)
                .expect("instruction profile should exist");
            assert!(
                ix_profile.error_message.is_none(),
                "Profile should succeed, found error: {}",
                ix_profile.error_message.as_ref().unwrap()
            );
            assert_eq!(ix_profile.compute_units_consumed, 1278);
            assert!(ix_profile.error_message.is_none());
            let account_states = &ix_profile.account_states;

            assert!(account_states.get(&payer.pubkey()).is_none());

            let UiAccountProfileState::Writable(mint_account_change) = account_states
                .get(&mint.pubkey())
                .expect("Mint account state should be present")
            else {
                panic!("Expected mint account state to be Writable");
            };
            match mint_account_change {
                UiAccountChange::Update(_before, after) => {
                    assert_eq!(
                        after.lamports, mint_rent,
                        "Mint account should have the correct rent amount"
                    );
                    assert_eq!(
                        after.owner,
                        spl_token_2022_interface::id().to_string(),
                        "Mint account should be owned by the SPL Token program"
                    );
                    // initialized account data should be empty bytes
                    assert_eq!(
                        after.data,
                        UiAccountData::Json(ParsedAccount {
                            program: "spl-token-2022".to_string(),
                            parsed: json!({
                                "info": {
                                    "decimals": 2,
                                    "freezeAuthority": payer.pubkey().to_string(),
                                    "mintAuthority": payer.pubkey().to_string(),
                                    "isInitialized": true,
                                    "supply": "0",
                                },
                                "type": "mint"
                            }),
                            space: 82,
                        }),
                    );
                }
                other => {
                    panic!("Expected account state to be an Update, got: {:?}", other);
                }
            }
        }

        // instruction 3: create token account
        {
            let ix_profile = ui_profile_result
                .instruction_profiles
                .as_ref()
                .unwrap()
                .get(2)
                .expect("instruction profile should exist");
            assert!(
                ix_profile.error_message.is_none(),
                "Profile should succeed, found error: {}",
                ix_profile.error_message.as_ref().unwrap()
            );
            // assert_eq!(ix_profile.compute_units_consumed, 15758);
            assert!(ix_profile.error_message.is_none());
            let account_states = &ix_profile.account_states;

            let UiAccountProfileState::Writable(sender_account_change) = account_states
                .get(&payer.pubkey())
                .expect("Payer account state should be present")
            else {
                panic!("Expected account state to be Writable");
            };

            match sender_account_change {
                UiAccountChange::Update(before, after) => {
                    assert_eq!(
                        after.lamports,
                        before.lamports - 2074080,
                        "Payer account should be original balance minus rent"
                    );
                }
                other => {
                    panic!("Expected account state to be an Update, got: {:?}", other);
                }
            }

            let UiAccountProfileState::Writable(mint_account_change) = account_states
                .get(&mint.pubkey())
                .expect("Mint account state should be present")
            else {
                panic!("Expected mint account state to be Writable");
            };
            match mint_account_change {
                UiAccountChange::Unchanged(mint_account) => {
                    assert!(mint_account.is_some())
                }
                other => {
                    panic!("Expected account state to be Unchanged, got: {:?}", other);
                }
            }

            let UiAccountProfileState::Writable(source_ata_change) = account_states
                .get(&source_ata)
                .expect("account state should be present")
            else {
                panic!("Expected account state to be Writable");
            };

            match source_ata_change {
                UiAccountChange::Create(new) => {
                    assert_eq!(
                        new.lamports, 2074080,
                        "Source ATA should have the correct lamports after creation"
                    );
                    assert_eq!(
                        new.owner,
                        spl_token_2022_interface::id().to_string(),
                        "Source ATA should be owned by the SPL Token program"
                    );
                    // since we're profiling, the "additional data" needed to json parse token 2022 accounts isn't available,
                    // so the result is base64 encoded
                    let UiAccountData::Binary(new_data, UiAccountEncoding::Base64) = &new.data
                    else {
                        panic!("Expected account data to be Base64 encoded");
                    };

                    let mut mint_bs64 =
                        base64::engine::general_purpose::STANDARD.encode(&mint.pubkey().to_bytes());
                    mint_bs64.truncate(42);
                    assert!(new_data.starts_with(mint_bs64.as_str()));
                    assert!(
                        new_data.ends_with(
                            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgcAAAA="
                        )
                    );
                }
                other => {
                    panic!("Expected account state to be Create, got: {:?}", other);
                }
            }
        }

        assert_eq!(
            ui_profile_result.transaction_profile.compute_units_consumed,
            ui_profile_result
                .instruction_profiles
                .as_ref()
                .unwrap()
                .iter()
                .map(|ix| ix.compute_units_consumed)
                .sum::<u64>(),
        );
    }

    // Process setup transaction
    // let (status_tx, status_rx) = crossbeam_channel::unbounded();
    // svm_locker
    //     .process_transaction(&None, setup_tx, status_tx, false, true)
    //     .await
    //     .unwrap();

    // match status_rx.recv() {
    //     Ok(TransactionStatusEvent::Success(_)) => println!("Setup transaction successful"),
    //     other => panic!("Setup transaction failed: {:?}", other),
    // }

    // // Now create a token transfer transaction to profile
    // let transfer_amount = 50; // 0.5 tokens
    // let transfer_ix = spl_token_2022_interface::instruction::transfer_checked(
    //     &spl_token_2022_interface::id(),
    //     &source_ata,
    //     &mint.pubkey(),
    //     &dest_ata,
    //     &payer.pubkey(),
    //     &[&payer.pubkey()],
    //     transfer_amount,
    //     2, // decimals
    // )
    // .unwrap();

    // let transfer_message =
    //     Message::new_with_blockhash(&[transfer_ix], Some(&payer.pubkey()), &recent_blockhash);
    // let transfer_tx =
    //     VersionedTransaction::try_new(VersionedMessage::Legacy(transfer_message), &[&payer])
    //         .unwrap();

    // // Profile the token transfer transaction
    // let profile_result = svm_locker
    //     .profile_transaction(&None, transfer_tx.clone(), None)
    //     .await
    //     .unwrap();

    // let rpc_profile_config = RpcProfileResultConfig {
    //     encoding: Some(UiAccountEncoding::JsonParsed),
    //     depth: Some(RpcProfileDepth::Instruction),
    // };
    // let ui_profile_result = svm_locker
    //     .encode_ui_keyed_profile_result(profile_result.inner.clone(), &rpc_profile_config);

    // println!(
    //     "UI Profile Result: {}",
    //     serde_json::to_string_pretty(&ui_profile_result).unwrap()
    // );

    // // Verify UUID generation
    // let UuidOrSignature::Uuid(_uuid) = profile_result.inner.key else {
    //     panic!("Expected a UUID from the profile result");
    // };

    // // Verify transaction profile
    // assert!(
    //     profile_result
    //         .inner
    //         .transaction_profile
    //         .error_message
    //         .is_none(),
    //     "Token transfer profiling should succeed"
    // );
    // assert!(
    //     profile_result
    //         .inner
    //         .transaction_profile
    //         .compute_units_consumed
    //         > 0,
    //     "Token transfer should consume compute units"
    // );

    // println!("Token transfer profiling test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_insufficient_funds(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts with insufficient funds
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let insufficient_funds = LAMPORTS_PER_SOL;
    let large_transfer = LAMPORTS_PER_SOL * 10;

    svm_locker
        .airdrop(&payer.pubkey(), insufficient_funds)
        .unwrap()
        .unwrap();

    // Create a transfer transaction that will fail due to insufficient funds
    let instruction = transfer(&payer.pubkey(), &recipient, large_transfer);
    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    // Profile the failing transaction
    let profile_uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), None)
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(profile_uuid);
    let ui_profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist");

    // Verify transaction profile shows failure
    assert!(
        ui_profile_result
            .transaction_profile
            .error_message
            .is_some(),
        "Transaction should fail due to insufficient funds"
    );

    let error_msg = ui_profile_result
        .transaction_profile
        .error_message
        .as_ref()
        .unwrap();
    assert!(
        error_msg.eq("Error processing Instruction 0: custom program error: 0x1"),
        "Error message should indicate insufficient funds, got: {}",
        error_msg
    );

    // Verify compute units were still consumed
    assert!(
        ui_profile_result.transaction_profile.compute_units_consumed > 0,
        "Failed transaction should still consume compute units"
    );

    println!("Insufficient funds profiling test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_multi_instruction_failure(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts
    let payer = Keypair::new();
    let payer2 = Keypair::new();
    let recipient1 = Pubkey::new_unique();
    let lamports_to_send = LAMPORTS_PER_SOL;

    // Airdrop SOL to payer
    svm_locker
        .airdrop(&payer.pubkey(), lamports_to_send * 3)
        .unwrap()
        .unwrap();

    // Create a multi-instruction transaction where the second instruction will fail
    let valid_instruction = transfer(&payer.pubkey(), &recipient1, lamports_to_send);
    let invalid_instruction = transfer(&payer2.pubkey(), &recipient1, lamports_to_send * 2); // payer2 has no funds

    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message = Message::new_with_blockhash(
        &[valid_instruction, invalid_instruction],
        Some(&payer.pubkey()),
        &latest_blockhash,
    );
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer, &payer2])
            .unwrap();

    // Profile the multi-instruction transaction

    let uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), None)
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(uuid);
    let profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist");

    // Verify transaction profile shows failure
    assert!(
        profile_result.transaction_profile.error_message.is_some(),
        "Multi-instruction transaction should fail"
    );

    // Verify instruction profiles exist
    assert!(
        profile_result.instruction_profiles.is_some(),
        "Instruction profiles should be generated for multi-instruction transaction"
    );

    let instruction_profiles = profile_result.instruction_profiles.as_ref().unwrap();
    assert_eq!(instruction_profiles.len(), 2,);

    // Verify the first instruction profile succeeded
    let first_instruction_profile = &instruction_profiles[0];
    assert!(
        first_instruction_profile.error_message.is_none(),
        "First instruction should succeed"
    );
    assert!(
        first_instruction_profile.compute_units_consumed > 0,
        "First instruction should consume compute units"
    );

    let second_profile = &instruction_profiles[1];
    assert!(
        second_profile.error_message.is_some(),
        "Second instruction should fail due to insufficient funds"
    );

    println!("Multi-instruction failure profiling test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_with_encoding(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = LAMPORTS_PER_SOL;

    // Airdrop SOL to payer
    svm_locker
        .with_svm_writer(|svm| svm.airdrop(&payer.pubkey(), lamports_to_send * 2))
        .unwrap()
        .unwrap();

    // Create a simple transfer transaction
    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    let profile_uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), None)
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(profile_uuid);
    let profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist");

    // Verify transaction profile
    assert!(
        profile_result.transaction_profile.error_message.is_none(),
        "Transaction profiling should succeed with base64 encoding"
    );

    // // Verify state snapshots use the specified encoding
    // let pre_execution_accounts = &profile_result.inner.transaction_profile.state.pre_execution;
    // let post_execution_accounts = &profile_result
    //     .inner
    //     .transaction_profile
    //     .state
    //     .post_execution;

    // for (_, account_opt) in pre_execution_accounts
    //     .iter()
    //     .chain(post_execution_accounts.iter())
    // {
    //     if let Some(account) = account_opt {
    //         // Verify the account data is base64 encoded
    //         if let UiAccountData::Binary(_, encoding) = &account.data {
    //             assert!(
    //                 *encoding == UiAccountEncoding::Base64,
    //                 "Account data should be base64 encoded"
    //             );
    //         }
    //     }
    // }

    println!("Encoding profiling test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_with_tag_and_retrieval(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = LAMPORTS_PER_SOL;

    // Airdrop SOL to payer
    svm_locker
        .with_svm_writer(|svm| svm.airdrop(&payer.pubkey(), lamports_to_send * 3))
        .unwrap()
        .unwrap();

    // Create a simple transfer transaction
    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    // Profile with a tag
    let tag = "test_tag_retrieval".to_string();

    let profile_uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), Some(tag.clone()))
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(profile_uuid);
    let profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist");

    // Verify transaction profile
    assert!(
        profile_result.transaction_profile.error_message.is_none(),
        "Transaction profiling should succeed"
    );

    // Test retrieval by UUID
    let retrieved_by_uuid = svm_locker
        .get_profile_result(
            UuidOrSignature::Uuid(profile_uuid),
            &RpcProfileResultConfig::default(),
        )
        .unwrap();
    assert!(
        retrieved_by_uuid.is_some(),
        "Profile should be retrievable by UUID"
    );

    let retrieved = retrieved_by_uuid.unwrap();
    assert_eq!(
        retrieved.transaction_profile.compute_units_consumed,
        profile_result.transaction_profile.compute_units_consumed,
        "Retrieved profile should match original profile"
    );

    // Test retrieval by tag
    let retrieved_by_tag = svm_locker
        .get_profile_results_by_tag(tag.clone(), &RpcProfileResultConfig::default())
        .unwrap();
    assert!(
        retrieved_by_tag.is_some(),
        "Profile should be retrievable by tag"
    );

    let tagged_profiles = retrieved_by_tag.unwrap();
    assert_eq!(
        tagged_profiles.len(),
        1,
        "Should have exactly one profile for this tag"
    );

    let tagged_profile = &tagged_profiles[0];
    assert_eq!(
        tagged_profile.key,
        UuidOrSignature::Uuid(profile_uuid),
        "Tagged profile should have the same UUID"
    );

    // Test retrieval with non-existent tag
    let non_existent_tag = "non_existent_tag".to_string();
    let non_existent_result = svm_locker
        .get_profile_results_by_tag(non_existent_tag, &RpcProfileResultConfig::default())
        .unwrap();
    assert!(
        non_existent_result.is_none(),
        "Non-existent tag should return None"
    );

    println!("Tag and retrieval profiling test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_empty_instruction(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts
    let payer = Keypair::new();
    let lamports_to_send = LAMPORTS_PER_SOL;

    // Airdrop SOL to payer
    svm_locker
        .airdrop(&payer.pubkey(), lamports_to_send)
        .unwrap()
        .unwrap();

    // Create a transaction with no instructions
    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message = Message::new_with_blockhash(
        &[], // No instructions
        Some(&payer.pubkey()),
        &latest_blockhash,
    );
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    // Profile the empty transaction
    let profile_uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), None)
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(profile_uuid);
    let profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist");

    println!("profile result: {:#?}", profile_result);

    // Verify transaction profile
    assert!(
        profile_result.transaction_profile.error_message.is_none(),
        "Empty transaction profiling should succeed"
    );

    // Verify compute units consumed (should be minimal)
    assert_eq!(profile_result.transaction_profile.compute_units_consumed, 0);

    // Verify no instruction profiles for empty transaction
    assert!(
        profile_result.instruction_profiles.is_none(),
        "Empty transaction should not have instruction profiles"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_versioned_message(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Set up test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = LAMPORTS_PER_SOL;

    // Airdrop SOL to payer
    svm_locker
        .airdrop(&payer.pubkey(), 2 * lamports_to_send)
        .unwrap()
        .unwrap();

    svm_locker.confirm_current_block(&None).await.unwrap();

    // Create a transfer instruction
    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    // Create a v0 message
    let v0_message = v0::Message::try_compile(
        &payer.pubkey(),
        &[instruction],
        &[], // No address table lookups
        latest_blockhash,
    )
    .expect("Failed to compile v0 message");

    let transaction =
        VersionedTransaction::try_new(VersionedMessage::V0(v0_message), &[&payer]).unwrap();

    // Profile the versioned transaction
    let profile_uuid = svm_locker
        .profile_transaction(&None, transaction.clone(), None)
        .await
        .unwrap()
        .inner;

    let key = UuidOrSignature::Uuid(profile_uuid);
    let profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist");

    // Verify transaction profile
    assert!(
        profile_result.transaction_profile.error_message.is_none(),
        "Versioned transaction profiling should succeed, found: {:?}",
        profile_result.transaction_profile.error_message.unwrap()
    );
    assert!(
        profile_result.transaction_profile.compute_units_consumed > 0,
        "Versioned transaction should consume compute units"
    );

    println!("Versioned message profiling test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_get_local_signatures_without_limit(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();

    let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance.clone());

    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker_for_context.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    let payer = Keypair::new();
    let recipient = Keypair::new();
    let lamports_to_send = 1_000_000;

    svm_locker_for_context
        .airdrop(&payer.pubkey(), lamports_to_send * 2)
        .unwrap()
        .unwrap();

    svm_locker_for_context
        .confirm_current_block(&None)
        .await
        .unwrap();

    let create_account_instruction = system_instruction::create_account(
        &payer.pubkey(),
        &recipient.pubkey(),
        lamports_to_send / 2,
        0,
        &solana_sdk_ids::system_program::id(),
    );

    let create_account_tx = Transaction::new_signed_with_payer(
        &[create_account_instruction],
        Some(&payer.pubkey()),
        &[&payer, &recipient],
        svm_locker_for_context.with_svm_reader(|svm| svm.latest_blockhash()),
    );

    let (create_status_tx, _create_status_rx) = crossbeam_channel::bounded(1);
    svm_locker_for_context
        .process_transaction(
            &None,
            create_account_tx.into(),
            create_status_tx,
            false,
            true,
        )
        .await
        .unwrap();
    // Confirm the block after creating the account
    svm_locker_for_context
        .confirm_current_block(&None)
        .await
        .unwrap();

    // Now create the transfer transaction
    let instruction = transfer(&payer.pubkey(), &recipient.pubkey(), lamports_to_send);
    let latest_blockhash = svm_locker_for_context.with_svm_reader(|svm| svm.latest_blockhash());
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message.clone()), &[&payer])
        .unwrap();

    let (status_tx, _status_rx) = crossbeam_channel::bounded(1);

    svm_locker_for_context
        .process_transaction(&None, tx.clone(), status_tx, false, true)
        .await
        .unwrap();

    // Confirm the current block to create a block with the transaction signature
    svm_locker_for_context
        .confirm_current_block(&None)
        .await
        .unwrap();

    let get_local_signatures_response: JsonRpcResult<RpcResponse<Vec<RpcLogsResponse>>> =
        rpc_server
            .get_local_signatures(Some(runloop_context.clone()), None)
            .await;

    assert!(
        get_local_signatures_response.is_ok(),
        "Get local signatures failed: {:?}",
        get_local_signatures_response.err()
    );

    let local_signatures = get_local_signatures_response.unwrap().value;
    assert!(local_signatures.len() > 0);
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_get_local_signatures_with_limit(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance.clone());

    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker_for_context.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    let payer = Keypair::new();
    let _recipient = Keypair::new();
    let lamports_to_send = 10_000_000;

    svm_locker_for_context
        .airdrop(&payer.pubkey(), lamports_to_send * 10)
        .unwrap()
        .unwrap();

    svm_locker_for_context
        .confirm_current_block(&None)
        .await
        .unwrap();

    // Get the initial number of signatures to establish a baseline
    let initial_signatures_response: JsonRpcResult<RpcResponse<Vec<RpcLogsResponse>>> = rpc_server
        .get_local_signatures(Some(runloop_context.clone()), None)
        .await;

    let initial_count = initial_signatures_response.unwrap().value.len();

    // Create multiple transactions to test limit functionality
    let num_transactions = 10;
    let mut transaction_signatures = Vec::new();

    for _i in 0..num_transactions {
        // Create a unique recipient for each transaction
        let unique_recipient = Keypair::new();

        let instruction = transfer(
            &payer.pubkey(),
            &unique_recipient.pubkey(),
            lamports_to_send / num_transactions as u64,
        );
        let latest_blockhash = svm_locker_for_context.with_svm_reader(|svm| svm.latest_blockhash());
        let message =
            Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
        let tx =
            VersionedTransaction::try_new(VersionedMessage::Legacy(message.clone()), &[&payer])
                .unwrap();

        let (status_tx, _status_rx) = crossbeam_channel::bounded(1);

        svm_locker_for_context
            .process_transaction(&None, tx.clone(), status_tx, false, true)
            .await
            .unwrap();

        // Store the signature for verification
        transaction_signatures.push(tx.signatures[0]);

        // Confirm the current block to create a new block with this transaction
        svm_locker_for_context
            .confirm_current_block(&None)
            .await
            .unwrap();
    }

    // Test with different limit values
    let test_limits = vec![1, 3, 5, 10, 15];

    for limit in test_limits {
        let get_local_signatures_response: JsonRpcResult<RpcResponse<Vec<RpcLogsResponse>>> =
            rpc_server
                .get_local_signatures(Some(runloop_context.clone()), Some(limit))
                .await;

        assert!(
            get_local_signatures_response.is_ok(),
            "Get local signatures with limit {} failed: {:?}",
            limit,
            get_local_signatures_response.err()
        );

        let local_signatures = get_local_signatures_response.unwrap().value;

        // Verify that the number of returned signatures respects the limit
        assert!(
            local_signatures.len() <= limit as usize,
            "Expected at most {} signatures, but got {}",
            limit,
            local_signatures.len()
        );

        // Verify that we get the expected number of signatures
        // The total expected count should be min(limit, initial_count + num_transactions)
        let total_expected_signatures = initial_count + num_transactions;
        let expected_count = std::cmp::min(limit as usize, total_expected_signatures);

        assert!(
            local_signatures.len() == expected_count,
            "Expected {} signatures with limit {}, but got {} (initial: {}, new: {})",
            expected_count,
            limit,
            local_signatures.len(),
            initial_count,
            num_transactions
        );
    }

    // Test with limit = 0 (should return empty list)
    let get_local_signatures_response: JsonRpcResult<RpcResponse<Vec<RpcLogsResponse>>> =
        rpc_server
            .get_local_signatures(Some(runloop_context.clone()), Some(0))
            .await;

    assert!(
        get_local_signatures_response.is_ok(),
        "Get local signatures with limit 0 failed: {:?}",
        get_local_signatures_response.err()
    );

    let local_signatures = get_local_signatures_response.unwrap().value;
    assert!(
        local_signatures.is_empty(),
        "Expected empty list with limit 0, but got {} signatures",
        local_signatures.len()
    );

    println!("All local signatures tests passed successfully!");
}

// ============================================================================
// Clock Control Tests (pauseClock, resumeClock, timeTravel)
// ============================================================================

fn boot_simnet(
    block_production_mode: BlockProductionMode,
    slot_time: Option<u64>,
    test_type: TestType,
) -> (
    SurfnetSvmLocker,
    crossbeam_channel::Sender<SimnetCommand>,
    crossbeam_channel::Receiver<SimnetEvent>,
) {
    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: slot_time.unwrap_or(DEFAULT_SLOT_TIME_MS),
            block_production_mode,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            gossip_port: 0,
            tpu_port: 0,
            tpu_quic_port: 0,
        },
        subgraph: SubgraphConfig::default(),
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);

    let svm_locker_cc: SurfnetSvmLocker = svm_locker.clone();
    let simnet_commands_tx_cc = simnet_commands_tx.clone();
    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            svm_locker_cc,
            config,
            simnet_commands_tx_cc,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });

    loop {
        if let Ok(SimnetEvent::Ready(_)) =
            simnet_events_rx.recv_timeout(Duration::from_millis(1000))
        {
            break;
        }
    }

    (svm_locker, simnet_commands_tx, simnet_events_rx)
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_time_travel_resume_paused_clock(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_locker, simnet_cmd_tx, _) =
        boot_simnet(BlockProductionMode::Clock, Some(100), test_type);
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Get initial epoch info
    let initial_slot = svm_locker.get_latest_absolute_slot();

    // Ensure the clock has advanced
    std::thread::sleep(Duration::from_millis(500));
    let new_slot = svm_locker.get_latest_absolute_slot();
    assert!(
        new_slot > initial_slot,
        "Slot should change when clock is not paused"
    );

    // Test pause clock
    let _ = rpc_server.pause_clock(Some(runloop_context.clone()));

    // Buffer to ensure the clock is paused
    std::thread::sleep(Duration::from_millis(100));

    // Get latest slot
    let slot_after_pause = svm_locker.get_latest_absolute_slot();

    // Ensure the clock is paused after 500ms
    std::thread::sleep(Duration::from_millis(500));
    let slot_after_pause_and_500ms = svm_locker.get_latest_absolute_slot();
    assert!(
        slot_after_pause == slot_after_pause_and_500ms,
        "Slot should change when clock is not paused"
    );

    // Ensure the clock is still paused after 2s
    std::thread::sleep(Duration::from_millis(2000));
    let slot_after_pause_and_2500ms = svm_locker.get_latest_absolute_slot();
    assert!(
        slot_after_pause == slot_after_pause_and_2500ms,
        "Slot should change when clock is not paused"
    );

    // Now let's resume the clock
    let resume_response: JsonRpcResult<EpochInfo> =
        rpc_server.resume_clock(Some(runloop_context.clone()));
    let slot_after_resume = svm_locker.get_latest_absolute_slot();

    assert!(
        resume_response.is_ok(),
        "Resume clock failed: {:?}",
        resume_response.err()
    );

    // Ensure the clock is paused after 500ms
    std::thread::sleep(Duration::from_millis(500));
    let slot_after_resume_and_500ms = svm_locker.get_latest_absolute_slot();
    assert!(
        slot_after_resume < slot_after_resume_and_500ms,
        "Slot should change when clock is not paused"
    );

    println!("Resume clock test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_time_travel_absolute_timestamp(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let slot_time = 100;
    let (svm_locker, simnet_cmd_tx, simnet_events_rx) = boot_simnet(
        BlockProductionMode::Clock,
        Some(slot_time.clone()),
        test_type,
    );
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker.clone(),
        simnet_commands_tx: simnet_cmd_tx.clone(),

        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    let clock = Clock {
        slot: 1,
        epoch_start_timestamp: 1,
        epoch: 1,
        leader_schedule_epoch: 100,
        unix_timestamp: 100,
    };

    simnet_cmd_tx
        .send(SimnetCommand::UpdateInternalClock(None, clock))
        .unwrap();
    let Ok(SimnetEvent::SystemClockUpdated(_clock_updated)) =
        simnet_events_rx.recv_timeout(Duration::from_millis(5000))
    else {
        panic!("failed to update internal clock")
    };

    let initial_epoch_info = svm_locker.get_epoch_info();

    println!("Initial epoch info: {:?}", initial_epoch_info);

    let seven_days = 7 * 24 * 60 * 60 * 1000;
    let target_timestamp = svm_locker.0.blocking_read().updated_at + seven_days;

    // Test time travel to absolute timestamp
    // Note: time_travel now uses confirmation mechanism, so it waits internally
    let time_travel_response: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteTimestamp(target_timestamp)),
    );

    assert!(
        time_travel_response.is_ok(),
        "Time travel to absolute timestamp failed: {:?}",
        time_travel_response.err()
    );

    let new_epoch_info = time_travel_response.unwrap();
    println!("Response: {:?}", new_epoch_info);

    // Verify the epoch info reflects the time travel
    assert_ne!(
        new_epoch_info.epoch, initial_epoch_info.epoch,
        "Epoch should change after time travel"
    );
    assert_ne!(
        new_epoch_info.absolute_slot, initial_epoch_info.absolute_slot,
        "Slot should change after time travel"
    );

    // Verify the current epoch info in SVM matches
    let current_epoch_info = svm_locker.get_epoch_info();
    println!("Updated epoch info: {:?}", current_epoch_info);

    assert_eq!(current_epoch_info.epoch, new_epoch_info.epoch);
    assert_eq!(
        current_epoch_info.absolute_slot,
        new_epoch_info.absolute_slot
    );

    println!("Time travel to absolute timestamp test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_time_travel_absolute_slot(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_locker, simnet_cmd_tx, simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker.clone(),
        simnet_commands_tx: simnet_cmd_tx.clone(),

        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    let clock = Clock {
        slot: 1,
        epoch_start_timestamp: 1,
        epoch: 1,
        leader_schedule_epoch: 100,
        unix_timestamp: 100,
    };

    simnet_cmd_tx
        .send(SimnetCommand::UpdateInternalClock(None, clock))
        .unwrap();
    let Ok(SimnetEvent::SystemClockUpdated(_clock_updated)) =
        simnet_events_rx.recv_timeout(Duration::from_millis(5000))
    else {
        panic!("failed to update internal clock")
    };

    let initial_epoch_info = svm_locker.get_epoch_info();
    let target_slot = initial_epoch_info.absolute_slot + 1000000; // A future slot number

    // Test time travel to absolute slot
    // Note: time_travel now uses confirmation mechanism, so it waits internally
    let time_travel_response: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteSlot(target_slot)),
    );

    assert!(
        time_travel_response.is_ok(),
        "Time travel to absolute slot failed: {:?}",
        time_travel_response.err()
    );

    let new_epoch_info = time_travel_response.unwrap();

    // Verify the epoch info reflects the time travel
    assert_eq!(
        new_epoch_info.absolute_slot, target_slot,
        "Slot should match target slot"
    );
    assert!(
        new_epoch_info.epoch > initial_epoch_info.epoch,
        "Epoch should change after time travel"
    );
    assert!(
        new_epoch_info.absolute_slot > initial_epoch_info.absolute_slot,
        "Epoch should change after time travel"
    );

    // Verify the current epoch info in SVM matches
    let current_epoch_info = svm_locker.get_epoch_info();
    assert_eq!(current_epoch_info.absolute_slot, target_slot);
    assert_eq!(current_epoch_info.epoch, new_epoch_info.epoch);

    println!("Time travel to absolute slot test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_time_travel_absolute_epoch(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_locker, simnet_cmd_tx, simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker.clone(),
        simnet_commands_tx: simnet_cmd_tx.clone(),

        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    let clock = Clock {
        slot: 1,
        epoch_start_timestamp: 1,
        epoch: 1,
        leader_schedule_epoch: 100,
        unix_timestamp: 100,
    };

    simnet_cmd_tx
        .send(SimnetCommand::UpdateInternalClock(None, clock))
        .unwrap();
    let Ok(SimnetEvent::SystemClockUpdated(_clock_updated)) =
        simnet_events_rx.recv_timeout(Duration::from_millis(5000))
    else {
        panic!("failed to update internal clock")
    };

    let initial_epoch_info = svm_locker.get_epoch_info();
    let target_epoch = initial_epoch_info.epoch + 100; // A future epoch number

    // Test time travel to absolute epoch
    // Note: time_travel now uses confirmation mechanism, so it waits internally
    let time_travel_response: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteEpoch(target_epoch)),
    );

    assert!(
        time_travel_response.is_ok(),
        "Time travel to absolute epoch failed: {:?}",
        time_travel_response.err()
    );

    let new_epoch_info = time_travel_response.unwrap();

    // Verify the epoch info reflects the time travel
    assert_eq!(
        new_epoch_info.epoch, target_epoch,
        "Epoch should match target epoch"
    );
    assert_ne!(
        new_epoch_info.epoch, initial_epoch_info.epoch,
        "Epoch should change after time travel"
    );
    assert_ne!(
        new_epoch_info.absolute_slot, initial_epoch_info.absolute_slot,
        "Slot should change after time travel"
    );

    // Verify the current epoch info in SVM matches
    let current_epoch_info = svm_locker.get_epoch_info();
    assert_eq!(current_epoch_info.epoch, target_epoch);
    assert_eq!(
        current_epoch_info.absolute_slot,
        new_epoch_info.absolute_slot
    );

    println!("Time travel to absolute epoch test passed successfully!");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ix_profiling_with_alt_tx(test_type: TestType) {
    let (svm_locker, _simnet_cmd_tx, _simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);

    let p1 = Keypair::new();
    let p2 = Keypair::new();

    svm_locker
        .airdrop(&p1.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();
    svm_locker
        .airdrop(&p2.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let mint = Keypair::new();
    let mint_rent = 1461600;
    let create_mint_ix = system_instruction::create_account(
        &p1.pubkey(),
        &mint.pubkey(),
        mint_rent,
        82,
        &spl_token_2022_interface::id(),
    );

    let initialize_mint_ix = spl_token_2022_interface::instruction::initialize_mint2(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &p1.pubkey(),
        Some(&p1.pubkey()),
        2,
    )
    .unwrap();

    let at1 = spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
        &p1.pubkey(),
        &mint.pubkey(),
        &spl_token_2022_interface::id(),
    );
    let at2 = spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
        &p2.pubkey(),
        &mint.pubkey(),
        &spl_token_2022_interface::id(),
    );

    let create_at1_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &p1.pubkey(),
            &p1.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_at2_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &p1.pubkey(),
            &p2.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let mint_amount = 100_00;
    let mint_to_ix = spl_token_2022_interface::instruction::mint_to(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &at1,
        &p1.pubkey(),
        &[&p1.pubkey()],
        mint_amount,
    )
    .unwrap();

    let setup_instructions = vec![
        create_mint_ix,
        initialize_mint_ix,
        create_at1_ix,
        create_at2_ix,
        mint_to_ix,
    ];

    let setup_message =
        Message::new_with_blockhash(&setup_instructions, Some(&p1.pubkey()), &recent_blockhash);

    let setup_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(setup_message), &[&p1, &mint])
            .unwrap();

    let status_tx = crossbeam_unbounded::<TransactionStatusEvent>().0;
    svm_locker
        .process_transaction(&None, setup_tx, status_tx, false, true)
        .await
        .unwrap();

    let alt_key = Pubkey::new_unique();

    let address_lookup_table_account = AddressLookupTableAccount {
        key: alt_key,
        addresses: vec![at1, at2, spl_token_2022_interface::id(), mint.pubkey()],
    };

    println!(
        "addresses present on the ALT: {:?}",
        address_lookup_table_account.addresses
    );

    let alt_account_data = AddressLookupTable {
        meta: LookupTableMeta {
            authority: Some(p1.pubkey()),
            ..Default::default()
        },
        addresses: address_lookup_table_account.addresses.clone().into(),
    };

    svm_locker.with_svm_writer(|svm| {
        let alt_data = alt_account_data.serialize_for_tests().unwrap();
        let alt_account = solana_account::Account {
            lamports: 1000000,
            data: alt_data,
            owner: solana_address_lookup_table_interface::program::id(),
            executable: false,
            rent_epoch: 0,
        };

        svm.set_account(&alt_key, alt_account).unwrap();
    });

    let transfer_amount = 50_00;
    let transfer_ix = spl_token_2022_interface::instruction::transfer_checked(
        &spl_token_2022_interface::id(),
        &at1,
        &mint.pubkey(),
        &at2,
        &p1.pubkey(),
        &[&p1.pubkey()],
        transfer_amount,
        2,
    )
    .unwrap();

    let alt_message = v0::Message::try_compile(
        &p1.pubkey(),
        &[transfer_ix],
        &[address_lookup_table_account.clone()],
        recent_blockhash,
    )
    .expect("Failed to compile ALT message");

    let alt_tx = VersionedTransaction::try_new(VersionedMessage::V0(alt_message.clone()), &[&p1])
        .expect("Failed to create ALT transaction");

    let binding = svm_locker
        .profile_transaction(&None, alt_tx.clone(), None)
        .await
        .unwrap();
    let profile_result_uuid = binding.inner();

    let profile_result = svm_locker
        .get_profile_result(
            UuidOrSignature::Uuid(*profile_result_uuid),
            &RpcProfileResultConfig::default(),
        )
        .unwrap()
        .unwrap();
    let ix_profiles = profile_result
        .instruction_profiles
        .as_ref()
        .expect("instruction profiles should exist");
    assert_eq!(
        ix_profiles.len(),
        1,
        "ALT transfer should have one instruction"
    );
    let ix_profile = ix_profiles.get(0).unwrap();
    assert!(
        ix_profile.error_message.is_none(),
        "Profile should succeed, found error: {:?}",
        ix_profile.error_message.as_ref().unwrap()
    );
    assert!(
        ix_profile.account_states.get(&alt_key).is_none(),
        "ALT account should not be in instruction account states"
    );
    assert!(
        profile_result
            .readonly_account_states
            .get(&alt_key)
            .is_none(),
        "ALT account should not be in readonly account states"
    );

    let table = alt_message
        .address_table_lookups
        .first()
        .expect("ALT lookups should exist");
    let expected_loaded_writable: Vec<Pubkey> = table
        .writable_indexes
        .iter()
        .map(|&i| address_lookup_table_account.addresses[i as usize])
        .collect();
    let expected_loaded_readonly: Vec<Pubkey> = table
        .readonly_indexes
        .iter()
        .map(|&i| address_lookup_table_account.addresses[i as usize])
        .collect();

    for pk in &expected_loaded_writable {
        match ix_profile
            .account_states
            .get(pk)
            .expect("loaded writable address must be present")
        {
            UiAccountProfileState::Writable(_) => {}
            other => panic!(
                "expected Writable for loaded writable address {}, got {:?}",
                pk, other
            ),
        }
    }
    for pk in &expected_loaded_readonly {
        match ix_profile
            .account_states
            .get(pk)
            .expect("loaded readonly address must be present")
        {
            UiAccountProfileState::Readonly => {}
            other => panic!(
                "expected Readonly for loaded readonly address {}, got {:?}",
                pk, other
            ),
        }
    }

    let account_states = ix_profile.account_states.clone();

    let UiAccountProfileState::Readonly = account_states
        .get(&spl_token_2022_interface::id())
        .expect("token-2022 program should be present")
    else {
        panic!("expected token-2022 program to be Readonly");
    };

    let UiAccountProfileState::Readonly = account_states
        .get(&mint.pubkey())
        .expect("mint should be present")
    else {
        panic!("expected mint to be Readonly");
    };

    let UiAccountProfileState::Writable(src_change) = account_states
        .get(&at1)
        .expect("source ATA should be present")
    else {
        panic!("expected source ATA to be Writable");
    };
    match src_change {
        UiAccountChange::Update(before, after) => {
            assert_ne!(
                before.data, after.data,
                "token data should change on source"
            );
        }
        _ => panic!("expected Update for source ATA"),
    }

    let UiAccountProfileState::Writable(dst_change) = account_states
        .get(&at2)
        .expect("destination ATA should be present")
    else {
        panic!("expected destination ATA to be Writable");
    };
    match dst_change {
        UiAccountChange::Update(before, after) => {
            assert_ne!(
                before.data, after.data,
                "token data should change on destination"
            );
        }
        _ => panic!("expected Update for destination ATA"),
    }
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn it_should_delete_accounts_with_no_lamports(test_type: TestType) {
    let (svm_locker, _simnet_cmd_tx, _simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);
    let p1 = Keypair::new();
    let p2 = Keypair::new();

    svm_locker
        .airdrop(&p1.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let message = Message::new_with_blockhash(
        &[system_instruction::transfer(
            &p1.pubkey(),
            &p2.pubkey(),
            LAMPORTS_PER_SOL - 5000,
        )],
        Some(&p1.pubkey()),
        &recent_blockhash,
    );
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&p1]).unwrap();

    let (status_tx, rx) = unbounded();
    let _ = svm_locker
        .process_transaction(&None, tx, status_tx, true, false)
        .await
        .unwrap();

    #[allow(clippy::never_loop)]
    loop {
        match rx.recv() {
            Ok(status) => {
                println!("Transaction status: {:?}", status);
                break;
            }
            Err(_) => panic!("status channel closed unexpectedly"),
        }
    }

    assert!(
        svm_locker.get_account_local(&p1.pubkey()).inner.is_none(),
        "Account should be deleted"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_compute_budget_profiling(test_type: TestType) {
    let (svm_locker, _simnet_cmd_tx, _simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);
    let p1 = Keypair::new();
    let p2 = Keypair::new();

    svm_locker
        .airdrop(&p1.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let message = Message::new_with_blockhash(
        &[
            ComputeBudgetInstruction::set_compute_unit_limit(1_000_000),
            ComputeBudgetInstruction::set_compute_unit_price(1),
            system_instruction::transfer(&p1.pubkey(), &p2.pubkey(), LAMPORTS_PER_SOL),
        ],
        Some(&p1.pubkey()),
        &recent_blockhash,
    );
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&p1]).unwrap();

    let uuid = svm_locker
        .profile_transaction(&None, tx, None)
        .await
        .unwrap()
        .inner;
    let profile_result = svm_locker
        .get_profile_result(
            UuidOrSignature::Uuid(uuid),
            &RpcProfileResultConfig::default(),
        )
        .unwrap()
        .unwrap();

    let ix_profile = profile_result.instruction_profiles.unwrap();
    assert_eq!(ix_profile.len(), 3, "Should have 3 instruction profiles");

    let ix = &ix_profile[0];
    assert!(
        ix.error_message.is_none(),
        "Expected no error for instruction, found {}",
        ix.error_message.as_ref().unwrap()
    );
    assert_eq!(ix.compute_units_consumed, 150);

    let ix = &ix_profile[1];
    assert!(
        ix.error_message.is_none(),
        "Expected no error for instruction, found {}",
        ix.error_message.as_ref().unwrap()
    );
    assert_eq!(ix.compute_units_consumed, 150);

    let ix = &ix_profile[1];
    assert!(
        ix.error_message.is_none(),
        "Expected no error for instruction, found {}",
        ix.error_message.as_ref().unwrap()
    );
    assert_eq!(ix.compute_units_consumed, 150);
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_reset_account(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);
    let p1 = Keypair::new();
    println!("P1 pubkey: {}", p1.pubkey());
    svm_locker
        .airdrop(&p1.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap(); // account is created in the SVM.unwrap()
    println!("Airdropped SOL to p1");

    println!(
        "Account before reset: {:?}",
        svm_locker.get_account_local(&p1.pubkey()).inner
    );

    svm_locker.reset_account(p1.pubkey(), false).unwrap();

    println!("Reset account");

    println!(
        "Account deleted: {:?}",
        svm_locker.get_account_local(&p1.pubkey()).inner
    );

    assert!(
        svm_locker.get_account_local(&p1.pubkey()).inner.is_none(),
        "Account should be deleted"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_reset_account_cascade(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Create owner account and owned account
    let owner = Pubkey::new_unique();
    let owned = Pubkey::new_unique();

    let owner_account = Account {
        lamports: 10 * LAMPORTS_PER_SOL,
        data: vec![0x01, 0x02],
        owner: solana_sdk_ids::system_program::id(),
        executable: false,
        rent_epoch: 0,
    };

    let owned_account = Account {
        lamports: 5 * LAMPORTS_PER_SOL,
        data: vec![0x03, 0x04],
        owner, // Owned by the first account
        executable: false,
        rent_epoch: 0,
    };

    // Insert accounts
    svm_locker
        .with_svm_writer(|svm_writer| {
            svm_writer.set_account(&owner, owner_account).unwrap();
            svm_writer.set_account(&owned, owned_account).unwrap();
            Ok::<(), SurfpoolError>(())
        })
        .unwrap();

    // Verify accounts exist
    assert!(!svm_locker.get_account_local(&owner).inner.is_none());
    assert!(!svm_locker.get_account_local(&owned).inner.is_none());

    // Reset with cascade=true (for regular accounts, doesn't cascade but tests the code path)
    svm_locker.reset_account(owner, true).unwrap();

    // Owner is deleted, owned account is deleted
    assert!(svm_locker.get_account_local(&owner).inner.is_none());
    assert!(svm_locker.get_account_local(&owned).inner.is_none());

    // Clean up
    svm_locker.reset_account(owned, false).unwrap();
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_reset_streamed_account(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);
    let p1 = Keypair::new();
    println!("P1 pubkey: {}", p1.pubkey());
    svm_locker
        .airdrop(&p1.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap(); // account is created in the SVM.unwrap()
    println!("Airdropped SOL to p1");

    let _ = svm_locker.confirm_current_block(&None).await;
    // Account still exists
    assert!(!svm_locker.get_account_local(&p1.pubkey()).inner.is_none());

    svm_locker.stream_account(p1.pubkey(), false).unwrap();

    let _ = svm_locker.confirm_current_block(&None).await;
    // Account is cleaned up as soon as the block is processed
    assert!(
        svm_locker.get_account_local(&p1.pubkey()).inner.is_none(),
        "Streamed account should be deleted"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_reset_streamed_account_cascade(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Create owner account and owned account
    let owner = Pubkey::new_unique();
    let owned = Pubkey::new_unique();

    let owner_account = Account {
        lamports: 10 * LAMPORTS_PER_SOL,
        data: vec![0x01, 0x02],
        owner: solana_sdk_ids::system_program::id(),
        executable: false,
        rent_epoch: 0,
    };

    let owned_account = Account {
        lamports: 5 * LAMPORTS_PER_SOL,
        data: vec![0x03, 0x04],
        owner, // Owned by the first account
        executable: false,
        rent_epoch: 0,
    };

    // Insert accounts
    svm_locker
        .with_svm_writer(|svm_writer| {
            svm_writer.set_account(&owner, owner_account).unwrap();
            svm_writer.set_account(&owned, owned_account).unwrap();
            Ok::<(), SurfpoolError>(())
        })
        .unwrap();

    // Verify accounts exist
    assert!(!svm_locker.get_account_local(&owner).inner.is_none());
    assert!(!svm_locker.get_account_local(&owned).inner.is_none());

    let _ = svm_locker.confirm_current_block(&None).await;
    // Accounts still exists
    assert!(!svm_locker.get_account_local(&owner).inner.is_none());
    assert!(!svm_locker.get_account_local(&owned).inner.is_none());

    svm_locker.stream_account(owner, true).unwrap();
    let _ = svm_locker.confirm_current_block(&None).await;

    // Owner is deleted, owned account is deleted
    assert!(svm_locker.get_account_local(&owner).inner.is_none());
    assert!(svm_locker.get_account_local(&owned).inner.is_none());
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_stream_accounts_multiple(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let p1 = Keypair::new();
    let p2 = Keypair::new();
    let p3 = Keypair::new();

    // Airdrop to all three accounts
    for kp in [&p1, &p2, &p3] {
        svm_locker
            .airdrop(&kp.pubkey(), LAMPORTS_PER_SOL)
            .unwrap()
            .unwrap();
    }

    let _ = svm_locker.confirm_current_block(&None).await;

    // All accounts exist
    assert!(!svm_locker.get_account_local(&p1.pubkey()).inner.is_none());
    assert!(!svm_locker.get_account_local(&p2.pubkey()).inner.is_none());
    assert!(!svm_locker.get_account_local(&p3.pubkey()).inner.is_none());

    // Stream all three accounts at once
    for kp in [&p1, &p2, &p3] {
        svm_locker.stream_account(kp.pubkey(), false).unwrap();
    }

    let _ = svm_locker.confirm_current_block(&None).await;

    // All accounts should be evicted
    assert!(
        svm_locker.get_account_local(&p1.pubkey()).inner.is_none(),
        "First streamed account should be deleted"
    );
    assert!(
        svm_locker.get_account_local(&p2.pubkey()).inner.is_none(),
        "Second streamed account should be deleted"
    );
    assert!(
        svm_locker.get_account_local(&p3.pubkey()).inner.is_none(),
        "Third streamed account should be deleted"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_stream_accounts_with_cascade(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Create two owners each with an owned account
    let owner1 = Pubkey::new_unique();
    let owned1 = Pubkey::new_unique();
    let owner2 = Pubkey::new_unique();
    let owned2 = Pubkey::new_unique();

    svm_locker
        .with_svm_writer(|svm_writer| {
            svm_writer
                .set_account(
                    &owner1,
                    Account {
                        lamports: 10 * LAMPORTS_PER_SOL,
                        data: vec![0x01],
                        owner: solana_sdk_ids::system_program::id(),
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            svm_writer
                .set_account(
                    &owned1,
                    Account {
                        lamports: 5 * LAMPORTS_PER_SOL,
                        data: vec![0x02],
                        owner: owner1,
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            svm_writer
                .set_account(
                    &owner2,
                    Account {
                        lamports: 10 * LAMPORTS_PER_SOL,
                        data: vec![0x03],
                        owner: solana_sdk_ids::system_program::id(),
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            svm_writer
                .set_account(
                    &owned2,
                    Account {
                        lamports: 5 * LAMPORTS_PER_SOL,
                        data: vec![0x04],
                        owner: owner2,
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            Ok::<(), SurfpoolError>(())
        })
        .unwrap();

    // Verify all accounts exist
    assert!(!svm_locker.get_account_local(&owner1).inner.is_none());
    assert!(!svm_locker.get_account_local(&owned1).inner.is_none());
    assert!(!svm_locker.get_account_local(&owner2).inner.is_none());
    assert!(!svm_locker.get_account_local(&owned2).inner.is_none());

    let _ = svm_locker.confirm_current_block(&None).await;

    // Stream both owners with cascade
    svm_locker.stream_account(owner1, true).unwrap();
    svm_locker.stream_account(owner2, true).unwrap();

    let _ = svm_locker.confirm_current_block(&None).await;

    // All four accounts should be evicted
    assert!(
        svm_locker.get_account_local(&owner1).inner.is_none(),
        "First owner should be deleted"
    );
    assert!(
        svm_locker.get_account_local(&owned1).inner.is_none(),
        "First owned account should be deleted"
    );
    assert!(
        svm_locker.get_account_local(&owner2).inner.is_none(),
        "Second owner should be deleted"
    );
    assert!(
        svm_locker.get_account_local(&owned2).inner.is_none(),
        "Second owned account should be deleted"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_stream_accounts_empty(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let p1 = Keypair::new();
    svm_locker
        .airdrop(&p1.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let _ = svm_locker.confirm_current_block(&None).await;
    assert!(!svm_locker.get_account_local(&p1.pubkey()).inner.is_none());

    // Streaming zero accounts should not error and should not affect existing accounts
    let _ = svm_locker.confirm_current_block(&None).await;

    assert!(
        !svm_locker.get_account_local(&p1.pubkey()).inner.is_none(),
        "Existing account should not be affected when no accounts are streamed"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_reset_network(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Create owner account and owned account
    let owner = Pubkey::new_unique();
    let owned = Pubkey::new_unique();

    let owner_account = Account {
        lamports: 10 * LAMPORTS_PER_SOL,
        data: vec![0x01, 0x02],
        owner: solana_sdk_ids::system_program::id(),
        executable: false,
        rent_epoch: 0,
    };

    let owned_account = Account {
        lamports: 5 * LAMPORTS_PER_SOL,
        data: vec![0x03, 0x04],
        owner, // Owned by the first account
        executable: false,
        rent_epoch: 0,
    };

    // Insert accounts
    svm_locker
        .with_svm_writer(|svm_writer| {
            svm_writer.set_account(&owner, owner_account).unwrap();
            svm_writer.set_account(&owned, owned_account).unwrap();
            Ok::<(), SurfpoolError>(())
        })
        .unwrap();

    // Verify accounts exist
    assert!(!svm_locker.get_account_local(&owner).inner.is_none());
    assert!(!svm_locker.get_account_local(&owned).inner.is_none());

    // Reset with cascade=true (for regular accounts, doesn't cascade but tests the code path)
    hiro_system_kit::nestable_block_on(svm_locker.reset_network(&None)).unwrap();

    // Owner is deleted, owned account is deleted
    assert!(svm_locker.get_account_local(&owner).inner.is_none());
    assert!(svm_locker.get_account_local(&owned).inner.is_none());

    // Clean up
    svm_locker.reset_account(owned, false).unwrap();
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_reset_network_keeps_latest_blockhash_valid(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    hiro_system_kit::nestable_block_on(svm_locker.reset_network(&None)).unwrap();

    let epoch_schedule =
        svm_locker.with_svm_reader(|svm_reader| svm_reader.inner.get_sysvar::<EpochSchedule>());
    let (genesis_slot, latest_slot) = svm_locker.with_svm_reader(|svm_reader| {
        (
            svm_reader.genesis_slot,
            svm_reader.latest_epoch_info.absolute_slot,
        )
    });
    assert_eq!(genesis_slot, FINALIZATION_SLOT_THRESHOLD);
    assert_eq!(latest_slot, FINALIZATION_SLOT_THRESHOLD);
    assert_eq!(epoch_schedule, EpochSchedule::without_warmup());

    let latest_blockhash = svm_locker.with_svm_reader(|svm_reader| svm_reader.latest_blockhash());
    let is_recent = svm_locker
        .with_svm_reader(|svm_reader| svm_reader.check_blockhash_is_recent(&latest_blockhash));
    assert!(
        is_recent,
        "latest_blockhash returned after reset should be present in RecentBlockhashes sysvar",
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_reset_network_time_travel_timestamp(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_locker, simnet_cmd_tx, simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Calculate a target timestamp in the future
    let seven_days = 7 * 24 * 60 * 60 * 1000;
    let target_timestamp = svm_locker.0.blocking_read().updated_at + seven_days;

    // First time travel to target timestamp
    // Note: time_travel now uses confirmation mechanism, so it waits internally
    let time_travel_response: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteTimestamp(target_timestamp)),
    );
    assert!(
        time_travel_response.is_ok(),
        "First time travel should succeed"
    );

    // Reset network
    let reset_response: JsonRpcResult<RpcResponse<()>> =
        hiro_system_kit::nestable_block_on(rpc_server.reset_network(Some(runloop_context.clone())));
    assert!(reset_response.is_ok(), "Reset network should succeed");

    // Second time travel to the same timestamp should now succeed after reset
    // because updated_at was reset to current time
    let time_travel_response2: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteTimestamp(target_timestamp)),
    );
    assert!(
        time_travel_response2.is_ok(),
        "Second time travel should succeed after reset. Error: {:?}",
        time_travel_response2.err()
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_reset_network_time_travel_slot(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_locker, simnet_cmd_tx, simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Do an initial reset to ensure we start from the offline baseline slot
    let initial_reset: JsonRpcResult<RpcResponse<()>> =
        hiro_system_kit::nestable_block_on(rpc_server.reset_network(Some(runloop_context.clone())));
    assert!(initial_reset.is_ok(), "Initial reset should succeed");

    // Target slot to time travel to (must be greater than the reset slot)
    let target_slot = 1000;

    // First time travel to target slot
    // Note: time_travel now uses confirmation mechanism, so it waits internally
    let time_travel_response: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteSlot(target_slot)),
    );
    assert!(
        time_travel_response.is_ok(),
        "First time travel should succeed"
    );

    // Reset network
    let reset_response: JsonRpcResult<RpcResponse<()>> =
        hiro_system_kit::nestable_block_on(rpc_server.reset_network(Some(runloop_context.clone())));
    assert!(reset_response.is_ok(), "Reset network should succeed");

    // Second time travel to the same slot should now succeed after reset
    // because latest_epoch_info.absolute_slot was reset to the offline baseline
    let time_travel_response2: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteSlot(target_slot)),
    );
    assert!(
        time_travel_response2.is_ok(),
        "Second time travel should succeed after reset. Error: {:?}",
        time_travel_response2.err()
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
fn test_reset_network_time_travel_epoch(test_type: TestType) {
    let rpc_server = SurfnetCheatcodesRpc::empty();
    let (svm_locker, simnet_cmd_tx, simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Do an initial reset to ensure we start from epoch 0
    let initial_reset: JsonRpcResult<RpcResponse<()>> =
        hiro_system_kit::nestable_block_on(rpc_server.reset_network(Some(runloop_context.clone())));
    assert!(initial_reset.is_ok(), "Initial reset should succeed");

    // Target epoch to time travel to (must be greater than 0 after reset)
    let target_epoch = 5;

    // First time travel to target epoch
    let time_travel_response: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteEpoch(target_epoch)),
    );
    // Note: time_travel now uses confirmation mechanism, so it waits internally
    assert!(
        time_travel_response.is_ok(),
        "First time travel should succeed"
    );

    // Reset network
    let reset_response: JsonRpcResult<RpcResponse<()>> =
        hiro_system_kit::nestable_block_on(rpc_server.reset_network(Some(runloop_context.clone())));
    assert!(reset_response.is_ok(), "Reset network should succeed");

    // Second time travel to the same epoch should now succeed after reset
    // because latest_epoch_info.epoch was reset to 0
    let time_travel_response2: JsonRpcResult<EpochInfo> = rpc_server.time_travel(
        Some(runloop_context.clone()),
        Some(TimeTravelConfig::AbsoluteEpoch(target_epoch)),
    );
    assert!(
        time_travel_response2.is_ok(),
        "Second time travel should succeed after reset. Error: {:?}",
        time_travel_response2.err()
    );
}

fn start_surfnet(
    airdrop_addresses: Vec<Pubkey>,
    datasource_rpc_url: Option<String>,
    test_type: TestType,
) -> Result<(String, SurfnetSvmLocker), String> {
    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();
    let offline_mode = datasource_rpc_url.is_none();

    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            airdrop_addresses,
            airdrop_token_amount: LAMPORTS_PER_SOL,
            offline_mode,
            remote_rpc_url: datasource_rpc_url,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();
    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);
    let svm_locker_cc: SurfnetSvmLocker = svm_locker.clone();

    let _handle = std::thread::spawn(move || {
        let future = start_local_surfnet_runloop(
            svm_locker_cc,
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });

    let mut ready = false;
    // don't wait for connection in offline mode
    let mut connected = offline_mode;
    loop {
        match simnet_events_rx.recv() {
            Ok(SimnetEvent::Ready(_)) => {
                ready = true;
            }
            Ok(SimnetEvent::Connected(_)) => {
                connected = true;
            }
            _ => (),
        }
        if ready && connected {
            break;
        }
    }

    Ok((format!("http://{}:{}", bind_host, bind_port), svm_locker))
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[tokio::test(flavor = "multi_thread")]
async fn test_closed_accounts(test_type: TestType) {
    let keypair = Keypair::new();
    let pubkey = keypair.pubkey();
    let another_test_type = match &test_type {
        TestType::OnDiskSqlite(_) => TestType::sqlite(),
        TestType::InMemorySqlite => TestType::in_memory(),
        TestType::NoDb => TestType::no_db(),
        #[cfg(feature = "postgres")]
        TestType::Postgres { url, .. } => TestType::Postgres {
            url: url.clone(),
            surfnet_id: crate::storage::tests::random_surfnet_id(),
        },
    };
    // Start datasource surfnet first, which will only have accounts we airdrop to
    let (datasource_surfnet_url, _datasource_svm_locker) =
        start_surfnet(vec![pubkey], None, test_type).expect("Failed to start datasource surfnet");
    println!("Datasource surfnet started at {}", datasource_surfnet_url);

    // Now start the test surfnet which forks the datasource surfnet
    let (surfnet_url, surfnet_svm_locker) =
        start_surfnet(vec![], Some(datasource_surfnet_url), another_test_type)
            .expect("Failed to start surfnet");
    println!("Surfnet started at {}", surfnet_url);

    let rpc_client = RpcClient::new(surfnet_url);

    // Verify that when we fetch our account from the surfnet, it will fetch it from the datasource surfnet
    {
        let account = rpc_client
            .get_account(&pubkey)
            .await
            .expect("Failed to get account from surfnet");
        assert_eq!(
            account.lamports, LAMPORTS_PER_SOL,
            "Account lamports should match airdrop amount"
        );
        println!("Account fetched successfully from datasource surfnet");
    }

    // Verify that if we send the `reset_account` cheatcode, the account will no longer exist locally, but will be fetched from the datasource surfnet again
    {
        let _: serde_json::Value = rpc_client
            .send(
                solana_client::rpc_request::RpcRequest::Custom {
                    method: "surfnet_resetAccount",
                },
                json!([pubkey.to_string()]),
            )
            .await
            .expect("Failed to reset account");

        assert!(
            surfnet_svm_locker
                .get_account_local(&pubkey)
                .inner
                .is_none(),
            "Account should be deleted locally after reset_account"
        );

        let account = rpc_client
            .get_account(&pubkey)
            .await
            .expect("Failed to get account from surfnet after reset_account");
        assert_eq!(
            account.lamports, LAMPORTS_PER_SOL,
            "Account should be re-fetched from remote after reset_account"
        );
        println!("Account re-fetched successfully from datasource surfnet after reset_account");
    }

    // Verify that if we send a transaction that closes the account, the account is deleted locally and will not be re-fetched from the datasource surfnet
    {
        let recent_blockhash = rpc_client
            .get_latest_blockhash()
            .await
            .expect("Failed to get latest blockhash");

        let recipient = Pubkey::new_unique();
        let close_ix = system_instruction::transfer(&pubkey, &recipient, LAMPORTS_PER_SOL - 5000);

        println!(
            "Sending {} from {} to {}",
            LAMPORTS_PER_SOL - 5000,
            pubkey,
            recipient
        );
        let message = Message::new_with_blockhash(&[close_ix], Some(&pubkey), &recent_blockhash);
        let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&keypair])
            .expect("Failed to create transaction");

        let _sig = rpc_client
            .send_and_confirm_transaction(&tx)
            .await
            .expect("Failed to send and confirm transaction");

        let tx = rpc_client
            .get_transaction(
                &_sig,
                solana_transaction_status::UiTransactionEncoding::JsonParsed,
            )
            .await
            .expect("Failed to get transaction");

        println!("Transaction details: {:?}", tx);
        let _ = rpc_client
            .get_signature_status_with_commitment(&_sig, CommitmentConfig::finalized())
            .await
            .expect("Failed to get transaction status")
            .expect("Transaction status not found")
            .unwrap();

        assert!(
            surfnet_svm_locker
                .get_account_local(&pubkey)
                .inner
                .is_none(),
            "Account should be deleted locally after being closed"
        );

        println!("Fetching account after being closed...");
        let account_result = rpc_client.get_account(&pubkey).await;
        assert!(
            account_result.is_err(),
            "Account should not be re-fetched from remote after being closed; found {:?}",
            account_result.unwrap()
        );
        println!("Account successfully closed and not re-fetched from datasource surfnet");
    }
}

/// Regression test for #618: when a `getSignaturesForAddress` call against a forked surfnet uses
/// a pagination boundary (`before` / `until`) that references a transaction that exists only on
/// the local surfnet, surfpool used to forward the boundary unchanged to the upstream, which
/// either returned an error (strict providers) or silently mis-paginated (lenient providers
/// like surfpool itself).
///
/// To exercise the real `get_signatures_for_address_local_then_remote` glue, we spin up TWO
/// surfnets in this test: one acts as the upstream "datasource" and the other forks it. Both
/// surfnets receive airdrops for the same `target` pubkey; the datasource airdrops become
/// "remote-only" signatures from the local surfnet's perspective, and the local airdrops become
/// "local-only" signatures invisible to the datasource.
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[tokio::test(flavor = "multi_thread")]
async fn test_get_signatures_for_address_local_then_remote(test_type: TestType) {
    use solana_client::rpc_client::GetConfirmedSignaturesForAddress2Config;
    use solana_signature::Signature;

    // Each surfnet needs an isolated storage instance; clone the TestType variant just like
    // `test_closed_accounts` does so the two SVMs don't share a sqlite file or surfnet_id.
    let another_test_type = match &test_type {
        TestType::OnDiskSqlite(_) => TestType::sqlite(),
        TestType::InMemorySqlite => TestType::in_memory(),
        TestType::NoDb => TestType::no_db(),
        #[cfg(feature = "postgres")]
        TestType::Postgres { url, .. } => TestType::Postgres {
            url: url.clone(),
            surfnet_id: crate::storage::tests::random_surfnet_id(),
        },
    };

    let target = Pubkey::new_unique();

    // Step 1: bring up the datasource surfnet (offline; no upstream of its own) and seed it
    // with 3 airdrops for `target`. Each airdrop stores one signature referencing `target`.
    //
    // Note: litesvm's `airdrop` synthesises a `transfer(airdrop_kp, target, lamports)` tx and
    // signs over the *current* blockhash. With `slot_time = 1ms` consecutive airdrops can land
    // in the same slot, share the same blockhash, and — because Ed25519 signatures are
    // deterministic — collapse to the same signature. Varying `lamports` per call guarantees a
    // distinct message (and therefore a distinct signature) regardless of slot timing.
    let (datasource_url, _datasource_locker) =
        start_surfnet(vec![], None, test_type).expect("start datasource surfnet");
    let datasource_rpc = RpcClient::new(datasource_url.clone());
    let mut datasource_sigs: Vec<Signature> = Vec::new();
    for i in 0..3u64 {
        let sig = datasource_rpc
            .request_airdrop(&target, LAMPORTS_PER_SOL + i)
            .await
            .expect("airdrop on datasource");
        datasource_sigs.push(sig);
    }
    // `request_airdrop` returns sigs in creation order; `getSignaturesForAddress` is newest-first.
    datasource_sigs.reverse();
    assert_eq!(
        datasource_sigs
            .iter()
            .map(Signature::to_string)
            .collect::<std::collections::HashSet<_>>()
            .len(),
        datasource_sigs.len(),
        "datasource airdrops must produce distinct signatures"
    );

    // Step 2: bring up the local surfnet, configured to fork the datasource, and seed 2 LOCAL
    // airdrops for `target`. These signatures only ever land in the local surfnet's storage.
    let (local_url, _local_locker) = start_surfnet(vec![], Some(datasource_url), another_test_type)
        .expect("start local surfnet");
    let local_rpc = RpcClient::new(local_url);
    let mut local_sigs: Vec<Signature> = Vec::new();
    for i in 0..2u64 {
        let sig = local_rpc
            .request_airdrop(&target, LAMPORTS_PER_SOL + 100 + i)
            .await
            .expect("airdrop on local");
        local_sigs.push(sig);
    }
    local_sigs.reverse();
    assert_eq!(
        local_sigs
            .iter()
            .map(Signature::to_string)
            .collect::<std::collections::HashSet<_>>()
            .len(),
        local_sigs.len(),
        "local airdrops must produce distinct signatures"
    );
    // local_sigs[0] is the newer local signature; local_sigs[1] is the older one.

    // Scenario A: `before` is a local-only signature.
    // Pre-fix surfpool forwarded `before=local_sigs[0]` to the datasource, which had never seen
    // that signature — so the datasource's local lookup returned an empty window and the caller
    // saw only `[local_sigs[1]]` (or `-32603` against a strict provider). Post-fix, the local
    // boundary is dropped on the remote leg, so the upstream contributes its full 3 sigs.
    {
        let result = local_rpc
            .get_signatures_for_address_with_config(
                &target,
                GetConfirmedSignaturesForAddress2Config {
                    before: Some(local_sigs[0]),
                    ..Default::default()
                },
            )
            .await
            .expect("scenario A: getSignaturesForAddress(before=local) must succeed");
        let got: Vec<String> = result.iter().map(|s| s.signature.clone()).collect();
        let mut expected: Vec<String> = vec![local_sigs[1].to_string()];
        expected.extend(datasource_sigs.iter().map(Signature::to_string));
        assert_eq!(
            got, expected,
            "scenario A: expected [older-local, datasource-sigs...] when paginating past the newer local sig"
        );
    }

    // Scenario B: `until` is a local-only signature.
    // Pre-fix surfpool forwarded `until=local_sigs[1]` to the datasource, which didn't recognise
    // it and so returned its FULL signature list — leaking 3 datasource sigs the caller never
    // wanted. Post-fix, the entire remote call is skipped because every remote signature is
    // older than the (local) boundary by construction.
    {
        let result = local_rpc
            .get_signatures_for_address_with_config(
                &target,
                GetConfirmedSignaturesForAddress2Config {
                    until: Some(local_sigs[1]),
                    ..Default::default()
                },
            )
            .await
            .expect("scenario B: getSignaturesForAddress(until=local) must succeed");
        let got: Vec<String> = result.iter().map(|s| s.signature.clone()).collect();
        assert_eq!(
            got,
            vec![local_sigs[0].to_string()],
            "scenario B: a local `until` must skip the remote leg entirely"
        );
    }

    // Scenario C: limit truncation across the local/remote boundary.
    // The fix caps the remote leg at `limit - local_count` and truncates the combined result.
    // Pre-fix the remote leg used the caller's full `limit` and nothing truncated the union, so
    // a caller asking for 3 received `local_count + limit` = 2 + 3 = 5 signatures.
    {
        let result = local_rpc
            .get_signatures_for_address_with_config(
                &target,
                GetConfirmedSignaturesForAddress2Config {
                    limit: Some(3),
                    ..Default::default()
                },
            )
            .await
            .expect("scenario C: getSignaturesForAddress(limit=3) must succeed");
        assert_eq!(
            result.len(),
            3,
            "scenario C: combined result must respect the caller's limit"
        );
        let got: Vec<String> = result.iter().map(|s| s.signature.clone()).collect();
        let expected = vec![
            local_sigs[0].to_string(),
            local_sigs[1].to_string(),
            datasource_sigs[0].to_string(),
        ];
        assert_eq!(got, expected, "scenario C: unexpected merged ordering");
    }

    // Scenario D (sanity): no boundary — local sigs come first, then the datasource sigs.
    {
        let result = local_rpc
            .get_signatures_for_address(&target)
            .await
            .expect("scenario D: getSignaturesForAddress(no config) must succeed");
        let got: Vec<String> = result.iter().map(|s| s.signature.clone()).collect();
        let mut expected: Vec<String> = local_sigs.iter().map(Signature::to_string).collect();
        expected.extend(datasource_sigs.iter().map(Signature::to_string));
        assert_eq!(
            got, expected,
            "scenario D: local sigs must precede datasource sigs in the merged stream"
        );
    }

    // Scenario E (sanity): `before` is a DATASOURCE signature, not a local one.
    // The fix must forward the boundary to the remote unchanged in this case.
    {
        let result = local_rpc
            .get_signatures_for_address_with_config(
                &target,
                GetConfirmedSignaturesForAddress2Config {
                    before: Some(datasource_sigs[0]),
                    ..Default::default()
                },
            )
            .await
            .expect("scenario E: getSignaturesForAddress(before=datasource) must succeed");
        let got: Vec<String> = result.iter().map(|s| s.signature.clone()).collect();
        let expected: Vec<String> = datasource_sigs[1..]
            .iter()
            .map(Signature::to_string)
            .collect();
        assert_eq!(
            got, expected,
            "scenario E: a non-local `before` must be forwarded to the remote unchanged"
        );
    }
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[tokio::test(flavor = "multi_thread")]
async fn test_offline_account_including_owned_accounts(test_type: TestType) {
    let owner = Pubkey::new_unique();
    let owned = Pubkey::new_unique();
    let another_test_type = match &test_type {
        TestType::OnDiskSqlite(_) => TestType::sqlite(),
        TestType::InMemorySqlite => TestType::in_memory(),
        TestType::NoDb => TestType::no_db(),
        #[cfg(feature = "postgres")]
        TestType::Postgres { url, .. } => TestType::Postgres {
            url: url.clone(),
            surfnet_id: crate::storage::tests::random_surfnet_id(),
        },
    };

    let (datasource_surfnet_url, datasource_svm_locker) =
        start_surfnet(vec![], None, test_type).expect("Failed to start datasource surfnet");

    datasource_svm_locker
        .with_svm_writer(|svm_writer| {
            svm_writer
                .set_account(
                    &owner,
                    Account {
                        lamports: LAMPORTS_PER_SOL,
                        data: vec![1, 2, 3],
                        owner: system_program::id(),
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            svm_writer
                .set_account(
                    &owned,
                    Account {
                        lamports: LAMPORTS_PER_SOL / 2,
                        data: vec![4, 5, 6],
                        owner,
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            Ok::<(), SurfpoolError>(())
        })
        .expect("Failed to seed datasource accounts");

    let (surfnet_url, surfnet_svm_locker) =
        start_surfnet(vec![], Some(datasource_surfnet_url), another_test_type)
            .expect("Failed to start surfnet");
    let rpc_client = RpcClient::new(surfnet_url);

    let _: serde_json::Value = rpc_client
        .send(
            solana_client::rpc_request::RpcRequest::Custom {
                method: "surfnet_offlineAccount",
            },
            serde_json::json!([owner.to_string(), { "includeOwnedAccounts": true }]),
        )
        .await
        .expect("Failed to set account offline");

    assert!(
        surfnet_svm_locker.is_account_offline(&owner),
        "Owner should be recorded as offline"
    );
    assert!(
        surfnet_svm_locker
            .get_offline_account_owners()
            .contains(&owner),
        "Owner should be recorded as a offline account owner"
    );

    let owner_result = rpc_client.get_account(&owner).await;
    assert!(
        owner_result.is_err(),
        "Offline owner account should not be fetched from remote"
    );
    assert!(
        surfnet_svm_locker.get_account_local(&owner).inner.is_none(),
        "Offline owner account should remain absent locally"
    );

    let owned_result = rpc_client.get_account(&owned).await;
    assert!(
        owned_result.is_err(),
        "Owned account should not be fetched from remote once marked offline"
    );
    assert!(
        surfnet_svm_locker.get_account_local(&owned).inner.is_none(),
        "Offline owned account should remain absent locally"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[tokio::test(flavor = "multi_thread")]
async fn test_offline_account_without_owned_accounts(test_type: TestType) {
    let owner = Pubkey::new_unique();
    let owned = Pubkey::new_unique();
    let another_test_type = match &test_type {
        TestType::OnDiskSqlite(_) => TestType::sqlite(),
        TestType::InMemorySqlite => TestType::in_memory(),
        TestType::NoDb => TestType::no_db(),
        #[cfg(feature = "postgres")]
        TestType::Postgres { url, .. } => TestType::Postgres {
            url: url.clone(),
            surfnet_id: crate::storage::tests::random_surfnet_id(),
        },
    };

    let (datasource_surfnet_url, datasource_svm_locker) =
        start_surfnet(vec![], None, test_type).expect("Failed to start datasource surfnet");

    datasource_svm_locker
        .with_svm_writer(|svm_writer| {
            svm_writer
                .set_account(
                    &owner,
                    Account {
                        lamports: LAMPORTS_PER_SOL,
                        data: vec![1, 2, 3],
                        owner: system_program::id(),
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            svm_writer
                .set_account(
                    &owned,
                    Account {
                        lamports: LAMPORTS_PER_SOL / 2,
                        data: vec![4, 5, 6],
                        owner,
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            Ok::<(), SurfpoolError>(())
        })
        .expect("Failed to seed datasource accounts");

    let (surfnet_url, surfnet_svm_locker) =
        start_surfnet(vec![], Some(datasource_surfnet_url), another_test_type)
            .expect("Failed to start surfnet");
    let rpc_client = RpcClient::new(surfnet_url);

    // Mark owner offline WITHOUT includeOwnedAccounts
    let _: serde_json::Value = rpc_client
        .send(
            solana_client::rpc_request::RpcRequest::Custom {
                method: "surfnet_offlineAccount",
            },
            serde_json::json!([owner.to_string()]),
        )
        .await
        .expect("Failed to set account offline");

    assert!(
        surfnet_svm_locker.is_account_offline(&owner),
        "Owner should be recorded as offline"
    );
    assert!(
        !surfnet_svm_locker
            .get_offline_account_owners()
            .contains(&owner),
        "Owner should NOT be in offline account owners (includeOwnedAccounts=false)"
    );

    // Offline account itself cannot be fetched from remote
    let owner_result = rpc_client.get_account(&owner).await;
    assert!(
        owner_result.is_err(),
        "Offline owner account should not be fetched from remote"
    );

    // Account owned by the offline owner CAN still be fetched
    let owned_result = rpc_client.get_account(&owned).await;
    assert!(
        owned_result.is_ok(),
        "Owned account should still be fetchable when owner blocking is not active"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[tokio::test(flavor = "multi_thread")]
async fn test_reset_account_after_offline_restores(test_type: TestType) {
    let account = Pubkey::new_unique();
    let another_test_type = match &test_type {
        TestType::OnDiskSqlite(_) => TestType::sqlite(),
        TestType::InMemorySqlite => TestType::in_memory(),
        TestType::NoDb => TestType::no_db(),
        #[cfg(feature = "postgres")]
        TestType::Postgres { url, .. } => TestType::Postgres {
            url: url.clone(),
            surfnet_id: crate::storage::tests::random_surfnet_id(),
        },
    };

    let (datasource_surfnet_url, datasource_svm_locker) =
        start_surfnet(vec![], None, test_type).expect("Failed to start datasource surfnet");

    datasource_svm_locker
        .with_svm_writer(|svm_writer| {
            svm_writer
                .set_account(
                    &account,
                    Account {
                        lamports: LAMPORTS_PER_SOL,
                        data: vec![1, 2, 3],
                        owner: system_program::id(),
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            Ok::<(), SurfpoolError>(())
        })
        .expect("Failed to seed datasource accounts");

    let (surfnet_url, surfnet_svm_locker) =
        start_surfnet(vec![], Some(datasource_surfnet_url), another_test_type)
            .expect("Failed to start surfnet");
    let rpc_client = RpcClient::new(surfnet_url);

    // Mark the account offline
    let _: serde_json::Value = rpc_client
        .send(
            solana_client::rpc_request::RpcRequest::Custom {
                method: "surfnet_offlineAccount",
            },
            serde_json::json!([account.to_string()]),
        )
        .await
        .expect("Failed to set account offline");

    assert!(
        surfnet_svm_locker.is_account_offline(&account),
        "Account should be offline"
    );

    // Verify it's blocked
    let result = rpc_client.get_account(&account).await;
    assert!(
        result.is_err(),
        "Offline account should not be fetched from remote"
    );

    // Reset the account — this should bring it back online
    let _: serde_json::Value = rpc_client
        .send(
            solana_client::rpc_request::RpcRequest::Custom {
                method: "surfnet_resetAccount",
            },
            serde_json::json!([account.to_string()]),
        )
        .await
        .expect("Failed to reset account");

    assert!(
        !surfnet_svm_locker.is_account_offline(&account),
        "Account should be online after reset"
    );

    // Verify it can be fetched from remote again
    let result = rpc_client.get_account(&account).await;
    assert!(
        result.is_ok(),
        "Account should be fetchable from remote after reset"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[tokio::test(flavor = "multi_thread")]
async fn test_reset_network_clears_offline_accounts(test_type: TestType) {
    let account = Pubkey::new_unique();
    let another_test_type = match &test_type {
        TestType::OnDiskSqlite(_) => TestType::sqlite(),
        TestType::InMemorySqlite => TestType::in_memory(),
        TestType::NoDb => TestType::no_db(),
        #[cfg(feature = "postgres")]
        TestType::Postgres { url, .. } => TestType::Postgres {
            url: url.clone(),
            surfnet_id: crate::storage::tests::random_surfnet_id(),
        },
    };

    let (datasource_surfnet_url, datasource_svm_locker) =
        start_surfnet(vec![], None, test_type).expect("Failed to start datasource surfnet");

    datasource_svm_locker
        .with_svm_writer(|svm_writer| {
            svm_writer
                .set_account(
                    &account,
                    Account {
                        lamports: LAMPORTS_PER_SOL,
                        data: vec![1, 2, 3],
                        owner: system_program::id(),
                        executable: false,
                        rent_epoch: 0,
                    },
                )
                .unwrap();
            Ok::<(), SurfpoolError>(())
        })
        .expect("Failed to seed datasource accounts");

    let (surfnet_url, surfnet_svm_locker) =
        start_surfnet(vec![], Some(datasource_surfnet_url), another_test_type)
            .expect("Failed to start surfnet");
    let rpc_client = RpcClient::new(surfnet_url);

    // Mark the account offline
    let _: serde_json::Value = rpc_client
        .send(
            solana_client::rpc_request::RpcRequest::Custom {
                method: "surfnet_offlineAccount",
            },
            serde_json::json!([account.to_string()]),
        )
        .await
        .expect("Failed to set account offline");

    assert!(
        surfnet_svm_locker.is_account_offline(&account),
        "Account should be offline"
    );

    // Reset the network
    let _: serde_json::Value = rpc_client
        .send(
            solana_client::rpc_request::RpcRequest::Custom {
                method: "surfnet_resetNetwork",
            },
            serde_json::json!([]),
        )
        .await
        .expect("Failed to reset network");

    assert!(
        !surfnet_svm_locker.is_account_offline(&account),
        "Account should be online after network reset"
    );

    // Verify the account can be fetched from remote again
    let result = rpc_client.get_account(&account).await;
    assert!(
        result.is_ok(),
        "Account should be fetchable from remote after network reset"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[tokio::test(flavor = "multi_thread")]
async fn test_remote_get_multiple_accounts_only_program_accounts(test_type: TestType) {
    let program_pubkey = Pubkey::new_unique();
    let another_test_type = match &test_type {
        TestType::OnDiskSqlite(_) => TestType::sqlite(),
        TestType::InMemorySqlite => TestType::in_memory(),
        TestType::NoDb => TestType::no_db(),
        #[cfg(feature = "postgres")]
        TestType::Postgres { url, .. } => TestType::Postgres {
            url: url.clone(),
            surfnet_id: crate::storage::tests::random_surfnet_id(),
        },
    };

    // Start datasource surfnet A (offline, no remote)
    let (datasource_url, datasource_svm_locker) =
        start_surfnet(vec![], None, test_type).expect("Failed to start datasource surfnet");
    println!("Datasource surfnet started at {}", datasource_url);

    // Insert a proper upgradeable program into A.
    // Using write_program ensures the program and program-data accounts are
    // stored with the correct BPF loader owner and serialized state, which is
    // required by LiteSVM's account validation.
    datasource_svm_locker
        .write_program(program_pubkey, None, 0, &[1, 2, 3], &None)
        .await
        .expect("Failed to write program account");

    // Start surfnet B pointing to A as remote
    let (surfnet_url, _surfnet_svm_locker) =
        start_surfnet(vec![], Some(datasource_url), another_test_type)
            .expect("Failed to start surfnet");
    println!("Surfnet B started at {}", surfnet_url);

    let rpc_client = RpcClient::new(surfnet_url);

    // Fetch the executable account via get_multiple_accounts.
    let accounts = rpc_client
        .get_multiple_accounts(&[program_pubkey])
        .await
        .expect("Failed to get multiple accounts");

    let account = accounts[0]
        .as_ref()
        .expect("Program account should be found (not None)");
    assert!(account.executable, "Account should be executable");
    println!("Program account successfully fetched via get_multiple_accounts");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[tokio::test(flavor = "multi_thread")]
async fn test_remote_get_multiple_accounts_ordering(test_type: TestType) {
    let program_pubkey = Pubkey::new_unique();
    let plain_pubkey = Pubkey::new_unique();
    let another_test_type = match &test_type {
        TestType::OnDiskSqlite(_) => TestType::sqlite(),
        TestType::InMemorySqlite => TestType::in_memory(),
        TestType::NoDb => TestType::no_db(),
        #[cfg(feature = "postgres")]
        TestType::Postgres { url, .. } => TestType::Postgres {
            url: url.clone(),
            surfnet_id: crate::storage::tests::random_surfnet_id(),
        },
    };

    // Start datasource surfnet A (offline, no remote)
    let (datasource_url, datasource_svm_locker) =
        start_surfnet(vec![], None, test_type).expect("Failed to start datasource surfnet");

    // Insert a program account on A
    datasource_svm_locker
        .write_program(program_pubkey, None, 0, &[1, 2, 3], &None)
        .await
        .expect("Failed to write program account");

    // Insert a plain SOL account on A
    datasource_svm_locker
        .airdrop(&plain_pubkey, LAMPORTS_PER_SOL)
        .expect("Failed to airdrop to plain account")
        .unwrap();

    // Start surfnet B pointing to A as remote
    let (surfnet_url, _) = start_surfnet(vec![], Some(datasource_url), another_test_type)
        .expect("Failed to start surfnet B");

    let rpc_client = RpcClient::new(surfnet_url);

    // Fetch with program FIRST, plain SECOND — this is the ordering that the old code broke
    let accounts = rpc_client
        .get_multiple_accounts(&[program_pubkey, plain_pubkey])
        .await
        .expect("Failed to get multiple accounts");

    assert_eq!(accounts.len(), 2);

    // Index 0 must be the program account (executable)
    let prog_account = accounts[0]
        .as_ref()
        .expect("Program account should be found at index 0");
    assert!(
        prog_account.executable,
        "accounts[0] should be executable (program)"
    );

    // Index 1 must be the plain account (not executable, has lamports)
    let plain_account = accounts[1]
        .as_ref()
        .expect("Plain account should be found at index 1");
    assert!(
        !plain_account.executable,
        "accounts[1] should not be executable (plain)"
    );
    assert_eq!(
        plain_account.lamports, LAMPORTS_PER_SOL,
        "accounts[1] should have airdrop lamports"
    );
}

// websocket rpc methods tests

#[test_case(SignatureSubscriptionType::processed() ; "processed commitment")]
#[test_case(SignatureSubscriptionType::received() ; "received commitment")]
#[test_case(SignatureSubscriptionType::confirmed() ; "confirmed commitment")]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_signature_subscribe(subscription_type: SignatureSubscriptionType) {
    use crossbeam_channel::unbounded;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default();

    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create a test transaction
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = 1_000_000;
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );
    let signature = tx.signatures[0];

    // subscribe with processed commitment
    let notification_rx =
        svm_locker.subscribe_for_signature_updates(&signature, subscription_type.clone());

    // process the transaction
    let (status_tx, _status_rx) = unbounded();
    let result = svm_locker
        .process_transaction(&None, VersionedTransaction::from(tx), status_tx, true, true)
        .await;
    assert!(
        result.is_ok(),
        "Transaction should be processed successfully"
    );

    match subscription_type {
        SignatureSubscriptionType::Commitment(CommitmentLevel::Confirmed) => {
            // confirm the block to trigger confirmed notification
            svm_locker.confirm_current_block(&None).await.unwrap();
        }
        _ => {}
    }

    // wait for the notification
    let notification = notification_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        notification.is_ok(),
        "Should receive {} notification",
        subscription_type
    );

    let (slot, error_opt) = notification.unwrap();
    assert!(
        error_opt.is_none(),
        "Transaction should succeed without error"
    );
    println!(
        "✓ Received {} signature notification at slot {}",
        subscription_type, slot
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_signature_subscribe_failed_transaction(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_system_interface::instruction as system_instruction;

    use crate::surfnet::SignatureSubscriptionType;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create a test transaction that will fail (insufficient funds)
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix =
        system_instruction::transfer(&payer.pubkey(), &recipient, LAMPORTS_PER_SOL * 2); // Try to send more than we have
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );
    let signature = tx.signatures[0];

    // subscribe with processed commitment
    let subscription_type = SignatureSubscriptionType::processed();
    let notification_rx = svm_locker.subscribe_for_signature_updates(&signature, subscription_type);

    // process the transaction (should fail)
    let (status_tx, _status_rx) = unbounded();
    let _ = svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await;

    // wait for the notification with error
    let notification = notification_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        notification.is_ok(),
        "Should receive notification for failed transaction"
    );

    let (slot, error_opt) = notification.unwrap();
    assert!(error_opt.is_some(), "Failed transaction should have error");
    println!(
        "✓ Received signature notification for failed transaction at slot {} with error: {:?}",
        slot, error_opt
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_signature_subscribe_multiple_subscribers(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_system_interface::instruction as system_instruction;

    use crate::surfnet::SignatureSubscriptionType;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create a test transaction
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );
    let signature = tx.signatures[0];

    // create multiple subscriptions to the same signature
    let notification_rx1 = svm_locker
        .subscribe_for_signature_updates(&signature, SignatureSubscriptionType::processed());
    let notification_rx2 = svm_locker
        .subscribe_for_signature_updates(&signature, SignatureSubscriptionType::processed());
    let notification_rx3 = svm_locker
        .subscribe_for_signature_updates(&signature, SignatureSubscriptionType::confirmed());

    // process the transaction
    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // all processed subscriptions should receive notification
    assert!(
        notification_rx1
            .recv_timeout(Duration::from_secs(5))
            .is_ok(),
        "Subscriber 1 should receive notification"
    );
    assert!(
        notification_rx2
            .recv_timeout(Duration::from_secs(5))
            .is_ok(),
        "Subscriber 2 should receive notification"
    );

    // confirm the block for confirmed subscription
    svm_locker.confirm_current_block(&None).await.unwrap();
    assert!(
        notification_rx3
            .recv_timeout(Duration::from_secs(5))
            .is_ok(),
        "Confirmed subscriber should receive notification"
    );

    println!("✓ Multiple subscribers all received notifications correctly");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_signature_subscribe_before_transaction_exists(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_system_interface::instruction as system_instruction;

    use crate::surfnet::SignatureSubscriptionType;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );
    let signature = tx.signatures[0];

    // subscribe before the transaction exists
    let subscription_type = SignatureSubscriptionType::processed();
    let notification_rx = svm_locker.subscribe_for_signature_updates(&signature, subscription_type);

    // small delay to ensure the subscription is registered
    tokio::time::sleep(Duration::from_millis(100)).await;

    // now process the transaction
    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // should still receive notification
    let notification = notification_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        notification.is_ok(),
        "Should receive notification even when subscribed before transaction"
    );

    let (slot, error_opt) = notification.unwrap();
    assert!(error_opt.is_none(), "Transaction should succeed");
    println!(
        "✓ Subscription before transaction works correctly at slot {}",
        slot
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_account_subscribe_balance_change(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create and fund a new account
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // subscribe to payer account updates
    let account_rx =
        svm_locker.subscribe_for_account_updates(&payer.pubkey(), Some(UiAccountEncoding::Base58));

    // make a transaction to change the account balance
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    let account_update = account_rx.recv_timeout(Duration::from_secs(5));
    assert!(account_update.is_ok(), "Should receive account update");

    let updated_account = account_update.unwrap();
    assert_eq!(
        updated_account.lamports,
        LAMPORTS_PER_SOL - 1_000_000 - 5000, // original - transfer amount - fees
        "Account balance should be updated"
    );
    println!(
        "✓ Received account update notification with new balance {}",
        updated_account.lamports
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_account_subscribe_multiple_changes(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_account_decoder::UiAccountEncoding;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create and fund a new account
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), 10 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // subscribe to payer account updates
    let account_rx =
        svm_locker.subscribe_for_account_updates(&payer.pubkey(), Some(UiAccountEncoding::Base58));

    // make multiple transactions
    for i in 0..3 {
        let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

        let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
        let tx = Transaction::new_signed_with_payer(
            &[transfer_ix],
            Some(&payer.pubkey()),
            &[&payer],
            recent_blockhash,
        );

        let (status_tx, _status_rx) = unbounded();
        svm_locker
            .process_transaction(
                &None,
                VersionedTransaction::from(tx),
                status_tx,
                false,
                false,
            )
            .await
            .unwrap();

        let account_update = account_rx.recv_timeout(Duration::from_secs(5));
        assert!(
            account_update.is_ok(),
            "Should receive account update for transaction {}",
            i + 1
        );
        println!(
            "✓ Received account update notification for transaction {}",
            i + 1
        );

        // confirm the block to get fresh blockhash for next transaction
        if i < 2 {
            svm_locker.confirm_current_block(&None).await.unwrap();
        }
    }
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_account_subscribe_multiple_subscribers(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_account_decoder::UiAccountEncoding;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let sender = Keypair::new();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();
    svm_locker
        .airdrop(&sender.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // create multiple subscriptions to the same account
    let account_rx1 =
        svm_locker.subscribe_for_account_updates(&payer.pubkey(), Some(UiAccountEncoding::Base64));
    let account_rx2 =
        svm_locker.subscribe_for_account_updates(&payer.pubkey(), Some(UiAccountEncoding::Base58));
    let account_rx3 = svm_locker.subscribe_for_account_updates(&payer.pubkey(), None);

    // trigger a change with a transfer (not airdrop)
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&sender.pubkey(), &payer.pubkey(), 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&sender.pubkey()),
        &[&sender],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // all subscribers should receive notifications
    assert!(
        account_rx1.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 1 should receive notification"
    );
    assert!(
        account_rx2.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 2 should receive notification"
    );
    assert!(
        account_rx3.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 3 should receive notification"
    );

    println!("✓ All 3 subscribers received notifications for account change");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_account_subscribe_new_account_creation(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_account_decoder::UiAccountEncoding;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let new_account = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // subscribe to an account that doesn't exist yet
    let account_rx =
        svm_locker.subscribe_for_account_updates(&new_account, Some(UiAccountEncoding::Base64));

    // create the account with a transfer
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &new_account, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // should receive notification when account is created
    let account_update = account_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        account_update.is_ok(),
        "Should receive notification when account is created"
    );

    let created_account = account_update.unwrap();
    assert_eq!(
        created_account.lamports, 1_000_000,
        "New account should have correct balance"
    );
    println!(
        "✓ Received account update notification for new account creation with balance {}",
        created_account.lamports
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_account_subscribe_account_closure(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_account_decoder::UiAccountEncoding;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let account_to_close = Keypair::new();
    let recipient = Pubkey::new_unique();

    // give the account some funds
    svm_locker
        .airdrop(&account_to_close.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // subscribe to the account
    let account_rx = svm_locker
        .subscribe_for_account_updates(&account_to_close.pubkey(), Some(UiAccountEncoding::Base64));

    // close the account by sending all funds minus fee
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let close_ix = system_instruction::transfer(
        &account_to_close.pubkey(),
        &recipient,
        LAMPORTS_PER_SOL - 5_000,
    );
    let tx = Transaction::new_signed_with_payer(
        &[close_ix],
        Some(&account_to_close.pubkey()),
        &[&account_to_close],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            true,
            false,
        )
        .await
        .unwrap();

    // should receive notification for the closure
    let account_update = account_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        account_update.is_ok(),
        "Should receive notification when account is closed"
    );

    println!("✓ Received notification for account closure");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slot_subscribe_basic(test_type: TestType) {
    use surfpool_types::types::BlockProductionMode;

    let (svm_locker, _simnet_commands_tx, _simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(100), test_type);

    // subscribe to slot updates
    let slot_rx = svm_locker.subscribe_for_slot_updates();

    // wait for the first slot update
    let slot_info_1 = slot_rx.recv_timeout(Duration::from_secs(2));
    assert!(slot_info_1.is_ok(), "Should receive slot update");

    let first_slot = slot_info_1.unwrap();
    println!("✓ Received first slot update: {}", first_slot.slot);

    // wait for the second slot update
    let slot_info_2 = slot_rx.recv_timeout(Duration::from_secs(2));
    assert!(slot_info_2.is_ok(), "Should receive slot update");

    let second_slot = slot_info_2.unwrap();
    println!("✓ Received second slot update: {}", second_slot.slot);

    assert!(
        second_slot.slot > first_slot.slot,
        "Second slot should be greater than first slot"
    );
    println!("✓ Slot updates are progressing correctly");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slot_subscribe_manual_advancement(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // subscribe to slot updates
    let slot_rx = svm_locker.subscribe_for_slot_updates();

    let initial_slot = svm_locker.get_latest_absolute_slot();

    // manually advance slot by confirming a block
    svm_locker.confirm_current_block(&None).await.unwrap();

    // should receive slot update notification
    let slot_update = slot_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        slot_update.is_ok(),
        "Should receive slot update after block confirmation"
    );

    let slot_info = slot_update.unwrap();
    assert!(
        slot_info.slot > initial_slot,
        "Updated slot should be greater than initial slot"
    );
    println!(
        "✓ Received slot notification after manual block confirmation: slot {} -> {}",
        initial_slot, slot_info.slot
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slot_subscribe_multiple_subscribers(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create multiple subscriptions
    let slot_rx1 = svm_locker.subscribe_for_slot_updates();
    let slot_rx2 = svm_locker.subscribe_for_slot_updates();
    let slot_rx3 = svm_locker.subscribe_for_slot_updates();

    // advance slot
    svm_locker.confirm_current_block(&None).await.unwrap();

    // all subscribers should receive notification
    assert!(
        slot_rx1.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 1 should receive slot update"
    );
    assert!(
        slot_rx2.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 2 should receive slot update"
    );
    assert!(
        slot_rx3.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 3 should receive slot update"
    );

    println!("✓ All 3 subscribers received slot update notifications");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slot_subscribe_multiple_slot_changes(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let slot_rx = svm_locker.subscribe_for_slot_updates();

    // advance slot multiple times
    for i in 0..3 {
        svm_locker.confirm_current_block(&None).await.unwrap();

        let slot_update = slot_rx.recv_timeout(Duration::from_secs(5));
        assert!(
            slot_update.is_ok(),
            "Should receive slot update for advancement {}",
            i + 1
        );

        let slot_info = slot_update.unwrap();
        println!(
            "✓ Received slot notification #{}: slot {}",
            i + 1,
            slot_info.slot
        );
    }
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slots_updates_subscribe_basic(test_type: TestType) {
    use surfpool_types::types::BlockProductionMode;

    let (svm_locker, _simnet_commands_tx, _simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(100), test_type);

    // subscribe to slots updates
    let slots_updates_rx = svm_locker.subscribe_for_slots_updates();

    // wait for the first slots update event
    let event_1 = slots_updates_rx.recv_timeout(Duration::from_secs(2));
    assert!(event_1.is_ok(), "Should receive slots update event");

    let first_event = event_1.unwrap();
    println!("✓ Received first slots update event: {:?}", first_event);

    // wait for at least one more event to confirm streaming
    let event_2 = slots_updates_rx.recv_timeout(Duration::from_secs(2));
    assert!(
        event_2.is_ok(),
        "Should receive a second slots update event"
    );

    println!("✓ slots_updates stream is producing events");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slots_updates_subscribe_manual_advancement(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // subscribe to slots updates
    let slots_updates_rx = svm_locker.subscribe_for_slots_updates();

    // manually advance slot by confirming a block
    svm_locker.confirm_current_block(&None).await.unwrap();

    // Drain all events emitted for this single block confirmation and assert we
    // observe the per-block lifecycle variants. `Root` is intentionally NOT
    // asserted here: the rooted slot only catches up to `genesis_slot` after
    // ~FINALIZATION_SLOT_THRESHOLD advancements, so a single confirmation is
    // not expected to produce a `Root` event. See the
    // `_root_emission` test below for that coverage.
    let mut saw_created_bank = false;
    let mut saw_frozen = false;
    let mut saw_optimistic_confirmation = false;
    let deadline = std::time::Instant::now() + Duration::from_secs(5);

    while std::time::Instant::now() < deadline {
        let Ok(event) = slots_updates_rx.recv_timeout(Duration::from_millis(200)) else {
            // No more events arriving in this window; bail out and check what we collected.
            break;
        };
        match event.as_ref() {
            SlotUpdate::CreatedBank { .. } => saw_created_bank = true,
            SlotUpdate::Frozen { .. } => saw_frozen = true,
            SlotUpdate::OptimisticConfirmation { .. } => saw_optimistic_confirmation = true,
            _ => {}
        }
        if saw_created_bank && saw_frozen && saw_optimistic_confirmation {
            break;
        }
    }

    assert!(
        saw_created_bank,
        "Should observe CreatedBank slot update event"
    );
    assert!(saw_frozen, "Should observe Frozen slot update event");
    assert!(
        saw_optimistic_confirmation,
        "Should observe OptimisticConfirmation slot update event"
    );

    println!("✓ Observed CreatedBank, Frozen, and OptimisticConfirmation events");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slots_updates_subscribe_root_emission(test_type: TestType) {
    use crate::surfnet::FINALIZATION_SLOT_THRESHOLD;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // Subscribe before advancing so we capture every event from genesis forward.
    let slots_updates_rx = svm_locker.subscribe_for_slots_updates();

    // Advance enough slots for the rooted slot to catch up to `genesis_slot`,
    // which is what gates emission of `SlotUpdate::Root`.
    let advancements = (FINALIZATION_SLOT_THRESHOLD as usize) + 2;
    for _ in 0..advancements {
        svm_locker.confirm_current_block(&None).await.unwrap();
    }

    // Drain everything that's been queued and check for a Root variant.
    let mut saw_root = false;
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while std::time::Instant::now() < deadline {
        let Ok(event) = slots_updates_rx.recv_timeout(Duration::from_millis(200)) else {
            break;
        };
        if matches!(event.as_ref(), SlotUpdate::Root { .. }) {
            saw_root = true;
            break;
        }
    }

    assert!(
        saw_root,
        "Should observe Root slot update event after {} advancements",
        advancements
    );
    println!(
        "✓ Observed Root slot update event after {} advancements",
        advancements
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slots_updates_subscribe_multiple_subscribers(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create multiple subscriptions
    let rx1 = svm_locker.subscribe_for_slots_updates();
    let rx2 = svm_locker.subscribe_for_slots_updates();
    let rx3 = svm_locker.subscribe_for_slots_updates();

    // advance slot
    svm_locker.confirm_current_block(&None).await.unwrap();

    // all subscribers should receive at least one slots update event
    assert!(
        rx1.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 1 should receive a slots update event"
    );
    assert!(
        rx2.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 2 should receive a slots update event"
    );
    assert!(
        rx3.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Subscriber 3 should receive a slots update event"
    );

    println!("✓ All 3 subscribers received slots update events");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_slots_updates_subscribe_multiple_slot_changes(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let slots_updates_rx = svm_locker.subscribe_for_slots_updates();

    // advance slot multiple times and ensure each block produces events
    for i in 0..3 {
        svm_locker.confirm_current_block(&None).await.unwrap();

        // expect at least one event for this block confirmation
        let event = slots_updates_rx.recv_timeout(Duration::from_secs(5));
        assert!(
            event.is_ok(),
            "Should receive slots update event for advancement {}",
            i + 1
        );
        println!(
            "✓ Received slots update event #{}: {:?}",
            i + 1,
            event.unwrap()
        );

        // drain any further events emitted for this block before the next iteration
        while slots_updates_rx
            .recv_timeout(Duration::from_millis(50))
            .is_ok()
        {}
    }
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_logs_subscribe_all_transactions(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_client::rpc_config::RpcTransactionLogsFilter;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // subscribe to all transaction logs
    let logs_rx = svm_locker
        .subscribe_for_logs_updates(&CommitmentLevel::Processed, &RpcTransactionLogsFilter::All);

    // create and process a test transaction
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );
    let signature = tx.signatures[0];

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // wait for the logs update
    let logs_update = logs_rx.recv_timeout(Duration::from_secs(5));
    assert!(logs_update.is_ok(), "Should receive logs update");

    let (_slot, logs_response) = logs_update.unwrap();
    assert_eq!(
        logs_response.signature,
        signature.to_string(),
        "Signature should match"
    );
    assert!(
        logs_response.err.is_none(),
        "Transaction should succeed without error, got error: {}",
        logs_response.err.unwrap()
    );
    assert!(
        !logs_response.logs.is_empty(),
        "Should have at least one log message"
    );
    println!("✓ Received logs update for transaction: {}", signature);
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_logs_subscribe_mentions_account(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_client::rpc_config::RpcTransactionLogsFilter;
    use solana_commitment_config::CommitmentLevel;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // subscribe to logs mentioning the system program
    let system_program = solana_sdk_ids::system_program::id();
    let logs_rx = svm_locker.subscribe_for_logs_updates(
        &CommitmentLevel::Processed,
        &RpcTransactionLogsFilter::Mentions(vec![system_program.to_string()]),
    );
    // also subscribe to logs mentioning the token program
    let token_program = spl_token_interface::id();
    let logs_rx_2 = svm_locker.subscribe_for_logs_updates(
        &CommitmentLevel::Processed,
        &RpcTransactionLogsFilter::Mentions(vec![token_program.to_string()]),
    );

    // create transaction that uses system program
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // should receive logs since transaction mentions system program
    let logs_notification = logs_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        logs_notification.is_ok(),
        "Should receive logs for transaction mentioning system program"
    );

    let (_slot, logs_response) = logs_notification.unwrap();
    assert!(
        !logs_response.logs.is_empty(),
        "Should have logs from system program"
    );
    println!("✓ Received logs notification for transaction mentioning system program");

    // should NOT receive logs for token program subscription
    let logs_notification_2 = logs_rx_2.recv_timeout(Duration::from_secs(3));
    assert!(
        logs_notification_2.is_err(),
        "Should NOT receive logs for transaction not mentioning token program"
    );
    println!("✓ Did not receive logs notification for transaction not mentioning token program");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_logs_subscribe_confirmed_commitment(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_client::rpc_config::RpcTransactionLogsFilter;
    use solana_commitment_config::CommitmentLevel;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // subscribe to confirmed logs
    let logs_rx = svm_locker
        .subscribe_for_logs_updates(&CommitmentLevel::Confirmed, &RpcTransactionLogsFilter::All);

    // create and process a transaction
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // confirm the block to trigger confirmed logs
    svm_locker.confirm_current_block(&None).await.unwrap();

    // wait for confirmed logs notification
    let logs_notification = logs_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        logs_notification.is_ok(),
        "Should receive confirmed logs notification"
    );

    let (slot, logs_response) = logs_notification.unwrap();
    assert!(
        !logs_response.logs.is_empty(),
        "Confirmed logs should not be empty"
    );
    println!("✓ Received confirmed logs notification at slot {}", slot);
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_logs_subscribe_finalized_commitment(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_client::rpc_config::RpcTransactionLogsFilter;
    use solana_commitment_config::CommitmentLevel;
    use solana_system_interface::instruction as system_instruction;

    use crate::surfnet::FINALIZATION_SLOT_THRESHOLD;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // subscribe to finalized logs
    let logs_rx = svm_locker
        .subscribe_for_logs_updates(&CommitmentLevel::Finalized, &RpcTransactionLogsFilter::All);

    // create and process a transaction
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // confirm and finalize the block
    svm_locker.confirm_current_block(&None).await.unwrap();

    // advance enough slots to trigger finalization
    for _ in 0..FINALIZATION_SLOT_THRESHOLD {
        svm_locker.confirm_current_block(&None).await.unwrap();
    }

    // wait for finalized logs notification
    let logs_notification = logs_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        logs_notification.is_ok(),
        "Should receive finalized logs notification"
    );

    let (slot, logs_response) = logs_notification.unwrap();
    assert!(
        !logs_response.logs.is_empty(),
        "Finalized logs should not be empty"
    );
    println!("✓ Received finalized logs notification at slot {}", slot);
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_logs_subscribe_failed_transaction(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_client::rpc_config::RpcTransactionLogsFilter;
    use solana_commitment_config::CommitmentLevel;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // subscribe to all logs
    let logs_rx = svm_locker
        .subscribe_for_logs_updates(&CommitmentLevel::Processed, &RpcTransactionLogsFilter::All);

    // create and process a transaction that will fail (insufficient funds)
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix =
        system_instruction::transfer(&payer.pubkey(), &recipient, LAMPORTS_PER_SOL * 2);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    let _ = svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await;

    // wait for logs notification with error
    let logs_notification = logs_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        logs_notification.is_ok(),
        "Should receive logs for failed transaction"
    );

    let (_slot, logs_response) = logs_notification.unwrap();
    assert!(
        logs_response.err.is_some(),
        "Failed transaction should have error in logs"
    );
    assert!(
        !logs_response.logs.is_empty(),
        "Failed transaction should still have logs"
    );
    println!(
        "✓ Received logs notification for failed transaction with error: {:?}",
        logs_response.err
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_logs_subscribe_multiple_subscribers(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_client::rpc_config::RpcTransactionLogsFilter;
    use solana_commitment_config::CommitmentLevel;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create multiple subscriptions with different commitment levels
    let logs_rx1 = svm_locker
        .subscribe_for_logs_updates(&CommitmentLevel::Processed, &RpcTransactionLogsFilter::All);
    let logs_rx2 = svm_locker
        .subscribe_for_logs_updates(&CommitmentLevel::Processed, &RpcTransactionLogsFilter::All);
    let logs_rx3 = svm_locker
        .subscribe_for_logs_updates(&CommitmentLevel::Confirmed, &RpcTransactionLogsFilter::All);

    // create and process a transaction
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // all processed subscribers should receive notification
    assert!(
        logs_rx1.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Processed subscriber 1 should receive logs"
    );
    assert!(
        logs_rx2.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Processed subscriber 2 should receive logs"
    );

    // confirm block for confirmed subscriber
    svm_locker.confirm_current_block(&None).await.unwrap();
    assert!(
        logs_rx3.recv_timeout(Duration::from_secs(5)).is_ok(),
        "Confirmed subscriber should receive logs"
    );

    println!("✓ All subscribers received logs notifications at their respective commitment levels");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_logs_subscribe_logs_content(test_type: TestType) {
    use crossbeam_channel::unbounded;
    use solana_client::rpc_config::RpcTransactionLogsFilter;
    use solana_commitment_config::CommitmentLevel;
    use solana_system_interface::instruction as system_instruction;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    // create test accounts
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    // subscribe to all logs
    let logs_rx = svm_locker
        .subscribe_for_logs_updates(&CommitmentLevel::Processed, &RpcTransactionLogsFilter::All);

    // create and process a transaction
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = system_instruction::transfer(&payer.pubkey(), &recipient, 1_000_000);
    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&payer.pubkey()),
        &[&payer],
        recent_blockhash,
    );
    let signature = tx.signatures[0];

    let (status_tx, _status_rx) = unbounded();
    svm_locker
        .process_transaction(
            &None,
            VersionedTransaction::from(tx),
            status_tx,
            false,
            false,
        )
        .await
        .unwrap();

    // receive and validate logs content
    let logs_notification = logs_rx.recv_timeout(Duration::from_secs(5));
    assert!(logs_notification.is_ok(), "Should receive logs");

    let (_slot, logs_response) = logs_notification.unwrap();

    // verify logs response structure
    assert_eq!(logs_response.signature, signature.to_string());
    assert!(logs_response.err.is_none());
    assert!(!logs_response.logs.is_empty());

    // logs should contain program invocation messages
    let has_program_log = logs_response.logs.iter().any(|log| log.contains("Program"));
    assert!(
        has_program_log,
        "Logs should contain program execution messages"
    );

    println!("✓ Logs notification contains valid content:");
    for (i, log) in logs_response.logs.iter().enumerate() {
        println!("  Log {}: {}", i + 1, log);
    }
}

struct Token2022PausableFixture {
    payer: Keypair,
    mint: Keypair,
    payer_ata: Pubkey,
    recipient_ata: Pubkey,
    decimals: u8,
    initial_mint_amount: u64,
}

fn token_2022_account_balance(svm_locker: &SurfnetSvmLocker, token_account: &Pubkey) -> u64 {
    let account = svm_locker
        .get_account_local(token_account)
        .inner
        .map_account()
        .expect("token account should exist");
    let token_account_state =
        StateWithExtensions::<spl_token_2022_interface::state::Account>::unpack(&account.data)
            .expect("token-2022 account should unpack");
    token_account_state.base.amount
}

fn token_2022_mint_is_paused(svm_locker: &SurfnetSvmLocker, mint: &Pubkey) -> bool {
    let account = svm_locker
        .get_account_local(mint)
        .inner
        .map_account()
        .expect("mint account should exist");
    let mint_state =
        StateWithExtensions::<spl_token_2022_interface::state::Mint>::unpack(&account.data)
            .expect("token-2022 mint should unpack");
    let pausable_config = mint_state
        .get_extension::<PausableConfig>()
        .expect("mint should have PausableConfig");
    bool::from(pausable_config.paused)
}

fn setup_token2022_pausable_fixture(svm_locker: &SurfnetSvmLocker) -> Token2022PausableFixture {
    use spl_token_2022_interface::{
        extension::pausable::instruction as pausable_instruction,
        instruction::{initialize_mint2, mint_to},
    };

    let payer = Keypair::new();
    let recipient = Keypair::new();
    let mint = Keypair::new();
    let decimals = 6u8;
    let initial_mint_amount = 1_000_000u64;

    svm_locker
        .airdrop(&payer.pubkey(), 10 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();
    svm_locker
        .airdrop(&recipient.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let mint_space =
        ExtensionType::try_calculate_account_len::<PodMint>(&[ExtensionType::Pausable])
            .expect("pausable mint size should calculate");
    let mint_rent =
        svm_locker.with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(mint_space));
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let payer_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &payer.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );
    let recipient_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_mint_ix = system_instruction::create_account(
        &payer.pubkey(),
        &mint.pubkey(),
        mint_rent,
        mint_space as u64,
        &spl_token_2022_interface::id(),
    );
    let init_pausable_ix = pausable_instruction::initialize(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer.pubkey(),
    )
    .expect("pausable extension should initialize");
    let init_mint_ix = initialize_mint2(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer.pubkey(),
        Some(&payer.pubkey()),
        decimals,
    )
    .unwrap();

    let create_mint_msg = Message::new_with_blockhash(
        &[create_mint_ix, init_pausable_ix, init_mint_ix],
        Some(&payer.pubkey()),
        &recent_blockhash,
    );
    let create_mint_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(create_mint_msg), &[&payer, &mint])
            .unwrap();
    let create_mint_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(create_mint_tx, false, false));
    assert!(
        create_mint_result.is_ok(),
        "Pausable mint setup failed: {:?}",
        create_mint_result.err()
    );
    assert!(
        !token_2022_mint_is_paused(svm_locker, &mint.pubkey()),
        "Pausable mint should start unpaused"
    );

    let fund_recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let create_payer_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &payer.pubkey(),
            &payer.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );
    let create_recipient_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &payer.pubkey(),
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );
    let mint_to_ix = mint_to(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer_ata,
        &payer.pubkey(),
        &[&payer.pubkey()],
        initial_mint_amount,
    )
    .unwrap();

    let fund_msg = Message::new_with_blockhash(
        &[create_payer_ata_ix, create_recipient_ata_ix, mint_to_ix],
        Some(&payer.pubkey()),
        &fund_recent_blockhash,
    );
    let fund_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(fund_msg), &[&payer]).unwrap();
    let fund_result = svm_locker.with_svm_writer(|svm| svm.send_transaction(fund_tx, false, false));
    assert!(
        fund_result.is_ok(),
        "Pausable mint funding failed: {:?}",
        fund_result.err()
    );
    assert_eq!(
        token_2022_account_balance(svm_locker, &payer_ata),
        initial_mint_amount,
        "Payer ATA should hold the initial minted balance"
    );
    assert_eq!(
        token_2022_account_balance(svm_locker, &recipient_ata),
        0,
        "Recipient ATA should start empty"
    );

    Token2022PausableFixture {
        payer,
        mint,
        payer_ata,
        recipient_ata,
        decimals,
        initial_mint_amount,
    }
}

/// Token-2022 pausable lifecycle:
/// create pausable mint → mint → transfer → pause → reject future minting
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_token2022_pausable_mint(test_type: TestType) {
    use spl_token_2022_interface::{
        extension::pausable::instruction as pausable_instruction,
        instruction::{mint_to, transfer_checked},
    };

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let fixture = setup_token2022_pausable_fixture(&svm_locker);

    let transfer_amount = 250_000u64;
    let transfer_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let transfer_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &fixture.payer_ata,
        &fixture.mint.pubkey(),
        &fixture.recipient_ata,
        &fixture.payer.pubkey(),
        &[&fixture.payer.pubkey()],
        transfer_amount,
        fixture.decimals,
    )
    .unwrap();
    let transfer_msg = Message::new_with_blockhash(
        &[transfer_ix],
        Some(&fixture.payer.pubkey()),
        &transfer_blockhash,
    );
    let transfer_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(transfer_msg), &[&fixture.payer])
            .unwrap();
    let transfer_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(transfer_tx, false, false));
    assert!(
        transfer_result.is_ok(),
        "Transfer before pause failed: {:?}",
        transfer_result.err()
    );
    assert_eq!(
        token_2022_account_balance(&svm_locker, &fixture.payer_ata),
        fixture.initial_mint_amount - transfer_amount,
        "Payer ATA should be debited by the transfer amount"
    );
    assert_eq!(
        token_2022_account_balance(&svm_locker, &fixture.recipient_ata),
        transfer_amount,
        "Recipient ATA should receive the transferred tokens"
    );

    let pause_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let pause_ix = pausable_instruction::pause(
        &spl_token_2022_interface::id(),
        &fixture.mint.pubkey(),
        &fixture.payer.pubkey(),
        &[&fixture.payer.pubkey()],
    )
    .unwrap();
    let pause_msg =
        Message::new_with_blockhash(&[pause_ix], Some(&fixture.payer.pubkey()), &pause_blockhash);
    let pause_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(pause_msg), &[&fixture.payer])
            .unwrap();
    let pause_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(pause_tx, false, false));
    assert!(
        pause_result.is_ok(),
        "Pause instruction failed: {:?}",
        pause_result.err()
    );
    assert!(
        token_2022_mint_is_paused(&svm_locker, &fixture.mint.pubkey()),
        "Pausable mint should report a paused state after pause"
    );

    let post_pause_transfer_amount = 25_000u64;
    let post_pause_transfer_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let post_pause_transfer_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &fixture.payer_ata,
        &fixture.mint.pubkey(),
        &fixture.recipient_ata,
        &fixture.payer.pubkey(),
        &[&fixture.payer.pubkey()],
        post_pause_transfer_amount,
        fixture.decimals,
    )
    .unwrap();
    let post_pause_transfer_msg = Message::new_with_blockhash(
        &[post_pause_transfer_ix],
        Some(&fixture.payer.pubkey()),
        &post_pause_transfer_blockhash,
    );
    let post_pause_transfer_tx = VersionedTransaction::try_new(
        VersionedMessage::Legacy(post_pause_transfer_msg),
        &[&fixture.payer],
    )
    .unwrap();
    let post_pause_transfer_result = svm_locker
        .with_svm_writer(|svm| svm.send_transaction(post_pause_transfer_tx, false, false));
    assert!(
        post_pause_transfer_result.is_err(),
        "Transfers while paused should fail"
    );
    assert_eq!(
        token_2022_account_balance(&svm_locker, &fixture.payer_ata),
        fixture.initial_mint_amount - transfer_amount,
        "Payer ATA balance should remain unchanged when transfers are paused"
    );
    assert_eq!(
        token_2022_account_balance(&svm_locker, &fixture.recipient_ata),
        transfer_amount,
        "Recipient ATA balance should remain unchanged when transfers are paused"
    );

    let post_pause_mint_amount = 50_000u64;
    let post_pause_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let post_pause_mint_ix = mint_to(
        &spl_token_2022_interface::id(),
        &fixture.mint.pubkey(),
        &fixture.recipient_ata,
        &fixture.payer.pubkey(),
        &[&fixture.payer.pubkey()],
        post_pause_mint_amount,
    )
    .unwrap();
    let post_pause_mint_msg = Message::new_with_blockhash(
        &[post_pause_mint_ix],
        Some(&fixture.payer.pubkey()),
        &post_pause_blockhash,
    );
    let post_pause_mint_tx = VersionedTransaction::try_new(
        VersionedMessage::Legacy(post_pause_mint_msg),
        &[&fixture.payer],
    )
    .unwrap();
    let post_pause_mint_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(post_pause_mint_tx, false, false));
    assert!(
        post_pause_mint_result.is_err(),
        "Minting while paused should fail"
    );
    assert_eq!(
        token_2022_account_balance(&svm_locker, &fixture.recipient_ata),
        transfer_amount,
        "Recipient ATA balance should remain unchanged when minting is paused"
    );
}

/// Token-2022 lifecycle:
/// create mint → initialize → create ATA → mint → transfer → burn → close account
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_token2022_full_lifecycle(test_type: TestType) {
    use solana_system_interface::instruction as system_instruction;
    use spl_token_2022_interface::instruction::{
        burn, close_account, initialize_mint2, mint_to, transfer_checked,
    };

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let recipient = Keypair::new();
    let mint = Keypair::new();
    let decimals = 6u8;

    svm_locker
        .airdrop(&payer.pubkey(), 10 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();
    svm_locker
        .airdrop(&recipient.pubkey(), 1 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let mint_rent =
        svm_locker.with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(82));

    let create_mint_ix = system_instruction::create_account(
        &payer.pubkey(),
        &mint.pubkey(),
        mint_rent,
        82,
        &spl_token_2022_interface::id(),
    );

    let init_mint_ix = initialize_mint2(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer.pubkey(),       // mint authority
        Some(&payer.pubkey()), // freeze authority
        decimals,
    )
    .unwrap();

    let payer_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &payer.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let recipient_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_payer_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &payer.pubkey(),
            &payer.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_recipient_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &payer.pubkey(),
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let mint_amount = 1_000_000u64;
    let mint_to_ix = mint_to(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer_ata,
        &payer.pubkey(),
        &[&payer.pubkey()],
        mint_amount,
    )
    .unwrap();

    let setup_msg = Message::new_with_blockhash(
        &[
            create_mint_ix,
            init_mint_ix,
            create_payer_ata_ix,
            create_recipient_ata_ix,
            mint_to_ix,
        ],
        Some(&payer.pubkey()),
        &recent_blockhash,
    );
    let setup_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(setup_msg), &[&payer, &mint])
            .unwrap();

    let setup_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(setup_tx, false, false));
    assert!(
        setup_result.is_ok(),
        "Setup transaction failed: {:?}",
        setup_result.err()
    );

    let transfer_amount = 500_000u64;
    let transfer_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &payer_ata,
        &mint.pubkey(),
        &recipient_ata,
        &payer.pubkey(),
        &[&payer.pubkey()],
        transfer_amount,
        decimals,
    )
    .unwrap();

    let transfer_msg =
        Message::new_with_blockhash(&[transfer_ix], Some(&payer.pubkey()), &recent_blockhash);
    let transfer_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(transfer_msg), &[&payer]).unwrap();

    let transfer_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(transfer_tx, false, false));
    assert!(
        transfer_result.is_ok(),
        "Transfer transaction failed: {:?}",
        transfer_result.err()
    );

    let burn_amount = 200_000u64;
    let burn_ix = burn(
        &spl_token_2022_interface::id(),
        &recipient_ata,
        &mint.pubkey(),
        &recipient.pubkey(),
        &[&recipient.pubkey()],
        burn_amount,
    )
    .unwrap();

    let burn_msg =
        Message::new_with_blockhash(&[burn_ix], Some(&recipient.pubkey()), &recent_blockhash);
    let burn_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(burn_msg), &[&recipient]).unwrap();

    let burn_result = svm_locker.with_svm_writer(|svm| svm.send_transaction(burn_tx, false, false));
    assert!(
        burn_result.is_ok(),
        "Burn transaction failed: {:?}",
        burn_result.err()
    );

    let remaining = transfer_amount - burn_amount;
    let transfer_back_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &recipient_ata,
        &mint.pubkey(),
        &payer_ata,
        &recipient.pubkey(),
        &[&recipient.pubkey()],
        remaining,
        decimals,
    )
    .unwrap();

    let close_ix = close_account(
        &spl_token_2022_interface::id(),
        &recipient_ata,
        &recipient.pubkey(), // destination for rent
        &recipient.pubkey(), // owner
        &[&recipient.pubkey()],
    )
    .unwrap();

    let close_msg = Message::new_with_blockhash(
        &[transfer_back_ix, close_ix],
        Some(&recipient.pubkey()),
        &recent_blockhash,
    );
    let close_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(close_msg), &[&recipient]).unwrap();

    let close_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(close_tx, false, false));
    assert!(
        close_result.is_ok(),
        "Close transaction failed: {:?}",
        close_result.err()
    );

    let recipient_account = svm_locker
        .get_account_local(&recipient_ata)
        .inner
        .map_account()
        .ok();
    assert!(
        recipient_account.is_none() || recipient_account.as_ref().map(|a| a.lamports) == Some(0),
        "Recipient ATA should be closed"
    );

    let expected_balance = mint_amount - burn_amount;
    let _ = expected_balance;
}

/// Token-2022 error cases: transfer/burn > balance and close with balance.
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_token2022_error_cases(test_type: TestType) {
    use solana_system_interface::instruction as system_instruction;
    use spl_token_2022_interface::instruction::{
        burn, close_account, initialize_mint2, mint_to, transfer_checked,
    };

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let recipient = Keypair::new();
    let mint = Keypair::new();
    let decimals = 6u8;

    svm_locker
        .airdrop(&payer.pubkey(), 10 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();
    svm_locker
        .airdrop(&recipient.pubkey(), 1 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let mint_rent =
        svm_locker.with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(82));

    let create_mint_ix = system_instruction::create_account(
        &payer.pubkey(),
        &mint.pubkey(),
        mint_rent,
        82,
        &spl_token_2022_interface::id(),
    );

    let init_mint_ix = initialize_mint2(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer.pubkey(),
        Some(&payer.pubkey()),
        decimals,
    )
    .unwrap();

    let payer_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &payer.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let recipient_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_payer_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &payer.pubkey(),
            &payer.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_recipient_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &payer.pubkey(),
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let mint_amount = 1_000_000u64;
    let mint_to_ix = mint_to(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer_ata,
        &payer.pubkey(),
        &[&payer.pubkey()],
        mint_amount,
    )
    .unwrap();

    let setup_msg = Message::new_with_blockhash(
        &[
            create_mint_ix,
            init_mint_ix,
            create_payer_ata_ix,
            create_recipient_ata_ix,
            mint_to_ix,
        ],
        Some(&payer.pubkey()),
        &recent_blockhash,
    );
    let setup_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(setup_msg), &[&payer, &mint])
            .unwrap();

    let setup_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(setup_tx, false, false));
    assert!(
        setup_result.is_ok(),
        "Setup failed: {:?}",
        setup_result.err()
    );

    let excessive_transfer = mint_amount + 1;
    let bad_transfer_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &payer_ata,
        &mint.pubkey(),
        &recipient_ata,
        &payer.pubkey(),
        &[&payer.pubkey()],
        excessive_transfer,
        decimals,
    )
    .unwrap();

    let bad_transfer_msg =
        Message::new_with_blockhash(&[bad_transfer_ix], Some(&payer.pubkey()), &recent_blockhash);
    let bad_transfer_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(bad_transfer_msg), &[&payer])
            .unwrap();

    let transfer_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(bad_transfer_tx, false, false));
    assert!(
        transfer_result.is_err(),
        "Transfer exceeding balance should fail"
    );

    let excessive_burn = mint_amount + 1;
    let bad_burn_ix = burn(
        &spl_token_2022_interface::id(),
        &payer_ata,
        &mint.pubkey(),
        &payer.pubkey(),
        &[&payer.pubkey()],
        excessive_burn,
    )
    .unwrap();

    let bad_burn_msg =
        Message::new_with_blockhash(&[bad_burn_ix], Some(&payer.pubkey()), &recent_blockhash);
    let bad_burn_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(bad_burn_msg), &[&payer]).unwrap();

    let burn_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(bad_burn_tx, false, false));
    assert!(burn_result.is_err(), "Burn exceeding balance should fail");

    let bad_close_ix = close_account(
        &spl_token_2022_interface::id(),
        &payer_ata,
        &payer.pubkey(),
        &payer.pubkey(),
        &[&payer.pubkey()],
    )
    .unwrap();

    let bad_close_msg =
        Message::new_with_blockhash(&[bad_close_ix], Some(&payer.pubkey()), &recent_blockhash);
    let bad_close_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(bad_close_msg), &[&payer]).unwrap();

    let close_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(bad_close_tx, false, false));
    assert!(
        close_result.is_err(),
        "Close account with balance should fail"
    );
}

/// Token-2022 delegate operations: approve, delegated transfer, revoke.
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_token2022_delegate_operations(test_type: TestType) {
    use solana_system_interface::instruction as system_instruction;
    use spl_token_2022_interface::instruction::{
        approve, initialize_mint2, mint_to, revoke, transfer_checked,
    };

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let owner = Keypair::new();
    let delegate = Keypair::new();
    let recipient = Keypair::new();
    let mint = Keypair::new();
    let decimals = 6u8;

    svm_locker
        .airdrop(&owner.pubkey(), 10 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();
    svm_locker
        .airdrop(&delegate.pubkey(), 1 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let mint_rent =
        svm_locker.with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(82));

    let create_mint_ix = system_instruction::create_account(
        &owner.pubkey(),
        &mint.pubkey(),
        mint_rent,
        82,
        &spl_token_2022_interface::id(),
    );

    let init_mint_ix = initialize_mint2(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &owner.pubkey(),
        None, // no freeze authority needed
        decimals,
    )
    .unwrap();

    let owner_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &owner.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let recipient_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_owner_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &owner.pubkey(),
            &owner.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_recipient_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &owner.pubkey(),
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let mint_amount = 1_000_000u64;
    let mint_to_ix = mint_to(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &owner_ata,
        &owner.pubkey(),
        &[&owner.pubkey()],
        mint_amount,
    )
    .unwrap();

    let setup_msg = Message::new_with_blockhash(
        &[
            create_mint_ix,
            init_mint_ix,
            create_owner_ata_ix,
            create_recipient_ata_ix,
            mint_to_ix,
        ],
        Some(&owner.pubkey()),
        &recent_blockhash,
    );
    let setup_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(setup_msg), &[&owner, &mint])
            .unwrap();

    let setup_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(setup_tx, false, false));
    assert!(
        setup_result.is_ok(),
        "Setup failed: {:?}",
        setup_result.err()
    );

    let delegate_amount = 500_000u64;
    let approve_ix = approve(
        &spl_token_2022_interface::id(),
        &owner_ata,
        &delegate.pubkey(),
        &owner.pubkey(),
        &[&owner.pubkey()],
        delegate_amount,
    )
    .unwrap();

    let approve_msg =
        Message::new_with_blockhash(&[approve_ix], Some(&owner.pubkey()), &recent_blockhash);
    let approve_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(approve_msg), &[&owner]).unwrap();

    let approve_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(approve_tx, false, false));
    assert!(
        approve_result.is_ok(),
        "Approve failed: {:?}",
        approve_result.err()
    );

    let transfer_amount = 200_000u64;
    let delegated_transfer_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &owner_ata,
        &mint.pubkey(),
        &recipient_ata,
        &delegate.pubkey(), // delegate is the authority
        &[&delegate.pubkey()],
        transfer_amount,
        decimals,
    )
    .unwrap();

    let delegated_transfer_msg = Message::new_with_blockhash(
        &[delegated_transfer_ix],
        Some(&delegate.pubkey()),
        &recent_blockhash,
    );
    let delegated_transfer_tx = VersionedTransaction::try_new(
        VersionedMessage::Legacy(delegated_transfer_msg),
        &[&delegate],
    )
    .unwrap();

    let delegated_transfer_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(delegated_transfer_tx, false, false));
    assert!(
        delegated_transfer_result.is_ok(),
        "Delegated transfer failed: {:?}",
        delegated_transfer_result.err()
    );

    let revoke_ix = revoke(
        &spl_token_2022_interface::id(),
        &owner_ata,
        &owner.pubkey(),
        &[&owner.pubkey()],
    )
    .unwrap();

    let revoke_msg =
        Message::new_with_blockhash(&[revoke_ix], Some(&owner.pubkey()), &recent_blockhash);
    let revoke_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(revoke_msg), &[&owner]).unwrap();

    let revoke_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(revoke_tx, false, false));
    assert!(
        revoke_result.is_ok(),
        "Revoke failed: {:?}",
        revoke_result.err()
    );

    let post_revoke_transfer_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &owner_ata,
        &mint.pubkey(),
        &recipient_ata,
        &delegate.pubkey(),
        &[&delegate.pubkey()],
        100_000u64,
        decimals,
    )
    .unwrap();

    let post_revoke_msg = Message::new_with_blockhash(
        &[post_revoke_transfer_ix],
        Some(&delegate.pubkey()),
        &recent_blockhash,
    );
    let post_revoke_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(post_revoke_msg), &[&delegate])
            .unwrap();

    let post_revoke_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(post_revoke_tx, false, false));
    assert!(
        post_revoke_result.is_err(),
        "Transfer after revoke should fail"
    );
}

/// Token-2022 freeze/thaw operations.
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_token2022_freeze_thaw(test_type: TestType) {
    use solana_system_interface::instruction as system_instruction;
    use spl_token_2022_interface::instruction::{
        freeze_account, initialize_mint2, mint_to, thaw_account, transfer_checked,
    };

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let owner = Keypair::new();
    let recipient = Keypair::new();
    let mint = Keypair::new();
    let decimals = 6u8;

    svm_locker
        .airdrop(&owner.pubkey(), 10 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let mint_rent =
        svm_locker.with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(82));

    let create_mint_ix = system_instruction::create_account(
        &owner.pubkey(),
        &mint.pubkey(),
        mint_rent,
        82,
        &spl_token_2022_interface::id(),
    );

    let init_mint_ix = initialize_mint2(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &owner.pubkey(),
        Some(&owner.pubkey()), // freeze authority = owner
        decimals,
    )
    .unwrap();

    let owner_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &owner.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let recipient_ata =
        spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_owner_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &owner.pubkey(),
            &owner.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let create_recipient_ata_ix =
        spl_associated_token_account_interface::instruction::create_associated_token_account(
            &owner.pubkey(),
            &recipient.pubkey(),
            &mint.pubkey(),
            &spl_token_2022_interface::id(),
        );

    let mint_amount = 1_000_000u64;
    let mint_to_ix = mint_to(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &owner_ata,
        &owner.pubkey(),
        &[&owner.pubkey()],
        mint_amount,
    )
    .unwrap();

    let setup_msg = Message::new_with_blockhash(
        &[
            create_mint_ix,
            init_mint_ix,
            create_owner_ata_ix,
            create_recipient_ata_ix,
            mint_to_ix,
        ],
        Some(&owner.pubkey()),
        &recent_blockhash,
    );
    let setup_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(setup_msg), &[&owner, &mint])
            .unwrap();

    let setup_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(setup_tx, false, false));
    assert!(
        setup_result.is_ok(),
        "Setup failed: {:?}",
        setup_result.err()
    );

    let freeze_ix = freeze_account(
        &spl_token_2022_interface::id(),
        &owner_ata,
        &mint.pubkey(),
        &owner.pubkey(), // freeze authority
        &[&owner.pubkey()],
    )
    .unwrap();

    let freeze_msg =
        Message::new_with_blockhash(&[freeze_ix], Some(&owner.pubkey()), &recent_blockhash);
    let freeze_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(freeze_msg), &[&owner]).unwrap();

    let freeze_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(freeze_tx, false, false));
    assert!(
        freeze_result.is_ok(),
        "Freeze failed: {:?}",
        freeze_result.err()
    );

    let transfer_amount = 100_000u64;
    let frozen_transfer_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &owner_ata,
        &mint.pubkey(),
        &recipient_ata,
        &owner.pubkey(),
        &[&owner.pubkey()],
        transfer_amount,
        decimals,
    )
    .unwrap();

    let frozen_transfer_msg = Message::new_with_blockhash(
        &[frozen_transfer_ix],
        Some(&owner.pubkey()),
        &recent_blockhash,
    );
    let frozen_transfer_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(frozen_transfer_msg), &[&owner])
            .unwrap();

    let frozen_transfer_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(frozen_transfer_tx, false, false));
    assert!(
        frozen_transfer_result.is_err(),
        "Transfer from frozen account should fail"
    );

    let fresh_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    let thaw_ix = thaw_account(
        &spl_token_2022_interface::id(),
        &owner_ata,
        &mint.pubkey(),
        &owner.pubkey(), // freeze authority
        &[&owner.pubkey()],
    )
    .unwrap();

    let thaw_msg = Message::new_with_blockhash(&[thaw_ix], Some(&owner.pubkey()), &fresh_blockhash);
    let thaw_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(thaw_msg), &[&owner]).unwrap();

    let thaw_result = svm_locker.with_svm_writer(|svm| svm.send_transaction(thaw_tx, false, false));
    assert!(thaw_result.is_ok(), "Thaw failed: {:?}", thaw_result.err());
    println!("✓ Step 3: Account thawed");

    // === Step 4: Verify transfer works after thaw ===
    // Use a different amount to ensure unique transaction signature
    let post_thaw_amount = 50_000u64; // Different from step 2's amount
    let post_thaw_transfer_ix = transfer_checked(
        &spl_token_2022_interface::id(),
        &owner_ata,
        &mint.pubkey(),
        &recipient_ata,
        &owner.pubkey(),
        &[&owner.pubkey()],
        post_thaw_amount,
        decimals,
    )
    .unwrap();

    let post_thaw_msg = Message::new_with_blockhash(
        &[post_thaw_transfer_ix],
        Some(&owner.pubkey()),
        &fresh_blockhash,
    );
    let post_thaw_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(post_thaw_msg), &[&owner]).unwrap();

    let post_thaw_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(post_thaw_tx, false, false));
    assert!(
        post_thaw_result.is_ok(),
        "Transfer after thaw failed: {:?}",
        post_thaw_result.err()
    );
    println!(
        "✓ Step 4: Transfer after thaw succeeded ({} tokens)",
        post_thaw_amount
    );

    println!("✓ All freeze/thaw operations work correctly!");
}

use std::sync::Once;

static INIT_LOGGER: Once = Once::new();

fn setup() {
    INIT_LOGGER.call_once(|| {
        env_logger::builder().is_test(true).try_init().unwrap();
    });
}

#[test]
fn test_nonce_accounts() {
    setup();
    use solana_system_interface::instruction::create_nonce_account;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let nonce_account = Keypair::new();
    println!("Payer Pubkey: {}", payer.pubkey());
    println!("Nonce Account Pubkey: {}", nonce_account.pubkey());
    println!("Nonce authority: {}", payer.pubkey());

    svm_locker
        .airdrop(&payer.pubkey(), 5 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let nonce_rent = svm_locker.with_svm_reader(|svm_reader| {
        svm_reader
            .inner
            .minimum_balance_for_rent_exemption(solana_nonce::state::State::size())
    });
    let create_nonce_ix = create_nonce_account(
        &payer.pubkey(),
        &nonce_account.pubkey(),
        &payer.pubkey(), // Make the fee payer the nonce account authority
        nonce_rent,
    );

    let recent_blockhash = svm_locker.latest_absolute_blockhash();

    let create_nonce_msg =
        Message::new_with_blockhash(&create_nonce_ix, Some(&payer.pubkey()), &recent_blockhash);
    let create_nonce_tx = VersionedTransaction::try_new(
        VersionedMessage::Legacy(create_nonce_msg),
        &[&payer, &nonce_account],
    )
    .unwrap();

    let create_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(create_nonce_tx, false, false));
    assert!(
        create_result.is_ok(),
        "Create nonce account failed: {:?}",
        create_result.err()
    );

    // Fetch and verify nonce account state
    let nonce_account_data = svm_locker
        .get_account_local(&nonce_account.pubkey())
        .inner
        .map_account()
        .expect("Failed to fetch nonce account");

    let state: solana_nonce::versions::Versions = bincode::deserialize(&nonce_account_data.data)
        .expect("Failed to deserialize nonce account state");

    let state = state.state();

    let nonce_hash = match state {
        solana_nonce::state::State::Initialized(nonce_data) => {
            println!(
                "✓ Nonce account initialized with nonce: {:?}",
                nonce_data.durable_nonce
            );
            nonce_data.blockhash()
        }
        _ => panic!("Nonce account is not initialized"),
    };

    let to_pubkey = Pubkey::new_unique();
    // Use the nonce in a transaction
    let transfer_ix =
        solana_system_interface::instruction::transfer(&payer.pubkey(), &to_pubkey, 1_000_000);
    let mut nonce_msg = Message::new_with_nonce(
        vec![transfer_ix],
        Some(&payer.pubkey()),
        &nonce_account.pubkey(),
        &payer.pubkey(),
    );
    nonce_msg.recent_blockhash = nonce_hash;
    let nonce_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(nonce_msg), &[&payer]).unwrap();

    let nonce_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(nonce_tx, false, false));
    assert!(
        nonce_result.is_ok(),
        "Transaction using nonce failed: {:?}",
        nonce_result.err()
    );

    // Verify to_pubkey received the funds
    let to_account_data = svm_locker
        .get_account_local(&to_pubkey)
        .inner
        .map_account()
        .expect("Failed to fetch recipient account");
    assert_eq!(
        to_account_data.lamports, 1_000_000,
        "Recipient account did not receive correct amount"
    );
}

/// Tests that profiling a transaction does not mutate the original SVM state.
/// This verifies the OverlayStorage implementation correctly isolates mutations
/// during profiling from the underlying database.
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_profile_transaction_does_not_mutate_state(test_type: TestType) {
    let (mut svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let rpc_server = crate::rpc::surfnet_cheatcodes::SurfnetCheatcodesRpc::empty();

    // Setup: Create accounts and fund the payer
    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = 1_000_000;
    let initial_payer_balance = lamports_to_send * 10;

    svm_instance
        .airdrop(&payer.pubkey(), initial_payer_balance)
        .unwrap()
        .unwrap();

    // Create a transfer transaction
    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_instance.latest_blockhash();
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message.clone()), &[&payer])
        .unwrap();

    let tx_bytes = bincode::serialize(&tx).unwrap();
    let tx_b64 = base64::engine::general_purpose::STANDARD.encode(&tx_bytes);

    // Record initial state BEFORE profiling
    let initial_transactions_processed = svm_instance.transactions_processed;
    let initial_payer_account = svm_instance.get_account(&payer.pubkey()).unwrap();
    let initial_recipient_account = svm_instance.get_account(&recipient).ok().flatten();

    // Create the locker and runloop context
    let svm_locker = SurfnetSvmLocker::new(svm_instance);
    let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
    let (plugin_commands_tx, _plugin_commands_rx) = crossbeam_channel::unbounded::<PluginCommand>();

    let runloop_context = RunloopContext {
        id: None,
        svm_locker: svm_locker.clone(),
        simnet_commands_tx: simnet_cmd_tx,
        remote_rpc_client: None,
        rpc_config: RpcConfig::default(),
        cheatcode_config: CheatcodeConfig::new(),
        plugin_commands_tx,
    };

    // Profile the transaction multiple times to ensure no state leakage
    for i in 0..3 {
        let response: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
            .profile_transaction(
                Some(runloop_context.clone()),
                tx_b64.clone(),
                Some(format!("test_isolation_{}", i)),
                None,
            )
            .await;

        assert!(
            response.is_ok(),
            "Profile transaction {} failed: {:?}",
            i,
            response.err()
        );

        let profile_result = response.unwrap().value;
        assert!(
            profile_result.transaction_profile.error_message.is_none(),
            "Profile {} had unexpected error: {:?}",
            i,
            profile_result.transaction_profile.error_message
        );

        // The profile should show the transaction would succeed
        assert!(
            profile_result.transaction_profile.compute_units_consumed > 0,
            "Profile {} should show compute units consumed",
            i
        );
    }

    // Verify state is UNCHANGED after profiling
    let final_transactions_processed = svm_locker.with_svm_reader(|svm| svm.transactions_processed);
    let final_payer_account = svm_locker
        .with_svm_reader(|svm| svm.get_account(&payer.pubkey()))
        .unwrap();
    let final_recipient_account = svm_locker
        .with_svm_reader(|svm| svm.get_account(&recipient))
        .ok()
        .flatten();

    // Transaction count should not have increased from profiling
    assert_eq!(
        initial_transactions_processed, final_transactions_processed,
        "transactions_processed should not change from profiling"
    );

    // Payer balance should be unchanged (transfer was only simulated)
    assert_eq!(
        initial_payer_account.as_ref().map(|a| a.lamports),
        final_payer_account.as_ref().map(|a| a.lamports),
        "Payer balance should not change from profiling"
    );

    // Recipient should still not exist or have the same balance
    assert_eq!(
        initial_recipient_account.as_ref().map(|a| a.lamports),
        final_recipient_account.as_ref().map(|a| a.lamports),
        "Recipient balance should not change from profiling"
    );

    // Now actually execute the transaction to prove the state can still be mutated
    let execution_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(tx.clone(), false, false));

    assert!(
        execution_result.is_ok(),
        "Actual transaction execution should succeed: {:?}",
        execution_result.err()
    );

    // Verify state DID change after actual execution
    let post_execution_transactions = svm_locker.with_svm_reader(|svm| svm.transactions_processed);
    let post_execution_recipient = svm_locker
        .with_svm_reader(|svm| svm.get_account(&recipient))
        .unwrap();

    assert_eq!(
        post_execution_transactions,
        initial_transactions_processed + 1,
        "Transaction count should increase after actual execution"
    );

    assert!(
        post_execution_recipient.is_some(),
        "Recipient should exist after actual execution"
    );

    assert_eq!(
        post_execution_recipient.unwrap().lamports,
        lamports_to_send,
        "Recipient should have received funds after actual execution"
    );
}

/// Tests that instruction-level profiling during transaction execution does not
/// mutate the original SVM state for failed transactions.
/// This creates a transaction with two instructions where:
/// - First instruction: a transfer that would succeed
/// - Second instruction: a transfer that will fail (insufficient funds)
/// The test verifies that even though the first instruction is profiled successfully
/// during execution, its effects are not persisted since the overall transaction fails.
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_instruction_profiling_does_not_mutate_state(test_type: TestType) {
    let (mut svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();

    // Verify instruction profiling is enabled by default
    assert!(
        svm_instance.instruction_profiling_enabled,
        "Instruction profiling should be enabled by default"
    );

    // Setup: Create accounts
    let payer = Keypair::new();
    let payer_without_funds = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = LAMPORTS_PER_SOL;

    // Fund only the first payer
    svm_instance
        .airdrop(&payer.pubkey(), lamports_to_send * 3)
        .unwrap()
        .unwrap();

    // Record initial state BEFORE processing
    let initial_payer_balance = svm_instance
        .get_account(&payer.pubkey())
        .unwrap()
        .map(|a| a.lamports)
        .unwrap_or(0);
    let initial_recipient_account = svm_instance.get_account(&recipient).ok().flatten();
    let initial_transactions_processed = svm_instance.transactions_processed;

    // Create a multi-instruction transaction where:
    // - First instruction: valid transfer from payer to recipient (would succeed alone)
    // - Second instruction: invalid transfer from unfunded account (will fail)
    let valid_instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let invalid_instruction = transfer(&payer_without_funds.pubkey(), &recipient, lamports_to_send);

    let latest_blockhash = svm_instance.latest_blockhash();
    let message = Message::new_with_blockhash(
        &[valid_instruction, invalid_instruction],
        Some(&payer.pubkey()),
        &latest_blockhash,
    );
    let transaction = VersionedTransaction::try_new(
        VersionedMessage::Legacy(message),
        &[&payer, &payer_without_funds],
    )
    .unwrap();
    let signature = transaction.signatures[0];

    // Create the locker and status channel for transaction processing
    let svm_locker = SurfnetSvmLocker::new(svm_instance);
    let (status_tx, _status_rx) = crossbeam_unbounded::<TransactionStatusEvent>();

    // Process the transaction using the actual execution path
    // This will trigger instruction-level profiling since it's enabled by default
    let process_result = svm_locker
        .process_transaction(
            &None, // no remote context
            transaction.clone(),
            status_tx,
            true,  // skip_preflight
            false, // sigverify
        )
        .await;

    // The transaction should fail due to the second instruction
    // But the profile result should still be written
    assert!(
        process_result.is_err() || process_result.is_ok(),
        "process_transaction should complete (success or failure)"
    );

    // Retrieve the profile result using the signature
    let key = UuidOrSignature::Signature(signature);
    let profile_result = svm_locker
        .get_profile_result(key, &RpcProfileResultConfig::default())
        .unwrap()
        .expect("Profile result should exist for executed transaction");

    // Verify the overall transaction failed (due to second instruction)
    assert!(
        profile_result.transaction_profile.error_message.is_some(),
        "Transaction should fail due to second instruction's insufficient funds"
    );

    // Verify instruction profiles were generated
    assert!(
        profile_result.instruction_profiles.is_some(),
        "Instruction profiles should be generated when instruction profiling is enabled"
    );

    let instruction_profiles = profile_result.instruction_profiles.as_ref().unwrap();
    assert_eq!(
        instruction_profiles.len(),
        2,
        "Should have profiles for both instructions"
    );

    // Verify first instruction profile shows SUCCESS (it was profiled independently)
    let first_ix_profile = &instruction_profiles[0];
    assert!(
        first_ix_profile.error_message.is_none(),
        "First instruction profile should succeed: {:?}",
        first_ix_profile.error_message
    );
    assert!(
        first_ix_profile.compute_units_consumed > 0,
        "First instruction should have consumed compute units"
    );

    // Verify second instruction profile shows FAILURE
    let second_ix_profile = &instruction_profiles[1];
    assert!(
        second_ix_profile.error_message.is_some(),
        "Second instruction should fail due to insufficient funds"
    );

    // NOW THE CRITICAL PART: Verify that instruction profiling didn't leak state
    // Even though the first instruction was profiled successfully, its effects
    // should NOT be persisted because:
    // 1. The instruction profiling uses clone_for_profiling() with OverlayStorage
    // 2. The overall transaction failed, so no state changes are committed
    //
    // Note: Failed transactions in Solana still deduct fees from the fee payer.
    // This is expected behavior and not related to instruction profiling.

    let final_payer_balance = svm_locker
        .with_svm_reader(|svm| svm.get_account(&payer.pubkey()))
        .unwrap()
        .map(|a| a.lamports)
        .unwrap_or(0);
    let final_recipient_account = svm_locker
        .with_svm_reader(|svm| svm.get_account(&recipient))
        .ok()
        .flatten();
    let final_transactions_processed = svm_locker.with_svm_reader(|svm| svm.transactions_processed);

    // THE KEY ASSERTION: Recipient should NOT have received funds
    // This proves that the first instruction's transfer (which was profiled successfully)
    // was NOT committed to the actual state. The instruction profiling used
    // clone_for_profiling() so its mutations were isolated.
    assert_eq!(
        initial_recipient_account.as_ref().map(|a| a.lamports),
        final_recipient_account.as_ref().map(|a| a.lamports),
        "Recipient should not have received funds - instruction profiling must not leak state"
    );

    // Payer balance should only decrease by the transaction fee (not by the transfer amount)
    // Failed transactions still pay fees in Solana, but the transfer should not have occurred
    let balance_decrease = initial_payer_balance.saturating_sub(final_payer_balance);
    assert!(
        balance_decrease < lamports_to_send,
        "Payer should only lose transaction fee, not the transfer amount. Lost: {} lamports",
        balance_decrease
    );

    // Transaction count increments even for failed transactions (they were still processed)
    // This is expected behavior - we're verifying instruction profiling isolation, not tx count
    assert_eq!(
        final_transactions_processed,
        initial_transactions_processed + 1,
        "Transaction count should increment after processing (even for failed tx)"
    );
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_program_subscribe_basic(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let program_id = Pubkey::new_unique();
    let account_pubkey = Pubkey::new_unique();

    // Subscribe to program updates
    let program_rx = svm_locker.subscribe_for_program_updates(
        &program_id,
        Some(UiAccountEncoding::Base64),
        None,
    );

    // Set an account owned by the program
    let account = Account {
        lamports: 1_000_000,
        data: vec![1, 2, 3, 4],
        owner: program_id,
        executable: false,
        rent_epoch: 0,
    };
    svm_locker.with_svm_writer(|svm| {
        svm.set_account(&account_pubkey, account).unwrap();
    });

    // Should receive a notification
    let update = program_rx.recv_timeout(Duration::from_secs(5));
    assert!(update.is_ok(), "Should receive program account update");

    let keyed_account = update.unwrap();
    assert_eq!(
        keyed_account.pubkey,
        account_pubkey.to_string(),
        "Notification should contain the correct account pubkey"
    );
    assert_eq!(
        keyed_account.account.lamports, 1_000_000,
        "Notification should contain the correct lamports"
    );
    println!("✓ programSubscribe basic flow works correctly");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_program_subscribe_data_size_filter(test_type: TestType) {
    use solana_client::rpc_filter::RpcFilterType;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let program_id = Pubkey::new_unique();

    // Subscribe with a dataSize filter for accounts with exactly 8 bytes of data
    let filters = vec![RpcFilterType::DataSize(8)];
    let program_rx = svm_locker.subscribe_for_program_updates(
        &program_id,
        Some(UiAccountEncoding::Base64),
        Some(filters),
    );

    // Set an account with 4 bytes (should NOT trigger notification)
    let small_account_pubkey = Pubkey::new_unique();
    let small_account = Account {
        lamports: 1_000_000,
        data: vec![1, 2, 3, 4],
        owner: program_id,
        executable: false,
        rent_epoch: 0,
    };
    svm_locker.with_svm_writer(|svm| {
        svm.set_account(&small_account_pubkey, small_account)
            .unwrap();
    });

    // Should NOT receive a notification for the 4-byte account
    let no_update = program_rx.recv_timeout(Duration::from_millis(200));
    assert!(
        no_update.is_err(),
        "Should NOT receive notification for account that doesn't match dataSize filter"
    );

    // Set an account with 8 bytes (SHOULD trigger notification)
    let matching_account_pubkey = Pubkey::new_unique();
    let matching_account = Account {
        lamports: 2_000_000,
        data: vec![1, 2, 3, 4, 5, 6, 7, 8],
        owner: program_id,
        executable: false,
        rent_epoch: 0,
    };
    svm_locker.with_svm_writer(|svm| {
        svm.set_account(&matching_account_pubkey, matching_account)
            .unwrap();
    });

    // Should receive a notification for the 8-byte account
    let update = program_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        update.is_ok(),
        "Should receive notification for account matching dataSize filter"
    );

    let keyed_account = update.unwrap();
    assert_eq!(
        keyed_account.pubkey,
        matching_account_pubkey.to_string(),
        "Notification should contain the correct matching account pubkey"
    );
    println!("✓ programSubscribe with dataSize filter works correctly");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_program_subscribe_memcmp_filter(test_type: TestType) {
    use solana_client::rpc_filter::{Memcmp, RpcFilterType};

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let program_id = Pubkey::new_unique();

    // Subscribe with a memcmp filter: offset 0, bytes [0xAA, 0xBB]
    let filters = vec![RpcFilterType::Memcmp(Memcmp::new_raw_bytes(
        0,
        vec![0xAA, 0xBB],
    ))];
    let program_rx = svm_locker.subscribe_for_program_updates(
        &program_id,
        Some(UiAccountEncoding::Base64),
        Some(filters),
    );

    // Set an account that doesn't match the memcmp filter
    let non_matching_pubkey = Pubkey::new_unique();
    let non_matching_account = Account {
        lamports: 1_000_000,
        data: vec![0x00, 0x00, 0xCC, 0xDD],
        owner: program_id,
        executable: false,
        rent_epoch: 0,
    };
    svm_locker.with_svm_writer(|svm| {
        svm.set_account(&non_matching_pubkey, non_matching_account)
            .unwrap();
    });

    // Should NOT receive a notification
    let no_update = program_rx.recv_timeout(Duration::from_millis(200));
    assert!(
        no_update.is_err(),
        "Should NOT receive notification for account that doesn't match memcmp filter"
    );

    // Set an account that matches the memcmp filter
    let matching_pubkey = Pubkey::new_unique();
    let matching_account = Account {
        lamports: 2_000_000,
        data: vec![0xAA, 0xBB, 0xCC, 0xDD],
        owner: program_id,
        executable: false,
        rent_epoch: 0,
    };
    svm_locker.with_svm_writer(|svm| {
        svm.set_account(&matching_pubkey, matching_account).unwrap();
    });

    // Should receive a notification
    let update = program_rx.recv_timeout(Duration::from_secs(5));
    assert!(
        update.is_ok(),
        "Should receive notification for account matching memcmp filter"
    );

    let keyed_account = update.unwrap();
    assert_eq!(
        keyed_account.pubkey,
        matching_pubkey.to_string(),
        "Notification should contain the correct matching account pubkey"
    );
    println!("✓ programSubscribe with memcmp filter works correctly");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_program_unsubscribe(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let program_id = Pubkey::new_unique();

    // Subscribe to program updates
    let program_rx = svm_locker.subscribe_for_program_updates(
        &program_id,
        Some(UiAccountEncoding::Base64),
        None,
    );

    // Verify subscription works by setting an account
    let account_pubkey = Pubkey::new_unique();
    let account = Account {
        lamports: 1_000_000,
        data: vec![1, 2, 3, 4],
        owner: program_id,
        executable: false,
        rent_epoch: 0,
    };
    svm_locker.with_svm_writer(|svm| {
        svm.set_account(&account_pubkey, account).unwrap();
    });

    let update = program_rx.recv_timeout(Duration::from_secs(5));
    assert!(update.is_ok(), "Should receive first notification");

    // Drop the receiver to simulate unsubscribe
    drop(program_rx);

    // Set another account - this should not panic or error
    let account_pubkey2 = Pubkey::new_unique();
    let account2 = Account {
        lamports: 2_000_000,
        data: vec![5, 6, 7, 8],
        owner: program_id,
        executable: false,
        rent_epoch: 0,
    };
    svm_locker.with_svm_writer(|svm| {
        svm.set_account(&account_pubkey2, account2).unwrap();
    });

    println!("✓ programUnsubscribe works correctly (no panic after receiver dropped)");
}

#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_ws_program_subscribe_wrong_owner(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let subscribed_program_id = Pubkey::new_unique();
    let other_program_id = Pubkey::new_unique();

    // Subscribe to updates for subscribed_program_id
    let program_rx = svm_locker.subscribe_for_program_updates(
        &subscribed_program_id,
        Some(UiAccountEncoding::Base64),
        None,
    );

    // Set an account owned by a DIFFERENT program
    let account_pubkey = Pubkey::new_unique();
    let account = Account {
        lamports: 1_000_000,
        data: vec![1, 2, 3, 4],
        owner: other_program_id,
        executable: false,
        rent_epoch: 0,
    };
    svm_locker.with_svm_writer(|svm| {
        svm.set_account(&account_pubkey, account).unwrap();
    });

    // Should NOT receive a notification since the account is owned by a different program
    let no_update = program_rx.recv_timeout(Duration::from_millis(200));
    assert!(
        no_update.is_err(),
        "Should NOT receive notification for account owned by a different program"
    );
    println!("✓ programSubscribe correctly ignores accounts owned by other programs");
}

/// Regression test for issue #530: Token-2022's TokenMetadataInstruction::Initialize
/// previously failed with "Failed to reallocate account data".
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_token2022_metadata_realloc(test_type: TestType) {
    use solana_system_interface::instruction as system_instruction;
    use spl_token_2022_interface::{
        extension::{ExtensionType, metadata_pointer},
        instruction::initialize_mint2,
        pod::PodMint,
    };

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let mint = Keypair::new();
    let decimals = 6u8;

    svm_locker
        .airdrop(&payer.pubkey(), 10 * LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    // Calculate space for mint with MetadataPointer + MintCloseAuthority extensions only.
    // NOT pre-sized for metadata content — the CPI realloc will need to grow it.
    let mint_space =
        ExtensionType::try_calculate_account_len::<PodMint>(&[ExtensionType::MetadataPointer])
            .unwrap();

    // Exact minimum rent
    let mint_rent =
        svm_locker.with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(mint_space));

    // --- Transaction 1: Setup (create mint with MetadataPointer) ---

    let create_account_ix = system_instruction::create_account(
        &payer.pubkey(),
        &mint.pubkey(),
        mint_rent,
        mint_space as u64,
        &spl_token_2022_interface::id(),
    );

    // Initialize metadata pointer to the mint itself (must come before mint init)
    let init_metadata_pointer_ix = metadata_pointer::instruction::initialize(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        Some(payer.pubkey()),
        Some(mint.pubkey()),
    )
    .unwrap();

    let init_mint_ix = initialize_mint2(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer.pubkey(),
        None,
        decimals,
    )
    .unwrap();

    let setup_msg = Message::new_with_blockhash(
        &[create_account_ix, init_metadata_pointer_ix, init_mint_ix],
        Some(&payer.pubkey()),
        &recent_blockhash,
    );

    let setup_tx =
        VersionedTransaction::try_new(VersionedMessage::Legacy(setup_msg), &[&payer, &mint])
            .unwrap();
    let setup_result =
        svm_locker.with_svm_writer(|svm| svm.send_transaction(setup_tx, false, false));

    assert!(
        setup_result.is_ok(),
        "Setup transaction (create mint with MetadataPointer) \
         should succeed: {:?}",
        setup_result,
    );
    println!("✓ Setup transaction succeeded");

    // --- Transaction 2: Increase rent and initialize metadata reproduces bug #530) ---

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    // Increase mint account lamports to ensure it can cover the cost of realloc during CPI.
    let increase_mint_rent_ix =
        system_instruction::transfer(&payer.pubkey(), &mint.pubkey(), LAMPORTS_PER_SOL);

    // Build the metadata initialize instruction data (discriminator + borsh-serialized fields).
    // We extract the data bytes from a properly-encoded instruction to pass through our CPI fixture.
    let metadata_ix_data = spl_token_metadata_interface::instruction::initialize(
        &spl_token_2022_interface::id(),
        &mint.pubkey(),
        &payer.pubkey(),
        &mint.pubkey(),
        &payer.pubkey(),
        "Test Token".to_string(),
        "TST".to_string(),
        "https://example.com/metadata.json".to_string(),
    );

    let msg = Message::new_with_blockhash(
        &[increase_mint_rent_ix, metadata_ix_data],
        Some(&payer.pubkey()),
        &recent_blockhash,
    );

    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(msg), &[&payer]).unwrap();
    let result = svm_locker.with_svm_writer(|svm| svm.send_transaction(tx, false, false));

    // Regression test for #530: CPI realloc previously failed when Token-2022
    // tried to realloc the mint account to store metadata
    assert!(
        result.is_ok(),
        "CPI metadata initialization should succeed (regression test for #530): {:?}",
        result,
    );
    println!("✓ Regression test #530: Token-2022 metadata CPI realloc works correctly");
}

async fn test_duplicate_transaction_rejected(test_type: TestType) {
    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    let recipient = Pubkey::new_unique();
    let lamports_to_send = 1_000_000;

    // Airdrop SOL to payer
    svm_locker
        .with_svm_writer(|svm| svm.airdrop(&payer.pubkey(), lamports_to_send * 10))
        .unwrap()
        .unwrap();

    // Build a transfer transaction
    let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
    let latest_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message =
        Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
    let transaction =
        VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    // First submission should succeed
    let (status_tx, status_rx) = crossbeam_unbounded();
    svm_locker
        .process_transaction(&None, transaction.clone(), status_tx, false, true)
        .await
        .unwrap();

    match status_rx.recv() {
        Ok(TransactionStatusEvent::Success(_)) => {
            println!("First transaction processed successfully");
        }
        other => {
            panic!("Expected first transaction to succeed, got: {:?}", other);
        }
    }

    // Second submission of the same transaction should be rejected
    let (status_tx2, status_rx2) = crossbeam_unbounded();
    let result = svm_locker
        .process_transaction(&None, transaction.clone(), status_tx2, false, true)
        .await;

    assert!(result.is_err(), "Duplicate transaction should be rejected");

    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("already been processed"),
        "Error should mention 'already been processed', got: {err_msg}"
    );

    // Status channel should receive a VerificationFailure
    match status_rx2.recv() {
        Ok(TransactionStatusEvent::VerificationFailure(msg)) => {
            assert!(
                msg.contains("already been processed"),
                "VerificationFailure should mention 'already been processed', got: {msg}"
            );
            println!("Duplicate correctly rejected with VerificationFailure");
        }
        other => {
            panic!(
                "Expected VerificationFailure on status channel, got: {:?}",
                other
            );
        }
    }

    // Verify the original transaction data is still stored correctly
    let sig = transaction.signatures[0].to_string();
    let stored = svm_locker.with_svm_reader(|svm| svm.transactions.get(&sig));
    assert!(
        matches!(
            stored,
            Ok(Some(crate::types::SurfnetTransactionStatus::Processed(_)))
        ),
        "Original transaction should still be stored as Processed"
    );

    println!("Duplicate transaction rejection test passed!");
}

// ============================================================================
// AccountLoadedTwice: V0 transactions with duplicate accounts in static keys + ALT
// ============================================================================
// When a V0 transaction has an account in both its static keys and an Address
// Lookup Table, Agave rejects pre-execution with AccountLoadedTwice (0 CU).
// Surfpool must match this behavior.
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_account_loaded_twice_rejected(test_type: TestType) {
    let (svm_locker, _simnet_cmd_tx, _simnet_events_rx) =
        boot_simnet(BlockProductionMode::Clock, Some(400), test_type);

    let payer = Keypair::new();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());

    // Create an ALT that contains system_program (11111...111)
    let alt_key = Pubkey::new_unique();
    let system_program_id = system_program::id();

    let alt_account_data = AddressLookupTable {
        meta: LookupTableMeta {
            authority: Some(payer.pubkey()),
            ..Default::default()
        },
        addresses: vec![system_program_id].into(),
    };

    svm_locker.with_svm_writer(|svm| {
        let alt_data = alt_account_data.serialize_for_tests().unwrap();
        let alt_account = Account {
            lamports: 1_000_000,
            data: alt_data,
            owner: solana_address_lookup_table_interface::program::id(),
            executable: false,
            rent_epoch: 0,
        };
        svm.set_account(&alt_key, alt_account).unwrap();
    });

    // Build a V0 message that has system_program in BOTH static keys AND the ALT.
    // try_compile would deduplicate, so we build the message manually.
    let recipient = Pubkey::new_unique();
    let v0_message = v0::Message {
        header: MessageHeader {
            num_required_signatures: 1,
            num_readonly_signed_accounts: 0,
            // system_program is readonly unsigned
            num_readonly_unsigned_accounts: 1,
        },
        // Static keys: [payer (signer+writable), recipient (writable), system_program (readonly)]
        account_keys: vec![payer.pubkey(), recipient, system_program_id],
        recent_blockhash,
        // A simple transfer instruction: program_id_index=2 (system_program),
        // accounts=[0 (payer), 1 (recipient)]
        instructions: vec![solana_message::compiled_instruction::CompiledInstruction {
            program_id_index: 2,
            accounts: vec![0, 1],
            data: {
                // system_instruction::transfer encodes as: [2,0,0,0] + 8-byte LE amount
                let mut data = vec![2, 0, 0, 0];
                data.extend_from_slice(&100u64.to_le_bytes());
                data
            },
        }],
        // ALT lookup that also loads system_program (index 0 in the ALT) as readonly
        address_table_lookups: vec![MessageAddressTableLookup {
            account_key: alt_key,
            writable_indexes: vec![],
            readonly_indexes: vec![0], // system_program is at index 0 in the ALT
        }],
    };

    let tx = VersionedTransaction::try_new(VersionedMessage::V0(v0_message), &[&payer])
        .expect("Failed to create transaction");

    let (status_tx, _status_rx) = crossbeam_channel::unbounded();
    let result = svm_locker
        .process_transaction(&None, tx, status_tx, false, true)
        .await;

    assert!(
        result.is_err(),
        "Transaction with duplicate account should be rejected, got: {:?}",
        result
    );
    let err_string = result.unwrap_err().to_string();
    assert!(
        err_string.contains("Account loaded twice"),
        "Expected AccountLoadedTwice error, got: {}",
        err_string
    );

    println!("AccountLoadedTwice rejection test passed!");
}

// ============================================================================
// Regression #684: finalized slot must be recent enough for ALT creation
// ============================================================================
// Address lookup table creation validates the provided recent_slot against the
// SlotHashes sysvar. Client code commonly passes getSlot(finalized), which
// should remain inside SlotHashes' 512-entry retention window.
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_create_lookup_table_with_finalized_slot(test_type: TestType) {
    use solana_slot_hashes::SlotHashes;

    let (svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
    let svm_locker = SurfnetSvmLocker::new(svm_instance);

    let payer = Keypair::new();
    svm_locker
        .airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)
        .unwrap()
        .unwrap();

    while svm_locker.get_latest_absolute_slot() < 40 {
        svm_locker.confirm_current_block(&None).await.unwrap();
    }

    let processed_slot = svm_locker.get_slot_for_commitment(&CommitmentConfig::processed());
    let finalized_slot = svm_locker.get_slot_for_commitment(&CommitmentConfig::finalized());

    assert_eq!(
        finalized_slot,
        processed_slot.saturating_sub(FINALIZATION_SLOT_THRESHOLD),
        "test setup should mirror Surfpool's finalized slot lag"
    );

    let slot_hash_slots = svm_locker.with_svm_reader(|svm| {
        svm.inner
            .get_sysvar::<SlotHashes>()
            .slot_hashes()
            .iter()
            .map(|(slot, _)| *slot)
            .collect::<Vec<_>>()
    });
    assert!(
        slot_hash_slots.contains(&finalized_slot),
        "SlotHashes should contain finalized_slot={finalized_slot}; entries={slot_hash_slots:?}"
    );

    let (create_lookup_table_ix, lookup_table_address) =
        address_lookup_table_instruction::create_lookup_table(
            payer.pubkey(),
            payer.pubkey(),
            finalized_slot,
        );
    let recent_blockhash = svm_locker.with_svm_reader(|svm| svm.latest_blockhash());
    let message = Message::new_with_blockhash(
        &[create_lookup_table_ix],
        Some(&payer.pubkey()),
        &recent_blockhash,
    );
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message), &[&payer]).unwrap();

    let (status_tx, status_rx) = crossbeam_unbounded();
    let result = svm_locker
        .process_transaction(&None, tx, status_tx, false, true)
        .await;
    assert!(
        result.is_ok(),
        "CreateLookupTable should accept getSlot(finalized) as recent_slot; \
         processed_slot={processed_slot}, finalized_slot={finalized_slot}, \
         SlotHashes entries={slot_hash_slots:?}, result={result:?}"
    );

    match status_rx.recv_timeout(Duration::from_secs(5)) {
        Ok(TransactionStatusEvent::Success(_)) => {}
        other => panic!(
            "CreateLookupTable should succeed, got: {other:?}; \
             processed_slot={processed_slot}, finalized_slot={finalized_slot}, \
             SlotHashes entries={slot_hash_slots:?}"
        ),
    }

    let lookup_table_account = svm_locker
        .with_svm_reader(|svm| svm.get_account(&lookup_table_address))
        .unwrap();
    assert!(
        matches!(
            lookup_table_account,
            Some(Account {
                owner,
                ..
            }) if owner == solana_address_lookup_table_interface::program::id()
        ),
        "lookup table account {lookup_table_address} should be created"
    );
}

#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test]
async fn test_send_transaction_skip_sig_verify_processes_and_updates_state(test_type: TestType) {
    let payer = Keypair::new();
    let recipient = Keypair::new().pubkey();
    let transfer_amount = LAMPORTS_PER_SOL / 2;
    let airdrop_amount = LAMPORTS_PER_SOL * 2;
    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();

    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            airdrop_addresses: vec![payer.pubkey()],
            airdrop_token_amount: airdrop_amount,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);

    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            svm_locker,
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });

    wait_for_ready_and_connected(&simnet_events_rx);

    let minimal_client =
        http::connect::<MinimalClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");
    let full_client =
        http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");

    // Verify payer got airdrop
    let payer_balance = minimal_client
        .get_balance(payer.pubkey().to_string(), None)
        .await
        .expect("Failed to get payer balance");
    assert_eq!(
        payer_balance.value, airdrop_amount,
        "Payer should have airdrop amount"
    );

    // Verify recipient starts with zero
    let recipient_balance = minimal_client
        .get_balance(recipient.to_string(), None)
        .await
        .expect("Failed to get recipient balance");
    assert_eq!(
        recipient_balance.value, 0,
        "Recipient should start with zero balance"
    );

    // Get a recent blockhash
    let recent_blockhash = full_client
        .get_latest_blockhash(None)
        .await
        .map(|r| {
            Hash::from_str(r.value.blockhash.as_str()).expect("Failed to deserialize blockhash")
        })
        .expect("Failed to get blockhash");

    // Build a transaction with an INVALID signature (Signature::new_unique instead of real signing)
    let msg = VersionedMessage::Legacy(Message::new_with_blockhash(
        &[system_instruction::transfer(
            &payer.pubkey(),
            &recipient,
            transfer_amount,
        )],
        Some(&payer.pubkey()),
        &recent_blockhash,
    ));
    let tx = VersionedTransaction {
        signatures: vec![solana_signature::Signature::new_unique()],
        message: msg,
    };

    let encoded = bincode::serialize(&tx).expect("Failed to serialize tx");
    let data = bs58::encode(encoded).into_string();

    // Send with skip_sig_verify=true and skip_preflight=true
    let send_config = SurfpoolRpcSendTransactionConfig {
        base: RpcSendTransactionConfig {
            skip_preflight: true,
            ..Default::default()
        },
        skip_sig_verify: Some(true),
    };
    let _sig = full_client
        .send_transaction(data, Some(send_config))
        .await
        .expect("send_transaction with skip_sig_verify should succeed");

    // Wait for the transaction to be processed
    let _ = task::spawn_blocking(move || {
        loop {
            match simnet_events_rx.recv() {
                Ok(SimnetEvent::TransactionProcessed(..)) => break,
                _ => (),
            }
        }
    })
    .await;

    // Assert recipient received the transfer
    let final_recipient_balance = minimal_client
        .get_balance(recipient.to_string(), None)
        .await
        .expect("Failed to get final recipient balance");
    assert_eq!(
        final_recipient_balance.value, transfer_amount,
        "Recipient should have received the transfer amount"
    );

    // Assert payer balance decreased by transfer + fees
    let final_payer_balance = minimal_client
        .get_balance(payer.pubkey().to_string(), None)
        .await
        .expect("Failed to get final payer balance");
    assert!(
        final_payer_balance.value < airdrop_amount - transfer_amount,
        "Payer balance ({}) should be less than airdrop minus transfer ({}) due to fees",
        final_payer_balance.value,
        airdrop_amount - transfer_amount
    );
    assert!(
        final_payer_balance.value > airdrop_amount - transfer_amount - LAMPORTS_PER_SOL / 10,
        "Payer balance ({}) should not have decreased by more than transfer + reasonable fees",
        final_payer_balance.value,
    );
}

#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::no_db(); "with no db")]
#[tokio::test]
async fn test_airdrop_amount_zero_skips_airdrops(test_type: TestType) {
    let recipient = Keypair::new().pubkey();
    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();

    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            airdrop_addresses: vec![recipient],
            airdrop_token_amount: 0,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);

    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            svm_locker,
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });

    // Startup must reach Ready without panicking. This is the core regression
    // assertion for https://github.com/solana-foundation/surfpool/issues/651.
    wait_for_ready_and_connected(&simnet_events_rx);

    let minimal_client =
        http::connect::<MinimalClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");

    let recipient_balance = minimal_client
        .get_balance(recipient.to_string(), None)
        .await
        .expect("Failed to get recipient balance");
    assert_eq!(
        recipient_balance.value, 0,
        "Recipient should have zero balance when --airdrop-amount=0"
    );
}

#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::no_db(); "with no db")]
#[tokio::test]
async fn test_airdrop_amount_below_rent_skips_airdrops(test_type: TestType) {
    let recipient = Keypair::new().pubkey();
    let bind_host = "127.0.0.1";
    let bind_port = get_free_port().unwrap();
    let ws_port = get_free_port().unwrap();

    // 1 lamport is far below any rent-exempt minimum, so airdrop must be skipped.
    let config = SurfpoolConfig {
        simnets: vec![SimnetConfig {
            slot_time: 1,
            airdrop_addresses: vec![recipient],
            airdrop_token_amount: 1,
            ..SimnetConfig::default()
        }],
        rpc: RpcConfig {
            bind_host: bind_host.to_string(),
            bind_port,
            ws_port,
            ..Default::default()
        },
        ..SurfpoolConfig::default()
    };

    let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
    let (simnet_commands_tx, simnet_commands_rx) = unbounded();

    let svm_locker = SurfnetSvmLocker::new(surfnet_svm);

    let _handle = hiro_system_kit::thread_named("test").spawn(move || {
        let future = start_local_surfnet_runloop(
            svm_locker,
            config,
            simnet_commands_tx,
            simnet_commands_rx,
            geyser_events_rx,
        );
        if let Err(e) = hiro_system_kit::nestable_block_on(future) {
            panic!("{e:?}");
        }
    });

    wait_for_ready_and_connected(&simnet_events_rx);

    let minimal_client =
        http::connect::<MinimalClient>(format!("http://{bind_host}:{bind_port}").as_str())
            .await
            .expect("Failed to connect to Surfpool");

    let recipient_balance = minimal_client
        .get_balance(recipient.to_string(), None)
        .await
        .expect("Failed to get recipient balance");
    assert_eq!(
        recipient_balance.value, 0,
        "Recipient should have zero balance when --airdrop-amount is below rent-exempt minimum"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn test_airdrop_pubkeys_zero_amount_unit() {
    use crate::{rpc::minimal::SurfpoolMinimalRpc, tests::helpers::TestSetup};

    let setup = TestSetup::new(SurfpoolMinimalRpc);
    let recipient = Pubkey::new_unique();
    setup.context.svm_locker.airdrop_pubkeys(0, &[recipient]);

    let account = setup
        .context
        .svm_locker
        .with_svm_reader(|svm| svm.get_account(&recipient).ok().flatten());
    assert!(
        account.is_none() || account.unwrap().lamports == 0,
        "Recipient must not be funded when airdrop amount is 0"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn test_airdrop_pubkeys_below_rent_unit() {
    use crate::{rpc::minimal::SurfpoolMinimalRpc, tests::helpers::TestSetup};

    let setup = TestSetup::new(SurfpoolMinimalRpc);
    let recipient = Pubkey::new_unique();

    let min_rent = setup
        .context
        .svm_locker
        .with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(0));
    assert!(min_rent > 1, "Rent-exempt minimum should be greater than 1");

    setup
        .context
        .svm_locker
        .airdrop_pubkeys(min_rent - 1, &[recipient]);

    let account = setup
        .context
        .svm_locker
        .with_svm_reader(|svm| svm.get_account(&recipient).ok().flatten());
    assert!(
        account.is_none() || account.unwrap().lamports == 0,
        "Recipient must not be funded when airdrop amount is below rent-exempt minimum"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn test_airdrop_pubkeys_at_rent_minimum_unit() {
    use crate::{rpc::minimal::SurfpoolMinimalRpc, tests::helpers::TestSetup};

    let setup = TestSetup::new(SurfpoolMinimalRpc);
    let recipient = Pubkey::new_unique();

    let min_rent = setup
        .context
        .svm_locker
        .with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(0));

    setup
        .context
        .svm_locker
        .airdrop_pubkeys(min_rent, &[recipient]);

    let account = setup
        .context
        .svm_locker
        .with_svm_reader(|svm| svm.get_account(&recipient).ok().flatten())
        .expect("Recipient should be funded when airdrop amount equals rent-exempt minimum");
    assert_eq!(
        account.lamports, min_rent,
        "Recipient should be funded with exactly the rent-exempt minimum"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn test_airdrop_pubkeys_empty_addresses_unit() {
    use crate::{rpc::minimal::SurfpoolMinimalRpc, tests::helpers::TestSetup};

    let setup = TestSetup::new(SurfpoolMinimalRpc);
    // Must not panic with an empty address slice, regardless of amount.
    setup.context.svm_locker.airdrop_pubkeys(0, &[]);
    setup
        .context
        .svm_locker
        .airdrop_pubkeys(LAMPORTS_PER_SOL, &[]);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_airdrop_returns_zero_amount_variant() {
    use crate::{error::AirdropError, rpc::minimal::SurfpoolMinimalRpc, tests::helpers::TestSetup};

    let setup = TestSetup::new(SurfpoolMinimalRpc);
    let recipient = Pubkey::new_unique();

    let err = setup
        .context
        .svm_locker
        .airdrop(&recipient, 0)
        .expect_err("airdrop with 0 lamports must error");
    assert!(
        matches!(err, AirdropError::ZeroAmount),
        "expected ZeroAmount, got {err:?}",
    );

    let account = setup
        .context
        .svm_locker
        .with_svm_reader(|svm| svm.get_account(&recipient).ok().flatten());
    assert!(
        account.is_none(),
        "recipient must not be created when airdrop is rejected"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn test_airdrop_returns_below_rent_variant() {
    use crate::{error::AirdropError, rpc::minimal::SurfpoolMinimalRpc, tests::helpers::TestSetup};

    let setup = TestSetup::new(SurfpoolMinimalRpc);
    let recipient = Pubkey::new_unique();

    let min_rent = setup
        .context
        .svm_locker
        .with_svm_reader(|svm| svm.inner.minimum_balance_for_rent_exemption(0));
    assert!(min_rent > 1);

    let err = setup
        .context
        .svm_locker
        .airdrop(&recipient, 1)
        .expect_err("airdrop with 1 lamport must error");
    assert!(
        matches!(
            err,
            AirdropError::BelowRentExemption { lamports: 1, min_rent: m } if m == min_rent
        ),
        "expected BelowRentExemption, got {err:?}",
    );

    let account = setup
        .context
        .svm_locker
        .with_svm_reader(|svm| svm.get_account(&recipient).ok().flatten());
    assert!(
        account.is_none(),
        "recipient must not be created when airdrop is rejected"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn test_request_airdrop_rejects_zero_amount() {
    use crate::{
        rpc::full::{Full, SurfpoolFullRpc},
        tests::helpers::TestSetup,
    };

    let setup = TestSetup::new(SurfpoolFullRpc);
    let recipient = Pubkey::new_unique();
    let err = setup
        .rpc
        .request_airdrop(Some(setup.context.clone()), recipient.to_string(), 0, None)
        .expect_err("requestAirdrop with 0 lamports must return an RPC error");
    assert_eq!(err.code, jsonrpc_core::ErrorCode::InvalidParams);
    assert!(err.message.contains("greater than zero"));
}

#[tokio::test(flavor = "multi_thread")]
async fn test_request_airdrop_rejects_below_rent_amount() {
    use crate::{
        rpc::full::{Full, SurfpoolFullRpc},
        tests::helpers::TestSetup,
    };

    let setup = TestSetup::new(SurfpoolFullRpc);
    let recipient = Pubkey::new_unique();
    let err = setup
        .rpc
        .request_airdrop(Some(setup.context.clone()), recipient.to_string(), 1, None)
        .expect_err("requestAirdrop below rent exemption must return an RPC error");
    assert_eq!(err.code, jsonrpc_core::ErrorCode::InvalidParams);
    assert!(err.message.contains("rent-exempt minimum"));
}