surfpool-types 1.1.1

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
use std::{
    cmp::Ordering,
    collections::{BTreeMap, HashMap},
    fmt,
    path::PathBuf,
    str::FromStr,
};

use blake3::Hash;
use chrono::{DateTime, Local};
use crossbeam_channel::{Receiver, Sender};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Visitor};
use serde_with::{BytesOrString, serde_as};
use solana_account::Account;
use solana_account_decoder_client_types::{ParsedAccount, UiAccount, UiAccountEncoding};
use solana_clock::{Clock, Epoch, Slot};
use solana_epoch_info::EpochInfo;
use solana_message::inner_instruction::InnerInstructionsList;
use solana_pubkey::Pubkey;
use solana_signature::Signature;
use solana_transaction::versioned::VersionedTransaction;
use solana_transaction_context::TransactionReturnData;
use solana_transaction_error::TransactionError;
use txtx_addon_kit::indexmap::IndexMap;
use txtx_addon_network_svm_types::subgraph::SubgraphRequest;
use uuid::Uuid;

use crate::{DEFAULT_MAINNET_RPC_URL, SvmFeatureConfig};

pub const DEFAULT_RPC_PORT: u16 = 8899;
pub const DEFAULT_WS_PORT: u16 = 8900;
pub const DEFAULT_STUDIO_PORT: u16 = 8488;
pub const CHANGE_TO_DEFAULT_STUDIO_PORT_ONCE_SUPERVISOR_MERGED: u16 = 18488;
pub const DEFAULT_NETWORK_HOST: &str = "127.0.0.1";
pub const DEFAULT_SLOT_TIME_MS: u64 = 400;
pub type Idl = anchor_lang_idl::types::Idl;
pub const DEFAULT_PROFILING_MAP_CAPACITY: usize = 200;

#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct TransactionMetadata {
    pub signature: Signature,
    pub logs: Vec<String>,
    pub inner_instructions: InnerInstructionsList,
    pub compute_units_consumed: u64,
    pub return_data: TransactionReturnData,
    pub fee: u64,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TransactionConfirmationStatus {
    Processed,
    Confirmed,
    Finalized,
}

#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum BlockProductionMode {
    #[default]
    Clock,
    Transaction,
    Manual,
}

impl fmt::Display for BlockProductionMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BlockProductionMode::Clock => write!(f, "clock"),
            BlockProductionMode::Transaction => write!(f, "transaction"),
            BlockProductionMode::Manual => write!(f, "manual"),
        }
    }
}

impl FromStr for BlockProductionMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "clock" => Ok(BlockProductionMode::Clock),
            "transaction" => Ok(BlockProductionMode::Transaction),
            "manual" => Ok(BlockProductionMode::Manual),
            _ => Err(format!(
                "Invalid block production mode: {}. Valid values are: clock, transaction, manual",
                s
            )),
        }
    }
}

#[derive(Debug)]
pub enum SubgraphEvent {
    EndpointReady,
    InfoLog(DateTime<Local>, String),
    ErrorLog(DateTime<Local>, String),
    WarnLog(DateTime<Local>, String),
    DebugLog(DateTime<Local>, String),
    Shutdown,
}

impl SubgraphEvent {
    pub fn info<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self::InfoLog(Local::now(), msg.into())
    }

    pub fn warn<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self::WarnLog(Local::now(), msg.into())
    }

    pub fn error<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self::ErrorLog(Local::now(), msg.into())
    }

    pub fn debug<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self::DebugLog(Local::now(), msg.into())
    }
}

/// Result structure for compute units estimation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ComputeUnitsEstimationResult {
    pub success: bool,
    pub compute_units_consumed: u64,
    pub log_messages: Option<Vec<String>>,
    pub error_message: Option<String>,
}

/// The struct for storing the profiling results.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KeyedProfileResult {
    pub slot: u64,
    pub key: UuidOrSignature,
    pub instruction_profiles: Option<Vec<ProfileResult>>,
    pub transaction_profile: ProfileResult,
    #[serde(with = "pubkey_account_map")]
    pub readonly_account_states: HashMap<Pubkey, Account>,
}

impl KeyedProfileResult {
    pub fn new(
        slot: u64,
        key: UuidOrSignature,
        instruction_profiles: Option<Vec<ProfileResult>>,
        transaction_profile: ProfileResult,
        readonly_account_states: HashMap<Pubkey, Account>,
    ) -> Self {
        Self {
            slot,
            key,
            instruction_profiles,
            transaction_profile,
            readonly_account_states,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProfileResult {
    #[serde(with = "pubkey_option_account_map")]
    pub pre_execution_capture: ExecutionCapture,
    #[serde(with = "pubkey_option_account_map")]
    pub post_execution_capture: ExecutionCapture,
    pub compute_units_consumed: u64,
    pub log_messages: Option<Vec<String>>,
    pub error_message: Option<String>,
}

pub type ExecutionCapture = BTreeMap<Pubkey, Option<Account>>;

impl ProfileResult {
    pub fn new(
        pre_execution_capture: ExecutionCapture,
        post_execution_capture: ExecutionCapture,
        compute_units_consumed: u64,
        log_messages: Option<Vec<String>>,
        error_message: Option<String>,
    ) -> Self {
        Self {
            pre_execution_capture,
            post_execution_capture,
            compute_units_consumed,
            log_messages,
            error_message,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum AccountProfileState {
    Readonly,
    Writable(AccountChange),
}

impl AccountProfileState {
    pub fn new(
        pubkey: Pubkey,
        pre_account: Option<Account>,
        post_account: Option<Account>,
        readonly_accounts: &[Pubkey],
    ) -> Self {
        if readonly_accounts.contains(&pubkey) {
            return AccountProfileState::Readonly;
        }

        match (pre_account, post_account) {
            (None, Some(post_account)) => {
                AccountProfileState::Writable(AccountChange::Create(post_account))
            }
            (Some(pre_account), None) => {
                AccountProfileState::Writable(AccountChange::Delete(pre_account))
            }
            (Some(pre_account), Some(post_account)) if pre_account == post_account => {
                AccountProfileState::Writable(AccountChange::Unchanged(Some(pre_account)))
            }
            (Some(pre_account), Some(post_account)) => {
                AccountProfileState::Writable(AccountChange::Update(pre_account, post_account))
            }
            (None, None) => AccountProfileState::Writable(AccountChange::Unchanged(None)),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum AccountChange {
    Create(Account),
    Update(Account, Account),
    Delete(Account),
    Unchanged(Option<Account>),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RpcProfileResultConfig {
    pub encoding: Option<UiAccountEncoding>,
    pub depth: Option<RpcProfileDepth>,
}

impl Default for RpcProfileResultConfig {
    fn default() -> Self {
        Self {
            encoding: Some(UiAccountEncoding::JsonParsed),
            depth: Some(RpcProfileDepth::default()),
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum RpcProfileDepth {
    Transaction,
    #[default]
    Instruction,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UiKeyedProfileResult {
    pub slot: u64,
    pub key: UuidOrSignature,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instruction_profiles: Option<Vec<UiProfileResult>>,
    pub transaction_profile: UiProfileResult,
    #[serde(with = "profile_state_map")]
    pub readonly_account_states: IndexMap<Pubkey, UiAccount>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UiProfileResult {
    #[serde(with = "profile_state_map")]
    pub account_states: IndexMap<Pubkey, UiAccountProfileState>,
    pub compute_units_consumed: u64,
    pub log_messages: Option<Vec<String>>,
    pub error_message: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", tag = "type", content = "accountChange")]
#[allow(clippy::large_enum_variant)]
pub enum UiAccountProfileState {
    Readonly,
    Writable(UiAccountChange),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", tag = "type", content = "data")]
pub enum UiAccountChange {
    Create(UiAccount),
    Update(UiAccount, UiAccount),
    Delete(UiAccount),
    /// The account didn't change. If [Some], this is the initial state. If [None], the account didn't exist before/after execution.
    Unchanged(Option<UiAccount>),
}

/// P starts with 300 lamports
/// Ix 1 Transfers 100 lamports to P
/// Ix 2 Transfers 100 lamports to P
///
/// Profile result 1 is from executing just Ix 1
/// AccountProfileState::Writable(P, AccountChange::Update( UiAccount { lamports: 300, ...}, UiAccount { lamports: 400, ... }))
///
/// Profile result 2 is from executing Ix 1 and Ix 2
/// AccountProfileState::Writable(P, AccountChange::Update( UiAccount { lamports: 400, ...}, UiAccount { lamports: 500, ... }))
pub mod profile_state_map {
    use super::*;

    pub fn serialize<S, T>(map: &IndexMap<Pubkey, T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: Serialize,
    {
        let str_map: IndexMap<String, &T> = map.iter().map(|(k, v)| (k.to_string(), v)).collect();
        str_map.serialize(serializer)
    }

    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<IndexMap<Pubkey, T>, D::Error>
    where
        D: Deserializer<'de>,
        T: Deserialize<'de>,
    {
        let str_map: IndexMap<String, T> = IndexMap::deserialize(deserializer)?;
        str_map
            .into_iter()
            .map(|(k, v)| {
                Pubkey::from_str(&k)
                    .map(|pk| (pk, v))
                    .map_err(serde::de::Error::custom)
            })
            .collect()
    }
}

/// Serialization module for HashMap<Pubkey, Account>
pub mod pubkey_account_map {
    use super::*;

    pub fn serialize<S>(map: &HashMap<Pubkey, Account>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let str_map: HashMap<String, &Account> =
            map.iter().map(|(k, v)| (k.to_string(), v)).collect();
        str_map.serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<Pubkey, Account>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let str_map: HashMap<String, Account> = HashMap::deserialize(deserializer)?;
        str_map
            .into_iter()
            .map(|(k, v)| {
                Pubkey::from_str(&k)
                    .map(|pk| (pk, v))
                    .map_err(serde::de::Error::custom)
            })
            .collect()
    }
}

/// Serialization module for BTreeMap<Pubkey, Option<Account>>
pub mod pubkey_option_account_map {
    use super::*;

    pub fn serialize<S>(
        map: &BTreeMap<Pubkey, Option<Account>>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let str_map: BTreeMap<String, &Option<Account>> =
            map.iter().map(|(k, v)| (k.to_string(), v)).collect();
        str_map.serialize(serializer)
    }

    pub fn deserialize<'de, D>(
        deserializer: D,
    ) -> Result<BTreeMap<Pubkey, Option<Account>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let str_map: BTreeMap<String, Option<Account>> = BTreeMap::deserialize(deserializer)?;
        str_map
            .into_iter()
            .map(|(k, v)| {
                Pubkey::from_str(&k)
                    .map(|pk| (pk, v))
                    .map_err(serde::de::Error::custom)
            })
            .collect()
    }
}

#[derive(Debug, Clone)]
pub enum SubgraphCommand {
    CreateCollection(Uuid, SubgraphRequest, Sender<String>),
    ObserveCollection(Receiver<DataIndexingCommand>),
    DestroyCollection(Uuid), // Clean up collection on plugin unload
    Shutdown,
}

#[derive(Debug)]
pub enum SimnetEvent {
    /// Surfnet is ready, with the initial count of processed transactions from storage
    Ready(u64),
    Connected(String),
    Aborted(String),
    Shutdown,
    SystemClockUpdated(Clock),
    ClockUpdate(ClockCommand),
    EpochInfoUpdate(EpochInfo),
    BlockHashExpired,
    InfoLog(DateTime<Local>, String),
    ErrorLog(DateTime<Local>, String),
    WarnLog(DateTime<Local>, String),
    DebugLog(DateTime<Local>, String),
    PluginLoaded(String),
    TransactionReceived(DateTime<Local>, VersionedTransaction),
    TransactionProcessed(
        DateTime<Local>,
        TransactionMetadata,
        Option<TransactionError>,
    ),
    AccountUpdate(DateTime<Local>, Pubkey),
    TaggedProfile {
        result: KeyedProfileResult,
        tag: String,
        timestamp: DateTime<Local>,
    },
    RunbookStarted(String),
    RunbookCompleted(String, Option<Vec<String>>),
}

impl SimnetEvent {
    pub fn info<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self::InfoLog(Local::now(), msg.into())
    }

    pub fn warn<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self::WarnLog(Local::now(), msg.into())
    }

    pub fn error<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self::ErrorLog(Local::now(), msg.into())
    }

    pub fn debug<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self::DebugLog(Local::now(), msg.into())
    }

    pub fn transaction_processed(meta: TransactionMetadata, err: Option<TransactionError>) -> Self {
        Self::TransactionProcessed(Local::now(), meta, err)
    }

    pub fn transaction_received(tx: VersionedTransaction) -> Self {
        Self::TransactionReceived(Local::now(), tx)
    }

    pub fn account_update(pubkey: Pubkey) -> Self {
        Self::AccountUpdate(Local::now(), pubkey)
    }

    pub fn tagged_profile(result: KeyedProfileResult, tag: String) -> Self {
        Self::TaggedProfile {
            result,
            tag,
            timestamp: Local::now(),
        }
    }

    pub fn account_update_msg(&self) -> String {
        match self {
            SimnetEvent::AccountUpdate(_, pubkey) => {
                format!("Account {} updated.", pubkey)
            }
            _ => unreachable!("This function should only be called for AccountUpdate events"),
        }
    }

    pub fn epoch_info_update_msg(&self) -> String {
        match self {
            SimnetEvent::EpochInfoUpdate(epoch_info) => {
                format!(
                    "Datasource connection successful. Epoch {} / Slot index {} / Slot {}.",
                    epoch_info.epoch, epoch_info.slot_index, epoch_info.absolute_slot
                )
            }
            _ => unreachable!("This function should only be called for EpochInfoUpdate events"),
        }
    }

    pub fn plugin_loaded_msg(&self) -> String {
        match self {
            SimnetEvent::PluginLoaded(plugin_name) => {
                format!("Plugin {} successfully loaded.", plugin_name)
            }
            _ => unreachable!("This function should only be called for PluginLoaded events"),
        }
    }

    pub fn clock_update_msg(&self) -> String {
        match self {
            SimnetEvent::SystemClockUpdated(clock) => {
                format!("Clock ticking (epoch {}, slot {})", clock.epoch, clock.slot)
            }
            _ => {
                unreachable!("This function should only be called for SystemClockUpdated events")
            }
        }
    }
}

#[derive(Debug)]
pub enum TransactionStatusEvent {
    Success(TransactionConfirmationStatus),
    SimulationFailure((TransactionError, TransactionMetadata)),
    ExecutionFailure((TransactionError, TransactionMetadata)),
    VerificationFailure(String),
}

#[derive(Debug)]
pub enum SimnetCommand {
    SlotForward(Option<Hash>),
    SlotBackward(Option<Hash>),
    CommandClock(Option<(Hash, String)>, ClockCommand),
    UpdateInternalClock(Option<(Hash, String)>, Clock),
    UpdateInternalClockWithConfirmation(Option<(Hash, String)>, Clock, Sender<EpochInfo>),
    UpdateBlockProductionMode(BlockProductionMode),
    ProcessTransaction(
        Option<(Hash, String)>,
        VersionedTransaction,
        Sender<TransactionStatusEvent>,
        bool,
        Option<bool>,
    ),
    Terminate(Option<(Hash, String)>),
    StartRunbookExecution(String),
    CompleteRunbookExecution(String, Option<Vec<String>>),
    FetchRemoteAccounts(Vec<Pubkey>, String),
    AirdropProcessed,
}

#[derive(Debug)]
pub enum ClockCommand {
    Pause,
    /// Pause with confirmation - sends epoch info back when actually paused
    PauseWithConfirmation(Sender<EpochInfo>),
    Resume,
    Toggle,
    UpdateSlotInterval(u64),
}

pub enum ClockEvent {
    Tick,
    ExpireBlockHash,
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct SanitizedConfig {
    pub rpc_url: String,
    pub ws_url: String,
    pub rpc_datasource_url: Option<String>,
    pub studio_url: String,
    pub graphql_query_route_url: String,
    pub version: String,
    pub workspace: Option<String>,
}

#[derive(Clone, Debug, Default)]
pub struct SurfpoolConfig {
    pub simnets: Vec<SimnetConfig>,
    pub rpc: RpcConfig,
    pub subgraph: SubgraphConfig,
    pub studio: StudioConfig,
    pub plugin_config_path: Vec<PathBuf>,
}

#[derive(Clone, Debug)]
pub struct SimnetConfig {
    pub offline_mode: bool,
    pub remote_rpc_url: Option<String>,
    pub slot_time: u64,
    pub block_production_mode: BlockProductionMode,
    pub airdrop_addresses: Vec<Pubkey>,
    pub airdrop_token_amount: u64,
    pub expiry: Option<u64>,
    pub instruction_profiling_enabled: bool,
    pub max_profiles: usize,
    pub log_bytes_limit: Option<usize>,
    pub feature_config: SvmFeatureConfig,
    pub skip_signature_verification: bool,
    /// Unique identifier for this surfnet instance. Used to isolate database storage
    /// when multiple surfnets share the same database. Defaults to "default".
    pub surfnet_id: String,
    /// Snapshot accounts to preload at startup.
    /// Keys are pubkey strings, values can be None to fetch from remote RPC.
    pub snapshot: BTreeMap<String, Option<AccountSnapshot>>,
}

impl Default for SimnetConfig {
    fn default() -> Self {
        Self {
            offline_mode: false,
            remote_rpc_url: Some(DEFAULT_MAINNET_RPC_URL.to_string()),
            slot_time: DEFAULT_SLOT_TIME_MS, // Default to 400ms to match CLI default
            block_production_mode: BlockProductionMode::Clock,
            airdrop_addresses: vec![],
            airdrop_token_amount: 0,
            expiry: None,
            instruction_profiling_enabled: true,
            max_profiles: DEFAULT_PROFILING_MAP_CAPACITY,
            log_bytes_limit: Some(10_000),
            feature_config: SvmFeatureConfig::default(),
            skip_signature_verification: false,
            surfnet_id: "default".to_string(),
            snapshot: BTreeMap::new(),
        }
    }
}

impl SimnetConfig {
    /// Returns a sanitized version of the datasource URL safe for display.
    /// Only returns scheme and host (e.g., "https://example.com") to prevent
    /// leaking API keys in paths or query parameters.
    pub fn get_sanitized_datasource_url(&self) -> Option<String> {
        let raw = self.remote_rpc_url.as_ref()?;

        if let Ok(url) = url::Url::parse(raw) {
            let scheme = url.scheme();
            let host = url.host_str()?;
            Some(format!("{}://{}", scheme, host))
        } else {
            None
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct SubgraphConfig {}

pub const DEFAULT_GOSSIP_PORT: u16 = 8001;
pub const DEFAULT_TPU_PORT: u16 = 8003;
pub const DEFAULT_TPU_QUIC_PORT: u16 = 8004;

#[derive(Clone, Debug)]
pub struct RpcConfig {
    pub bind_host: String,
    pub bind_port: u16,
    pub ws_port: u16,
    pub gossip_port: u16,
    pub tpu_port: u16,
    pub tpu_quic_port: u16,
}

impl RpcConfig {
    pub fn get_rpc_base_url(&self) -> String {
        format!("{}:{}", self.bind_host, self.bind_port)
    }
    pub fn get_ws_base_url(&self) -> String {
        format!("{}:{}", self.bind_host, self.ws_port)
    }
}

impl Default for RpcConfig {
    fn default() -> Self {
        Self {
            bind_host: DEFAULT_NETWORK_HOST.to_string(),
            bind_port: DEFAULT_RPC_PORT,
            ws_port: DEFAULT_WS_PORT,
            gossip_port: DEFAULT_GOSSIP_PORT,
            tpu_port: DEFAULT_TPU_PORT,
            tpu_quic_port: DEFAULT_TPU_QUIC_PORT,
        }
    }
}

#[derive(Clone, Debug)]
pub struct StudioConfig {
    pub bind_host: String,
    pub bind_port: u16,
}

impl StudioConfig {
    pub fn get_studio_base_url(&self) -> String {
        format!("{}:{}", self.bind_host, self.bind_port)
    }
}

impl Default for StudioConfig {
    fn default() -> Self {
        Self {
            bind_host: DEFAULT_NETWORK_HOST.to_string(),
            bind_port: CHANGE_TO_DEFAULT_STUDIO_PORT_ONCE_SUPERVISOR_MERGED,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SubgraphPluginConfig {
    pub uuid: Uuid,
    pub ipc_token: String,
    pub subgraph_request: SubgraphRequest,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub struct CreateSurfnetRequest {
    pub domain: String,
    pub block_production_mode: BlockProductionMode,
    pub datasource_rpc_url: String,
    pub settings: Option<CloudSurfnetSettings>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "snake_case", default)]
pub struct CloudSurfnetSettings {
    pub database_url: Option<String>,
    pub profiling_disabled: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gating: Option<CloudSurfnetRpcGating>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "snake_case", default)]
pub struct CloudSurfnetRpcGating {
    pub private_methods_secret_token: Option<String>,
    pub private_methods: Vec<String>,
    pub public_methods: Vec<String>,
    pub disabled_methods: Vec<String>,
}

impl CloudSurfnetRpcGating {
    pub fn restricted() -> CloudSurfnetRpcGating {
        CloudSurfnetRpcGating {
            private_methods: vec![],
            private_methods_secret_token: None,
            public_methods: vec![],
            disabled_methods: vec![
                "surfnet_cloneProgramAccount".into(),
                "surfnet_profileTransaction".into(),
                "surfnet_getProfileResultsByTag".into(),
                "surfnet_setSupply".into(),
                "surfnet_setProgramAuthority".into(),
                "surfnet_getTransactionProfile".into(),
                "surfnet_registerIdl".into(),
                "surfnet_getActiveIdl".into(),
                "surfnet_getLocalSignatures".into(),
                "surfnet_timeTravel".into(),
                "surfnet_pauseClock".into(),
                "surfnet_resumeClock".into(),
                "surfnet_resetAccount".into(),
                "surfnet_resetNetwork".into(),
                "surfnet_exportSnapshot".into(),
                "surfnet_streamAccount".into(),
                "surfnet_getStreamedAccounts".into(),
            ],
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub struct CreateSubgraphRequest {
    pub subgraph_id: Uuid,
    pub subgraph_revision_id: Uuid,
    pub revision_number: i32,
    pub start_block: i64,
    pub network: String,
    pub workspace_slug: String,
    pub request: SubgraphRequest,
    pub settings: Option<CloudSubgraphSettings>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub struct CloudSubgraphSettings {}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum SvmCloudCommand {
    CreateSurfnet(CreateSurfnetRequest),
    CreateSubgraph(CreateSubgraphRequest),
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CreateNetworkRequest {
    pub workspace_id: Uuid,
    pub name: String,
    pub description: Option<String>,
    pub datasource_rpc_url: String,
    pub block_production_mode: BlockProductionMode,
    pub profiling_enabled: Option<bool>,
}

impl CreateNetworkRequest {
    pub fn new(
        workspace_id: Uuid,
        name: String,
        description: Option<String>,
        datasource_rpc_url: String,
        block_production_mode: BlockProductionMode,
        profiling_enabled: bool,
    ) -> Self {
        Self {
            workspace_id,
            name,
            description,
            datasource_rpc_url,
            block_production_mode,
            profiling_enabled: Some(profiling_enabled),
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct CreateNetworkResponse {
    pub rpc_url: String,
}

#[derive(Serialize, Deserialize)]
pub struct DeleteNetworkRequest {
    pub workspace_id: Uuid,
    pub network_id: Uuid,
}

impl DeleteNetworkRequest {
    pub fn new(workspace_id: Uuid, network_id: Uuid) -> Self {
        Self {
            workspace_id,
            network_id,
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct DeleteNetworkResponse;

#[serde_as]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountUpdate {
    /// providing this value sets the lamports in the account
    pub lamports: Option<u64>,
    /// providing this value sets the data held in this account
    #[serde_as(as = "Option<BytesOrString>")]
    pub data: Option<Vec<u8>>,
    ///  providing this value sets the program that owns this account. If executable, the program that loads this account.
    pub owner: Option<String>,
    /// providing this value sets whether this account's data contains a loaded program (and is now read-only)
    pub executable: Option<bool>,
    /// providing this value sets the epoch at which this account will next owe rent
    pub rent_epoch: Option<Epoch>,
}

#[derive(Debug, Clone)]
pub enum SetSomeAccount {
    Account(String),
    NoAccount,
}

impl<'de> Deserialize<'de> for SetSomeAccount {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct SetSomeAccountVisitor;

        impl<'de> Visitor<'de> for SetSomeAccountVisitor {
            type Value = SetSomeAccount;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a Pubkey String or the String 'null'")
            }

            fn visit_some<D_>(self, deserializer: D_) -> std::result::Result<Self::Value, D_::Error>
            where
                D_: Deserializer<'de>,
            {
                Deserialize::deserialize(deserializer).map(|v: String| match v.as_str() {
                    "null" => SetSomeAccount::NoAccount,
                    _ => SetSomeAccount::Account(v.to_string()),
                })
            }
        }

        deserializer.deserialize_option(SetSomeAccountVisitor)
    }
}

impl Serialize for SetSomeAccount {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            SetSomeAccount::Account(val) => serializer.serialize_str(val),
            SetSomeAccount::NoAccount => serializer.serialize_str("null"),
        }
    }
}

#[serde_as]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenAccountUpdate {
    /// providing this value sets the amount of the token in the account data
    pub amount: Option<u64>,
    /// providing this value sets the delegate of the token account
    pub delegate: Option<SetSomeAccount>,
    /// providing this value sets the state of the token account
    pub state: Option<String>,
    /// providing this value sets the amount authorized to the delegate
    pub delegated_amount: Option<u64>,
    /// providing this value sets the close authority of the token account
    pub close_authority: Option<SetSomeAccount>,
}

// token supply update for set supply method in SVM tricks
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct SupplyUpdate {
    pub total: Option<u64>,
    pub circulating: Option<u64>,
    pub non_circulating: Option<u64>,
    pub non_circulating_accounts: Option<Vec<String>>,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum UuidOrSignature {
    Uuid(Uuid),
    Signature(Signature),
}

impl std::fmt::Display for UuidOrSignature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UuidOrSignature::Uuid(uuid) => write!(f, "{}", uuid),
            UuidOrSignature::Signature(signature) => write!(f, "{}", signature),
        }
    }
}

impl<'de> Deserialize<'de> for UuidOrSignature {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;

        if let Ok(uuid) = Uuid::parse_str(&s) {
            return Ok(UuidOrSignature::Uuid(uuid));
        }

        if let Ok(signature) = s.parse::<Signature>() {
            return Ok(UuidOrSignature::Signature(signature));
        }

        Err(serde::de::Error::custom(
            "expected a Uuid or a valid Solana Signature",
        ))
    }
}

impl Serialize for UuidOrSignature {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            UuidOrSignature::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
            UuidOrSignature::Signature(signature) => {
                serializer.serialize_str(&signature.to_string())
            }
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum DataIndexingCommand {
    ProcessCollection(Uuid),
    ProcessCollectionEntriesPack(Uuid, Vec<u8>),
}

// Define a wrapper struct
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionedIdl(pub Slot, pub Idl);

// Implement ordering based on Slot
impl PartialEq for VersionedIdl {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl Eq for VersionedIdl {}

impl PartialOrd for VersionedIdl {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for VersionedIdl {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

#[derive(Debug, Clone)]
pub struct FifoMap<K, V> {
    // IndexMap is a map that preserves the insertion order of the keys. (It will be used for the FIFO eviction)
    map: IndexMap<K, V>,
}

impl<K: std::hash::Hash + Eq, V> Default for FifoMap<K, V> {
    fn default() -> Self {
        Self::new(DEFAULT_PROFILING_MAP_CAPACITY)
    }
}
impl<K: std::hash::Hash + Eq, V> FifoMap<K, V> {
    pub fn new(capacity: usize) -> Self {
        Self {
            map: IndexMap::with_capacity(capacity),
        }
    }

    pub fn capacity(&self) -> usize {
        self.map.capacity()
    }

    pub fn len(&self) -> usize {
        self.map.len()
    }

    pub fn clear(&mut self) {
        self.map.clear();
    }

    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Insert a key/value. If `K` is new and we're full, evict the oldest (FIFO)
    /// Returns a tuple of (old_value, evicted_key):
    /// - old_value: The previous value if this was an update to an existing key
    /// - evicted_key: The key that was evicted if the map was at capacity
    pub fn insert(&mut self, key: K, value: V) -> (Option<V>, Option<K>) {
        if self.map.contains_key(&key) {
            // Update doesn't change insertion order in IndexMap
            return (self.map.insert(key, value), None);
        }
        let evicted_key = if self.map.len() == self.map.capacity() {
            // Evict oldest (index 0). O(n) due shifting the rest of the map
            // We could use a hashmap + vecdeque to get O(1) here, but then we'd have to handle removing from both maps, storing the index, and managing the eviction.
            // This is a good compromise between performance and simplicity. And thinking about memory usage, this is probably the best way to go.
            self.map.shift_remove_index(0).map(|(k, _)| k)
        } else {
            None
        };
        self.map.insert(key, value);
        (None, evicted_key)
    }

    pub fn get(&self, key: &K) -> Option<&V> {
        self.map.get(key)
    }

    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        self.map.get_mut(key)
    }

    pub fn contains_key(&self, key: &K) -> bool {
        self.map.contains_key(key)
    }

    /// Removes a key from the map, returning the value if present.
    pub fn remove(&mut self, key: &K) -> Option<V> {
        self.map.shift_remove(key)
    }

    // This is a wrapper around the IndexMap::iter() method, but it preserves the insertion order of the keys.
    // It's used to iterate over the profiling map in the order of the keys being inserted.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&K, &V)> {
        self.map.iter()
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountSnapshot {
    pub lamports: u64,
    pub owner: String,
    pub executable: bool,
    pub rent_epoch: u64,
    /// Base64 encoded data
    pub data: String,
    /// Parsed account data if available
    pub parsed_data: Option<ParsedAccount>,
}

impl AccountSnapshot {
    pub fn new(
        lamports: u64,
        owner: String,
        executable: bool,
        rent_epoch: u64,
        data: String,
        parsed_data: Option<ParsedAccount>,
    ) -> Self {
        Self {
            lamports,
            owner,
            executable,
            rent_epoch,
            data,
            parsed_data,
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportSnapshotConfig {
    pub include_parsed_accounts: Option<bool>,
    pub filter: Option<ExportSnapshotFilter>,
    pub scope: ExportSnapshotScope,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ExportSnapshotScope {
    #[default]
    Network,
    PreTransaction(String),
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportSnapshotFilter {
    pub include_program_accounts: Option<bool>,
    pub include_accounts: Option<Vec<String>>,
    pub exclude_accounts: Option<Vec<String>>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResetAccountConfig {
    pub include_owned_accounts: Option<bool>,
}

impl Default for ResetAccountConfig {
    fn default() -> Self {
        Self {
            include_owned_accounts: Some(false),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StreamAccountConfig {
    pub include_owned_accounts: Option<bool>,
}

impl Default for StreamAccountConfig {
    fn default() -> Self {
        Self {
            include_owned_accounts: Some(false),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StreamedAccountInfo {
    pub pubkey: String,
    pub include_owned_accounts: bool,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSurfnetInfoResponse {
    runbook_executions: Vec<RunbookExecutionStatusReport>,
}
impl GetSurfnetInfoResponse {
    pub fn new(runbook_executions: Vec<RunbookExecutionStatusReport>) -> Self {
        Self { runbook_executions }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetStreamedAccountsResponse {
    accounts: Vec<StreamedAccountInfo>,
}
impl GetStreamedAccountsResponse {
    pub fn from_iter<I>(streamed_accounts: I) -> Self
    where
        I: IntoIterator<Item = (String, bool)>,
    {
        let accounts = streamed_accounts
            .into_iter()
            .map(|(pubkey, include_owned_accounts)| StreamedAccountInfo {
                pubkey,
                include_owned_accounts,
            })
            .collect();
        Self { accounts }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RunbookExecutionStatusReport {
    pub started_at: u32,
    pub completed_at: Option<u32>,
    pub runbook_id: String,
    pub errors: Option<Vec<String>>,
}
impl RunbookExecutionStatusReport {
    pub fn new(runbook_id: String) -> Self {
        Self {
            started_at: Local::now().timestamp() as u32,
            completed_at: None,
            runbook_id,
            errors: None,
        }
    }
    pub fn mark_completed(&mut self, error: Option<Vec<String>>) {
        self.completed_at = Some(Local::now().timestamp() as u32);
        self.errors = error;
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;
    use solana_account_decoder_client_types::{ParsedAccount, UiAccountData};

    use super::*;

    #[test]
    fn print_ui_keyed_profile_result() {
        let pubkey = Pubkey::new_unique();
        let owner = Pubkey::new_unique();
        let readonly_account_state = UiAccount {
            lamports: 100,
            data: UiAccountData::Binary(
                "ABCDEFG".into(),
                solana_account_decoder_client_types::UiAccountEncoding::Base64,
            ),
            owner: owner.to_string(),
            executable: false,
            rent_epoch: 0,
            space: Some(100),
        };

        let account_1 = UiAccount {
            lamports: 100,
            data: UiAccountData::Json(ParsedAccount {
                program: "custom-program".into(),
                parsed: json!({
                    "field1": "value1",
                    "field2": "value2"
                }),
                space: 50,
            }),
            owner: owner.to_string(),
            executable: false,
            rent_epoch: 0,
            space: Some(100),
        };

        let account_2 = UiAccount {
            lamports: 100,
            data: UiAccountData::Json(ParsedAccount {
                program: "custom-program".into(),
                parsed: json!({
                    "field1": "updated-value1",
                    "field2": "updated-value2"
                }),
                space: 50,
            }),
            owner: owner.to_string(),
            executable: false,
            rent_epoch: 0,
            space: Some(100),
        };
        let profile_result = UiKeyedProfileResult {
            slot: 123,
            key: UuidOrSignature::Uuid(Uuid::new_v4()),
            instruction_profiles: Some(vec![
                UiProfileResult {
                    account_states: IndexMap::from_iter([
                        (
                            pubkey,
                            UiAccountProfileState::Writable(UiAccountChange::Create(
                                account_1.clone(),
                            )),
                        ),
                        (owner, UiAccountProfileState::Readonly),
                    ]),
                    compute_units_consumed: 100,
                    log_messages: Some(vec![
                        "Log message: Creating Account".to_string(),
                        "Log message: Account created".to_string(),
                    ]),
                    error_message: None,
                },
                UiProfileResult {
                    account_states: IndexMap::from_iter([
                        (
                            pubkey,
                            UiAccountProfileState::Writable(UiAccountChange::Update(
                                account_1,
                                account_2.clone(),
                            )),
                        ),
                        (owner, UiAccountProfileState::Readonly),
                    ]),
                    compute_units_consumed: 100,
                    log_messages: Some(vec![
                        "Log message: Updating Account".to_string(),
                        "Log message: Account updated".to_string(),
                    ]),
                    error_message: None,
                },
                UiProfileResult {
                    account_states: IndexMap::from_iter([
                        (
                            pubkey,
                            UiAccountProfileState::Writable(UiAccountChange::Delete(account_2)),
                        ),
                        (owner, UiAccountProfileState::Readonly),
                    ]),
                    compute_units_consumed: 100,
                    log_messages: Some(vec![
                        "Log message: Deleting Account".to_string(),
                        "Log message: Account deleted".to_string(),
                    ]),
                    error_message: None,
                },
            ]),
            transaction_profile: UiProfileResult {
                account_states: IndexMap::from_iter([
                    (
                        pubkey,
                        UiAccountProfileState::Writable(UiAccountChange::Unchanged(None)),
                    ),
                    (owner, UiAccountProfileState::Readonly),
                ]),
                compute_units_consumed: 300,
                log_messages: Some(vec![
                    "Log message: Creating Account".to_string(),
                    "Log message: Account created".to_string(),
                    "Log message: Updating Account".to_string(),
                    "Log message: Account updated".to_string(),
                    "Log message: Deleting Account".to_string(),
                    "Log message: Account deleted".to_string(),
                ]),
                error_message: None,
            },
            readonly_account_states: IndexMap::from_iter([(owner, readonly_account_state)]),
        };
        println!("{}", serde_json::to_string_pretty(&profile_result).unwrap());
    }

    #[test]
    fn test_profiling_map_capacity() {
        let profiling_map = FifoMap::<Signature, KeyedProfileResult>::new(10);
        assert_eq!(profiling_map.capacity(), 10);
    }

    #[test]
    fn test_profiling_map_len() {
        let profiling_map = FifoMap::<Signature, KeyedProfileResult>::new(10);
        assert!(profiling_map.len() == 0);
    }

    #[test]
    fn test_profiling_map_is_empty() {
        let profiling_map = FifoMap::<Signature, KeyedProfileResult>::new(10);
        assert_eq!(profiling_map.is_empty(), true);
    }

    #[test]
    fn test_profiling_map_insert() {
        let mut profiling_map = FifoMap::<Signature, KeyedProfileResult>::new(10);
        let key = Signature::default();
        let value = KeyedProfileResult::new(
            1,
            UuidOrSignature::Signature(key),
            None,
            ProfileResult::new(BTreeMap::new(), BTreeMap::new(), 0, None, None),
            HashMap::new(),
        );
        profiling_map.insert(key, value.clone());
        assert_eq!(profiling_map.len(), 1);
    }

    #[test]
    fn test_profiling_map_get() {
        let mut profiling_map = FifoMap::<Signature, KeyedProfileResult>::new(10);
        let key = Signature::default();
        let value = KeyedProfileResult::new(
            1,
            UuidOrSignature::Signature(key),
            None,
            ProfileResult::new(BTreeMap::new(), BTreeMap::new(), 0, None, None),
            HashMap::new(),
        );
        profiling_map.insert(key, value.clone());

        assert_eq!(profiling_map.get(&key), Some(&value));
    }

    #[test]
    fn test_profiling_map_get_mut() {
        let mut profiling_map = FifoMap::<Signature, KeyedProfileResult>::new(10);
        let key = Signature::default();
        let mut value = KeyedProfileResult::new(
            1,
            UuidOrSignature::Signature(key),
            None,
            ProfileResult::new(BTreeMap::new(), BTreeMap::new(), 0, None, None),
            HashMap::new(),
        );
        profiling_map.insert(key, value.clone());
        assert_eq!(profiling_map.get_mut(&key), Some(&mut value));
    }

    #[test]
    fn test_profiling_map_contains_key() {
        let mut profiling_map = FifoMap::<Signature, KeyedProfileResult>::new(10);
        let key = Signature::default();
        let value = KeyedProfileResult::new(
            1,
            UuidOrSignature::Signature(key),
            None,
            ProfileResult::new(BTreeMap::new(), BTreeMap::new(), 0, None, None),
            HashMap::new(),
        );
        profiling_map.insert(key, value.clone());

        assert_eq!(profiling_map.contains_key(&key), true);
    }

    #[test]
    fn test_profiling_map_iter() {
        let mut profiling_map = FifoMap::<Signature, KeyedProfileResult>::new(10);
        let key = Signature::default();
        let value = KeyedProfileResult::new(
            1,
            UuidOrSignature::Signature(key),
            None,
            ProfileResult::new(BTreeMap::new(), BTreeMap::new(), 0, None, None),
            HashMap::new(),
        );
        profiling_map.insert(key, value.clone());

        assert_eq!(profiling_map.iter().count(), 1);
    }

    #[test]
    fn test_profiling_map_evicts_oldest_on_overflow() {
        let mut profiling_map = FifoMap::<String, u32>::new(10);
        profiling_map.insert("a".to_string(), 1);
        profiling_map.insert("b".to_string(), 2);
        profiling_map.insert("c".to_string(), 3);
        profiling_map.insert("d".to_string(), 4);
        profiling_map.insert("e".to_string(), 5);
        profiling_map.insert("f".to_string(), 6);
        profiling_map.insert("g".to_string(), 7);
        profiling_map.insert("h".to_string(), 8);
        profiling_map.insert("i".to_string(), 9);
        profiling_map.insert("j".to_string(), 10);

        println!("Profiling map: {:?}", profiling_map);
        println!("Profile Map capacity: {:?}", profiling_map.capacity());
        println!("Profile Map len: {:?}", profiling_map.len());

        assert_eq!(profiling_map.len(), 10);

        // Now insert one more, which should evict the oldest
        profiling_map.insert("k".to_string(), 11);
        assert_eq!(profiling_map.len(), 10);
        assert_eq!(profiling_map.get(&"a".to_string()), None);
        assert_eq!(profiling_map.get(&"k".to_string()), Some(&11));
    }

    #[test]
    fn test_profiling_map_update_do_not_reorder() {
        let mut profiling_map = FifoMap::<&str, u32>::new(4);
        profiling_map.insert("a", 1);
        profiling_map.insert("b", 2);
        profiling_map.insert("c", 3);
        profiling_map.insert("d", 4);

        //update b, should not reorder (order remains a:1,b:2,c:3,d:4)
        println!("Profiling map: {:?}", profiling_map);
        println!("Profile Map key b holds: {:?}", profiling_map.get(&"b"));
        profiling_map.insert("b", 4);
        println!("Profile Map key b holds: {:?}", profiling_map.get(&"b"));

        //overflow with a new key, should evict the oldest (a)
        profiling_map.insert("e", 5);
        assert_eq!(profiling_map.len(), 4);
        assert_eq!(profiling_map.get(&"a"), None);
        assert_eq!(profiling_map.get(&"b"), Some(&4));
        assert_eq!(profiling_map.get(&"e"), Some(&5));

        let get: Vec<_> = profiling_map.iter().map(|(k, v)| (*k, *v)).collect();
        println!("Profiling map: {:?}", get);
        assert_eq!(get, vec![("b", 4), ("c", 3), ("d", 4), ("e", 5)]);
    }

    #[test]
    fn test_export_snapshot_scope_serialization() {
        // Test Network variant
        let network_config = ExportSnapshotConfig {
            include_parsed_accounts: None,
            filter: None,
            scope: ExportSnapshotScope::Network,
        };
        let network_json = serde_json::to_value(&network_config).unwrap();
        println!(
            "Network config: {}",
            serde_json::to_string_pretty(&network_json).unwrap()
        );
        assert_eq!(network_json["scope"], json!("network"));

        // Test PreTransaction variant
        let pre_tx_config = ExportSnapshotConfig {
            include_parsed_accounts: None,
            filter: None,
            scope: ExportSnapshotScope::PreTransaction("5signature123".to_string()),
        };
        let pre_tx_json = serde_json::to_value(&pre_tx_config).unwrap();
        println!(
            "PreTransaction config: {}",
            serde_json::to_string_pretty(&pre_tx_json).unwrap()
        );
        assert_eq!(
            pre_tx_json["scope"],
            json!({"preTransaction": "5signature123"})
        );

        // Test deserialization
        let deserialized_network: ExportSnapshotConfig =
            serde_json::from_value(network_json).unwrap();
        assert_eq!(deserialized_network.scope, ExportSnapshotScope::Network);

        let deserialized_pre_tx: ExportSnapshotConfig =
            serde_json::from_value(pre_tx_json).unwrap();
        assert_eq!(
            deserialized_pre_tx.scope,
            ExportSnapshotScope::PreTransaction("5signature123".to_string())
        );
    }

    #[test]
    fn test_sanitize_datasource_url_strips_path_and_query() {
        // API key in path should be stripped
        let config = SimnetConfig {
            remote_rpc_url: Some(
                "https://example.rpc-provider.com/v2/abc123def456ghi789".to_string(),
            ),
            ..Default::default()
        };
        let sanitized = config.get_sanitized_datasource_url().unwrap();
        assert_eq!(sanitized, "https://example.rpc-provider.com");
        assert!(!sanitized.contains("abc123"));
    }

    #[test]
    fn test_sanitize_datasource_url_strips_query_params() {
        let config = SimnetConfig {
            remote_rpc_url: Some(
                "https://mainnet.helius-rpc.com/?api-key=secret-key-12345".to_string(),
            ),
            ..Default::default()
        };
        let sanitized = config.get_sanitized_datasource_url().unwrap();
        assert_eq!(sanitized, "https://mainnet.helius-rpc.com");
        assert!(!sanitized.contains("secret-key"));
    }

    #[test]
    fn test_sanitize_datasource_url_public_rpc() {
        let config = SimnetConfig {
            remote_rpc_url: Some("https://api.mainnet-beta.solana.com".to_string()),
            ..Default::default()
        };
        let sanitized = config.get_sanitized_datasource_url().unwrap();
        assert_eq!(sanitized, "https://api.mainnet-beta.solana.com");
    }

    #[test]
    fn test_sanitize_datasource_url_none() {
        let config = SimnetConfig {
            remote_rpc_url: None,
            ..Default::default()
        };
        assert!(config.get_sanitized_datasource_url().is_none());
    }

    #[test]
    fn test_sanitize_datasource_url_invalid() {
        let config = SimnetConfig {
            remote_rpc_url: Some("not-a-valid-url".to_string()),
            ..Default::default()
        };
        assert!(config.get_sanitized_datasource_url().is_none());
    }
}