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
use http::{uri::Authority, Uri};
use itertools::Itertools;
use jsonrpsee_core::params::ObjectParams;
use jsonrpsee_core::{self, client::ClientT};
use jsonrpsee_http_client::{HeaderMap, HttpClient, HttpClientBuilder};
use serde_aux::prelude::{
    deserialize_default_from_null, deserialize_number_from_string,
    deserialize_option_number_from_string,
};
use stellar_xdr::curr::{
    self as xdr, AccountEntry, AccountId, ContractDataEntry, ContractEventType, DiagnosticEvent,
    Error as XdrError, Hash, LedgerEntryData, LedgerFootprint, LedgerKey, LedgerKeyAccount,
    Limited, Limits, PublicKey, ReadXdr, ScContractInstance, SorobanAuthorizationEntry,
    SorobanResources, SorobanTransactionData, Transaction, TransactionEnvelope, TransactionMeta,
    TransactionMetaV3, TransactionResult, TransactionV1Envelope, Uint256, VecM, WriteXdr,
};

use std::{
    f64::consts::E,
    fmt::Display,
    str::FromStr,
    sync::Arc,
    time::{Duration, Instant},
};

use termcolor::{Color, ColorChoice, StandardStream, WriteColor};
use termcolor_output::colored;
use tokio::time::sleep;

pub mod log;
mod txn;

pub use txn::Assembled;

const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
pub(crate) const DEFAULT_TRANSACTION_FEES: u32 = 100;

pub type LogEvents = fn(
    footprint: &LedgerFootprint,
    auth: &[VecM<SorobanAuthorizationEntry>],
    events: &[DiagnosticEvent],
) -> ();

pub type LogResources = fn(resources: &SorobanResources) -> ();

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    InvalidAddress(#[from] stellar_strkey::DecodeError),
    #[error("invalid response from server")]
    InvalidResponse,
    #[error("provided network passphrase {expected:?} does not match the server: {server:?}")]
    InvalidNetworkPassphrase { expected: String, server: String },
    #[error("xdr processing error: {0}")]
    Xdr(#[from] XdrError),
    #[error("invalid rpc url: {0}")]
    InvalidRpcUrl(http::uri::InvalidUri),
    #[error("invalid rpc url: {0}")]
    InvalidRpcUrlFromUriParts(http::uri::InvalidUriParts),
    #[error("invalid friendbot url: {0}")]
    InvalidUrl(String),
    #[error(transparent)]
    JsonRpc(#[from] jsonrpsee_core::Error),
    #[error("json decoding error: {0}")]
    Serde(#[from] serde_json::Error),
    #[error("transaction failed: {0}")]
    TransactionFailed(String),
    #[error("transaction submission failed: {0}")]
    TransactionSubmissionFailed(String),
    #[error("expected transaction status: {0}")]
    UnexpectedTransactionStatus(String),
    #[error("transaction submission timeout")]
    TransactionSubmissionTimeout,
    #[error("transaction simulation failed: {0}")]
    TransactionSimulationFailed(String),
    #[error("{0} not found: {1}")]
    NotFound(String, String),
    #[error("Missing result in successful response")]
    MissingResult,
    #[error("Failed to read Error response from server")]
    MissingError,
    #[error("Missing signing key for account {address}")]
    MissingSignerForAddress { address: String },
    #[error("cursor is not valid")]
    InvalidCursor,
    #[error("unexpected ({length}) simulate transaction result length")]
    UnexpectedSimulateTransactionResultSize { length: usize },
    #[error("unexpected ({count}) number of operations")]
    UnexpectedOperationCount { count: usize },
    #[error("Transaction contains unsupported operation type")]
    UnsupportedOperationType,
    #[error("unexpected contract code data type: {0:?}")]
    UnexpectedContractCodeDataType(LedgerEntryData),
    #[error("unexpected contract instance type: {0:?}")]
    UnexpectedContractInstance(xdr::ScVal),
    #[error("unexpected contract code got token")]
    UnexpectedToken(ContractDataEntry),
    #[error("Fee was too large {0}")]
    LargeFee(u64),
    #[error("Cannot authorize raw transactions")]
    CannotAuthorizeRawTransaction,

    #[error("Missing result for tnx")]
    MissingOp,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct SendTransactionResponse {
    pub hash: String,
    pub status: String,
    #[serde(
        rename = "errorResultXdr",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub error_result_xdr: Option<String>,
    #[serde(rename = "latestLedger")]
    pub latest_ledger: u32,
    #[serde(
        rename = "latestLedgerCloseTime",
        deserialize_with = "deserialize_number_from_string"
    )]
    pub latest_ledger_close_time: u32,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct GetTransactionResponseRaw {
    pub status: String,
    #[serde(
        rename = "envelopeXdr",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub envelope_xdr: Option<String>,
    #[serde(rename = "resultXdr", skip_serializing_if = "Option::is_none", default)]
    pub result_xdr: Option<String>,
    #[serde(
        rename = "resultMetaXdr",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub result_meta_xdr: Option<String>,
    // TODO: add ledger info and application order
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct GetTransactionResponse {
    pub status: String,
    pub envelope: Option<xdr::TransactionEnvelope>,
    pub result: Option<xdr::TransactionResult>,
    pub result_meta: Option<xdr::TransactionMeta>,
}

impl TryInto<GetTransactionResponse> for GetTransactionResponseRaw {
    type Error = xdr::Error;

    fn try_into(self) -> Result<GetTransactionResponse, Self::Error> {
        Ok(GetTransactionResponse {
            status: self.status,
            envelope: self
                .envelope_xdr
                .map(|v| ReadXdr::from_xdr_base64(v, Limits::none()))
                .transpose()?,
            result: self
                .result_xdr
                .map(|v| ReadXdr::from_xdr_base64(v, Limits::none()))
                .transpose()?,
            result_meta: self
                .result_meta_xdr
                .map(|v| ReadXdr::from_xdr_base64(v, Limits::none()))
                .transpose()?,
        })
    }
}

impl GetTransactionResponse {
    ///
    /// # Errors
    pub fn return_value(&self) -> Result<xdr::ScVal, Error> {
        if let Some(xdr::TransactionMeta::V3(xdr::TransactionMetaV3 {
            soroban_meta: Some(xdr::SorobanTransactionMeta { return_value, .. }),
            ..
        })) = &self.result_meta
        {
            Ok(return_value.clone())
        } else {
            Err(Error::MissingOp)
        }
    }

    ///
    /// # Errors
    pub fn events(&self) -> Result<Vec<DiagnosticEvent>, Error> {
        self.result_meta
            .as_ref()
            .map(extract_events)
            .ok_or(Error::MissingOp)
    }

    ///
    /// # Errors
    pub fn contract_events(&self) -> Result<Vec<DiagnosticEvent>, Error> {
        Ok(self
            .events()?
            .into_iter()
            .filter(|e| matches!(e.event.type_, ContractEventType::Contract))
            .collect::<Vec<_>>())
    }
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct LedgerEntryResult {
    pub key: String,
    pub xdr: String,
    #[serde(rename = "lastModifiedLedgerSeq")]
    pub last_modified_ledger: u32,
    #[serde(
        rename = "liveUntilLedgerSeq",
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_option_number_from_string",
        default
    )]
    pub live_until_ledger_seq_ledger_seq: Option<u32>,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct GetLedgerEntriesResponse {
    pub entries: Option<Vec<LedgerEntryResult>>,
    #[serde(rename = "latestLedger")]
    pub latest_ledger: i64,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct GetNetworkResponse {
    #[serde(
        rename = "friendbotUrl",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub friendbot_url: Option<String>,
    pub passphrase: String,
    #[serde(rename = "protocolVersion")]
    pub protocol_version: u32,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct GetLatestLedgerResponse {
    pub id: String,
    #[serde(rename = "protocolVersion")]
    pub protocol_version: u32,
    pub sequence: u32,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Default, Clone)]
pub struct Cost {
    #[serde(
        rename = "cpuInsns",
        deserialize_with = "deserialize_number_from_string"
    )]
    pub cpu_insns: u64,
    #[serde(
        rename = "memBytes",
        deserialize_with = "deserialize_number_from_string"
    )]
    pub mem_bytes: u64,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct SimulateHostFunctionResultRaw {
    #[serde(deserialize_with = "deserialize_default_from_null")]
    pub auth: Vec<String>,
    pub xdr: String,
}

#[derive(Debug, Clone)]
pub struct SimulateHostFunctionResult {
    pub auth: Vec<SorobanAuthorizationEntry>,
    pub xdr: xdr::ScVal,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, PartialEq)]
#[serde(tag = "type")]
pub enum LedgerEntryChange {
    #[serde(rename = "created")]
    Created { key: String, after: String },
    #[serde(rename = "deleted")]
    Deleted { key: String, before: String },
    #[serde(rename = "updated")]
    Updated {
        key: String,
        before: String,
        after: String,
    },
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Default, Clone)]
pub struct SimulateTransactionResponse {
    #[serde(
        rename = "minResourceFee",
        deserialize_with = "deserialize_number_from_string",
        default
    )]
    pub min_resource_fee: u64,
    #[serde(default)]
    pub cost: Cost,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub results: Vec<SimulateHostFunctionResultRaw>,
    #[serde(rename = "transactionData", default)]
    pub transaction_data: String,
    #[serde(
        deserialize_with = "deserialize_default_from_null",
        skip_serializing_if = "Vec::is_empty",
        default
    )]
    pub events: Vec<String>,
    #[serde(
        rename = "restorePreamble",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub restore_preamble: Option<RestorePreamble>,
    #[serde(
        rename = "stateChanges",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub state_changes: Option<Vec<LedgerEntryChange>>,
    #[serde(rename = "latestLedger")]
    pub latest_ledger: u32,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub error: Option<String>,
}

impl SimulateTransactionResponse {
    ///
    /// # Errors
    pub fn results(&self) -> Result<Vec<SimulateHostFunctionResult>, Error> {
        self.results
            .iter()
            .map(|r| {
                Ok(SimulateHostFunctionResult {
                    auth: r
                        .auth
                        .iter()
                        .map(|a| {
                            Ok(SorobanAuthorizationEntry::from_xdr_base64(
                                a,
                                Limits::none(),
                            )?)
                        })
                        .collect::<Result<_, Error>>()?,
                    xdr: xdr::ScVal::from_xdr_base64(&r.xdr, Limits::none())?,
                })
            })
            .collect()
    }

    ///
    /// # Errors
    pub fn events(&self) -> Result<Vec<DiagnosticEvent>, Error> {
        self.events
            .iter()
            .map(|e| Ok(DiagnosticEvent::from_xdr_base64(e, Limits::none())?))
            .collect()
    }

    ///
    /// # Errors
    pub fn transaction_data(&self) -> Result<SorobanTransactionData, Error> {
        Ok(SorobanTransactionData::from_xdr_base64(
            &self.transaction_data,
            Limits::none(),
        )?)
    }
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Default, Clone)]
pub struct RestorePreamble {
    #[serde(rename = "transactionData")]
    pub transaction_data: String,
    #[serde(
        rename = "minResourceFee",
        deserialize_with = "deserialize_number_from_string"
    )]
    pub min_resource_fee: u64,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct GetEventsResponse {
    #[serde(deserialize_with = "deserialize_default_from_null")]
    pub events: Vec<Event>,
    #[serde(rename = "latestLedger")]
    pub latest_ledger: u32,
}

// Determines whether or not a particular filter matches a topic based on the
// same semantics as the RPC server:
//
//  - for an exact segment match, the filter is a base64-encoded ScVal
//  - for a wildcard, single-segment match, the string "*" matches exactly one
//    segment
//
// The expectation is that a `filter` is a comma-separated list of segments that
// has previously been validated, and `topic` is the list of segments applicable
// for this event.
//
// [API
// Reference](https://docs.google.com/document/d/1TZUDgo_3zPz7TiPMMHVW_mtogjLyPL0plvzGMsxSz6A/edit#bookmark=id.35t97rnag3tx)
// [Code
// Reference](https://github.com/stellar/soroban-tools/blob/bac1be79e8c2590c9c35ad8a0168aab0ae2b4171/cmd/soroban-rpc/internal/methods/get_events.go#L182-L203)
#[must_use]
pub fn does_topic_match(topic: &[String], filter: &[String]) -> bool {
    filter.len() == topic.len()
        && filter
            .iter()
            .enumerate()
            .all(|(i, s)| *s == "*" || topic[i] == *s)
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub struct Event {
    #[serde(rename = "type")]
    pub event_type: String,

    pub ledger: u32,
    #[serde(rename = "ledgerClosedAt")]
    pub ledger_closed_at: String,

    pub id: String,
    #[serde(rename = "pagingToken")]
    pub paging_token: String,

    #[serde(rename = "contractId")]
    pub contract_id: String,
    pub topic: Vec<String>,
    pub value: String,
}

impl Display for Event {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "Event {} [{}]:",
            self.paging_token,
            self.event_type.to_ascii_uppercase()
        )?;
        writeln!(
            f,
            "  Ledger:   {} (closed at {})",
            self.ledger, self.ledger_closed_at
        )?;
        writeln!(f, "  Contract: {}", self.contract_id)?;
        writeln!(f, "  Topics:")?;
        for topic in &self.topic {
            let scval =
                xdr::ScVal::from_xdr_base64(topic, Limits::none()).map_err(|_| std::fmt::Error)?;
            writeln!(f, "            {scval:?}")?;
        }
        let scval = xdr::ScVal::from_xdr_base64(&self.value, Limits::none())
            .map_err(|_| std::fmt::Error)?;
        writeln!(f, "  Value:    {scval:?}")
    }
}

impl Event {
    ///
    /// # Errors
    pub fn parse_cursor(&self) -> Result<(u64, i32), Error> {
        parse_cursor(&self.id)
    }
    ///
    /// # Errors
    pub fn pretty_print(&self) -> Result<(), Box<dyn std::error::Error>> {
        let mut stdout = StandardStream::stdout(ColorChoice::Auto);
        if !stdout.supports_color() {
            println!("{self}");
            return Ok(());
        }

        let color = match self.event_type.as_str() {
            "system" => Color::Yellow,
            _ => Color::Blue,
        };
        colored!(
            stdout,
            "{}Event{} {}{}{} [{}{}{}{}]:\n",
            bold!(true),
            bold!(false),
            fg!(Some(Color::Green)),
            self.paging_token,
            reset!(),
            bold!(true),
            fg!(Some(color)),
            self.event_type.to_ascii_uppercase(),
            reset!(),
        )?;

        colored!(
            stdout,
            "  Ledger:   {}{}{} (closed at {}{}{})\n",
            fg!(Some(Color::Green)),
            self.ledger,
            reset!(),
            fg!(Some(Color::Green)),
            self.ledger_closed_at,
            reset!(),
        )?;

        colored!(
            stdout,
            "  Contract: {}{}{}\n",
            fg!(Some(Color::Green)),
            self.contract_id,
            reset!(),
        )?;

        colored!(stdout, "  Topics:\n")?;
        for topic in &self.topic {
            let scval = xdr::ScVal::from_xdr_base64(topic, Limits::none())?;
            colored!(
                stdout,
                "            {}{:?}{}\n",
                fg!(Some(Color::Green)),
                scval,
                reset!(),
            )?;
        }

        let scval = xdr::ScVal::from_xdr_base64(&self.value, Limits::none())?;
        colored!(
            stdout,
            "  Value: {}{:?}{}\n",
            fg!(Some(Color::Green)),
            scval,
            reset!(),
        )?;

        Ok(())
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, clap::ValueEnum)]
pub enum EventType {
    All,
    Contract,
    System,
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum EventStart {
    Ledger(u32),
    Cursor(String),
}

#[derive(Debug, Clone)]
pub struct FullLedgerEntry {
    pub key: LedgerKey,
    pub val: LedgerEntryData,
    pub last_modified_ledger: u32,
    pub live_until_ledger_seq: u32,
}

#[derive(Debug, Clone)]
pub struct FullLedgerEntries {
    pub entries: Vec<FullLedgerEntry>,
    pub latest_ledger: i64,
}

#[derive(Debug, Clone)]
pub struct Client {
    base_url: Arc<str>,
    timeout_in_secs: u64,
    http_client: Arc<HttpClient>,
}

impl Client {
    ///
    /// # Errors
    pub fn new(base_url: &str) -> Result<Self, Error> {
        // Add the port to the base URL if there is no port explicitly included
        // in the URL and the scheme allows us to infer a default port.
        // Jsonrpsee requires a port to always be present even if one can be
        // inferred. This may change: https://github.com/paritytech/jsonrpsee/issues/1048.
        let uri = base_url.parse::<Uri>().map_err(Error::InvalidRpcUrl)?;
        let mut parts = uri.into_parts();
        if let (Some(scheme), Some(authority)) = (&parts.scheme, &parts.authority) {
            if authority.port().is_none() {
                let port = match scheme.as_str() {
                    "http" => Some(80),
                    "https" => Some(443),
                    _ => None,
                };
                if let Some(port) = port {
                    let host = authority.host();
                    parts.authority = Some(
                        Authority::from_str(&format!("{host}:{port}"))
                            .map_err(Error::InvalidRpcUrl)?,
                    );
                }
            }
        }
        let uri = Uri::from_parts(parts).map_err(Error::InvalidRpcUrlFromUriParts)?;
        let base_url = Arc::from(uri.to_string());
        tracing::trace!(?uri);
        let mut headers = HeaderMap::new();
        headers.insert("X-Client-Name", unsafe {
            "soroban-cli".parse().unwrap_unchecked()
        });
        let version = VERSION.unwrap_or("devel");
        headers.insert("X-Client-Version", unsafe {
            version.parse().unwrap_unchecked()
        });
        let http_client = Arc::new(
            HttpClientBuilder::default()
                .set_headers(headers)
                .build(&base_url)?,
        );
        Ok(Self {
            base_url,
            timeout_in_secs: 30,
            http_client,
        })
    }

    #[must_use]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Create a new client with a timeout in seconds
    /// # Errors
    pub fn new_with_timeout(base_url: &str, timeout: u64) -> Result<Self, Error> {
        let mut client = Self::new(base_url)?;
        client.timeout_in_secs = timeout;
        Ok(client)
    }

    #[must_use]
    pub fn client(&self) -> &HttpClient {
        &self.http_client
    }

    ///
    /// # Errors
    pub async fn friendbot_url(&self) -> Result<String, Error> {
        let network = self.get_network().await?;
        tracing::trace!("{network:#?}");
        network.friendbot_url.ok_or_else(|| {
            Error::NotFound(
                "Friendbot".to_string(),
                "Friendbot is not available on this network".to_string(),
            )
        })
    }
    ///
    /// # Errors
    pub async fn verify_network_passphrase(&self, expected: Option<&str>) -> Result<String, Error> {
        let server = self.get_network().await?.passphrase;
        if let Some(expected) = expected {
            if expected != server {
                return Err(Error::InvalidNetworkPassphrase {
                    expected: expected.to_string(),
                    server,
                });
            }
        }
        Ok(server)
    }

    ///
    /// # Errors
    pub async fn get_network(&self) -> Result<GetNetworkResponse, Error> {
        tracing::trace!("Getting network");
        Ok(self
            .client()
            .request("getNetwork", ObjectParams::new())
            .await?)
    }

    ///
    /// # Errors
    pub async fn get_latest_ledger(&self) -> Result<GetLatestLedgerResponse, Error> {
        tracing::trace!("Getting latest ledger");
        Ok(self
            .client()
            .request("getLatestLedger", ObjectParams::new())
            .await?)
    }

    ///
    /// # Errors
    pub async fn get_account(&self, address: &str) -> Result<AccountEntry, Error> {
        tracing::trace!("Getting address {}", address);
        let key = LedgerKey::Account(LedgerKeyAccount {
            account_id: AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(
                stellar_strkey::ed25519::PublicKey::from_string(address)?.0,
            ))),
        });
        let keys = Vec::from([key]);
        let response = self.get_ledger_entries(&keys).await?;
        let entries = response.entries.unwrap_or_default();
        if entries.is_empty() {
            return Err(Error::NotFound("Account".to_string(), address.to_owned()));
        }
        let ledger_entry = &entries[0];
        let mut read = Limited::new(ledger_entry.xdr.as_bytes(), Limits::none());
        if let LedgerEntryData::Account(entry) = LedgerEntryData::read_xdr_base64(&mut read)? {
            tracing::trace!(account=?entry);
            Ok(entry)
        } else {
            Err(Error::InvalidResponse)
        }
    }

    /// Send a transaction to the network and get back the hash of the transaction.
    /// # Errors
    pub async fn send_transaction(&self, tx: &TransactionEnvelope) -> Result<Hash, Error> {
        tracing::trace!("Sending:\n{tx:#?}");
        let mut oparams = ObjectParams::new();
        oparams.insert("transaction", tx.to_xdr_base64(Limits::none())?)?;
        let SendTransactionResponse {
            hash,
            error_result_xdr,
            status,
            ..
        } = self
            .client()
            .request("sendTransaction", oparams)
            .await
            .map_err(|err| {
                Error::TransactionSubmissionFailed(format!("No status yet:\n {err:#?}"))
            })?;

        if status == "ERROR" {
            let error = error_result_xdr
                .ok_or(Error::MissingError)
                .and_then(|x| {
                    TransactionResult::read_xdr_base64(&mut Limited::new(
                        x.as_bytes(),
                        Limits::none(),
                    ))
                    .map_err(|_| Error::InvalidResponse)
                })
                .map(|r| r.result);
            tracing::error!("TXN {hash} failed:\n {error:#?}");
            return Err(Error::TransactionSubmissionFailed(format!("{:#?}", error?)));
        }
        Ok(Hash::from_str(&hash)?)
    }

    ///
    /// # Errors
    pub async fn send_transaction_polling(
        &self,
        tx: &TransactionEnvelope,
    ) -> Result<GetTransactionResponse, Error> {
        let hash = self.send_transaction(tx).await?;
        self.get_transaction_polling(&hash, None).await
    }

    ///
    /// # Errors
    pub async fn simulate_and_assemble_transaction(
        &self,
        tx: &Transaction,
    ) -> Result<Assembled, Error> {
        let sim_res = self
            .simulate_transaction_envelope(&TransactionEnvelope::Tx(TransactionV1Envelope {
                tx: tx.clone(),
                signatures: VecM::default(),
            }))
            .await?;
        match sim_res.error {
            None => Ok(Assembled::new(tx, sim_res)?),
            Some(e) => {
                log::diagnostic_events(&sim_res.events, tracing::Level::ERROR);
                Err(Error::TransactionSimulationFailed(e))
            }
        }
    }

    ///
    /// # Errors
    pub async fn simulate_transaction_envelope(
        &self,
        tx: &TransactionEnvelope,
    ) -> Result<SimulateTransactionResponse, Error> {
        tracing::trace!("Simulating:\n{tx:#?}");
        let base64_tx = tx.to_xdr_base64(Limits::none())?;
        let mut oparams = ObjectParams::new();
        oparams.insert("transaction", base64_tx)?;
        let sim_res = self
            .client()
            .request("simulateTransaction", oparams)
            .await?;
        tracing::trace!("Simulation response:\n {sim_res:#?}");
        Ok(sim_res)
    }

    ///
    /// # Errors
    pub async fn get_transaction(&self, tx_id: &Hash) -> Result<GetTransactionResponse, Error> {
        let mut oparams = ObjectParams::new();
        oparams.insert("hash", tx_id)?;
        Ok(self.client().request("getTransaction", oparams).await?)
    }

    /// Poll the transaction status. Can provide a timeout in seconds, otherwise uses the default timeout.
    ///
    /// It uses exponential backoff with a base of 1 second and a maximum of 30 seconds.
    ///
    /// # Errors
    /// - `Error::TransactionSubmissionTimeout` if the transaction status is not found within the timeout
    /// - `Error::TransactionSubmissionFailed` if the transaction status is "FAILED"
    /// - `Error::UnexpectedTransactionStatus` if the transaction status is not one of "SUCCESS", "FAILED", or ``NOT_FOUND``
    /// - `json_rpsee` Errors
    pub async fn get_transaction_polling(
        &self,
        tx_id: &Hash,
        timeout_s: Option<Duration>,
    ) -> Result<GetTransactionResponse, Error> {
        // Poll the transaction status
        let start = Instant::now();
        let timeout = timeout_s.unwrap_or(Duration::from_secs(self.timeout_in_secs));
        // see https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=50731
        // Is optimimal exponent for expontial backoff
        let exponential_backoff: f64 = 1.0 / (1.0 - E.powf(-1.0));
        let mut sleep_time = Duration::from_secs(1);
        loop {
            let response = self.get_transaction(tx_id).await?;
            match response.status.as_str() {
                "SUCCESS" => {
                    // TODO: the caller should probably be printing this
                    tracing::trace!("{response:#?}");
                    return Ok(response);
                }
                "FAILED" => {
                    tracing::error!("{response:#?}");
                    // TODO: provide a more elaborate error
                    return Err(Error::TransactionSubmissionFailed(format!(
                        "{:#?}",
                        response.result
                    )));
                }
                "NOT_FOUND" => (),
                _ => {
                    return Err(Error::UnexpectedTransactionStatus(response.status));
                }
            };
            if start.elapsed() > timeout {
                return Err(Error::TransactionSubmissionTimeout);
            }
            sleep(sleep_time).await;
            sleep_time = Duration::from_secs_f64(sleep_time.as_secs_f64() * exponential_backoff);
        }
    }

    ///
    /// # Errors
    pub async fn get_ledger_entries(
        &self,
        keys: &[LedgerKey],
    ) -> Result<GetLedgerEntriesResponse, Error> {
        let mut base64_keys: Vec<String> = vec![];
        for k in keys {
            let base64_result = k.to_xdr_base64(Limits::none());
            if base64_result.is_err() {
                return Err(Error::Xdr(XdrError::Invalid));
            }
            base64_keys.push(k.to_xdr_base64(Limits::none())?);
        }
        let mut oparams = ObjectParams::new();
        oparams.insert("keys", base64_keys)?;
        Ok(self.client().request("getLedgerEntries", oparams).await?)
    }

    ///
    /// # Errors
    pub async fn get_full_ledger_entries(
        &self,
        ledger_keys: &[LedgerKey],
    ) -> Result<FullLedgerEntries, Error> {
        let keys = ledger_keys
            .iter()
            .filter(|key| !matches!(key, LedgerKey::Ttl(_)))
            .map(Clone::clone)
            .collect::<Vec<_>>();
        tracing::trace!("keys: {keys:#?}");
        let GetLedgerEntriesResponse {
            entries,
            latest_ledger,
        } = self.get_ledger_entries(&keys).await?;
        tracing::trace!("raw: {entries:#?}");
        let entries = entries
            .unwrap_or_default()
            .iter()
            .map(
                |LedgerEntryResult {
                     key,
                     xdr,
                     last_modified_ledger,
                     live_until_ledger_seq_ledger_seq,
                 }| {
                    Ok(FullLedgerEntry {
                        key: LedgerKey::from_xdr_base64(key, Limits::none())?,
                        val: LedgerEntryData::from_xdr_base64(xdr, Limits::none())?,
                        live_until_ledger_seq: live_until_ledger_seq_ledger_seq.unwrap_or_default(),
                        last_modified_ledger: *last_modified_ledger,
                    })
                },
            )
            .collect::<Result<Vec<_>, Error>>()?;
        tracing::trace!("parsed: {entries:#?}");
        Ok(FullLedgerEntries {
            entries,
            latest_ledger,
        })
    }
    ///
    /// # Errors
    pub async fn get_events(
        &self,
        start: EventStart,
        event_type: Option<EventType>,
        contract_ids: &[String],
        topics: &[String],
        limit: Option<usize>,
    ) -> Result<GetEventsResponse, Error> {
        let mut filters = serde_json::Map::new();

        event_type
            .and_then(|t| match t {
                EventType::All => None, // all is the default, so avoid incl. the param
                EventType::Contract => Some("contract"),
                EventType::System => Some("system"),
            })
            .map(|t| filters.insert("type".to_string(), t.into()));

        filters.insert("topics".to_string(), topics.into());
        filters.insert("contractIds".to_string(), contract_ids.into());

        let mut pagination = serde_json::Map::new();
        if let Some(limit) = limit {
            pagination.insert("limit".to_string(), limit.into());
        }

        let mut oparams = ObjectParams::new();
        match start {
            EventStart::Ledger(l) => oparams.insert("startLedger", l)?,
            EventStart::Cursor(c) => {
                pagination.insert("cursor".to_string(), c.into());
            }
        };
        oparams.insert("filters", vec![filters])?;
        oparams.insert("pagination", pagination)?;

        Ok(self.client().request("getEvents", oparams).await?)
    }

    ///
    /// # Errors
    pub async fn get_contract_data(
        &self,
        contract_id: &[u8; 32],
    ) -> Result<ContractDataEntry, Error> {
        // Get the contract from the network
        let contract_key = LedgerKey::ContractData(xdr::LedgerKeyContractData {
            contract: xdr::ScAddress::Contract(xdr::Hash(*contract_id)),
            key: xdr::ScVal::LedgerKeyContractInstance,
            durability: xdr::ContractDataDurability::Persistent,
        });
        let contract_ref = self.get_ledger_entries(&[contract_key]).await?;
        let entries = contract_ref.entries.unwrap_or_default();
        if entries.is_empty() {
            let contract_address = stellar_strkey::Contract(*contract_id).to_string();
            return Err(Error::NotFound("Contract".to_string(), contract_address));
        }
        let contract_ref_entry = &entries[0];
        match LedgerEntryData::from_xdr_base64(&contract_ref_entry.xdr, Limits::none())? {
            LedgerEntryData::ContractData(contract_data) => Ok(contract_data),
            scval => Err(Error::UnexpectedContractCodeDataType(scval)),
        }
    }

    ///
    /// # Errors
    pub async fn get_remote_wasm(&self, contract_id: &[u8; 32]) -> Result<Vec<u8>, Error> {
        match self.get_contract_data(contract_id).await? {
            xdr::ContractDataEntry {
                val:
                    xdr::ScVal::ContractInstance(xdr::ScContractInstance {
                        executable: xdr::ContractExecutable::Wasm(hash),
                        ..
                    }),
                ..
            } => self.get_remote_wasm_from_hash(hash).await,
            scval => Err(Error::UnexpectedToken(scval)),
        }
    }

    ///
    /// # Errors
    pub async fn get_remote_wasm_from_hash(&self, hash: xdr::Hash) -> Result<Vec<u8>, Error> {
        let code_key = LedgerKey::ContractCode(xdr::LedgerKeyContractCode { hash: hash.clone() });
        let contract_data = self.get_ledger_entries(&[code_key]).await?;
        let entries = contract_data.entries.unwrap_or_default();
        if entries.is_empty() {
            return Err(Error::NotFound(
                "Contract Code".to_string(),
                hex::encode(hash),
            ));
        }
        let contract_data_entry = &entries[0];
        match LedgerEntryData::from_xdr_base64(&contract_data_entry.xdr, Limits::none())? {
            LedgerEntryData::ContractCode(xdr::ContractCodeEntry { code, .. }) => Ok(code.into()),
            scval => Err(Error::UnexpectedContractCodeDataType(scval)),
        }
    }

    /// Get the contract instance from the network. Could be normal contract or native Stellar Asset Contract (SAC)
    ///
    /// # Errors
    /// - Could fail to find contract or have a network error
    pub async fn get_contract_instance(
        &self,
        contract_id: &[u8; 32],
    ) -> Result<ScContractInstance, Error> {
        let contract_data = self.get_contract_data(contract_id).await?;
        match contract_data.val {
            xdr::ScVal::ContractInstance(instance) => Ok(instance),
            scval => Err(Error::UnexpectedContractInstance(scval)),
        }
    }
}

fn extract_events(tx_meta: &TransactionMeta) -> Vec<DiagnosticEvent> {
    match tx_meta {
        TransactionMeta::V3(TransactionMetaV3 {
            soroban_meta: Some(meta),
            ..
        }) => {
            // NOTE: we assume there can only be one operation, since we only send one
            if meta.diagnostic_events.len() == 1 {
                meta.diagnostic_events.clone().into()
            } else if meta.events.len() == 1 {
                meta.events
                    .iter()
                    .map(|e| DiagnosticEvent {
                        in_successful_contract_call: true,
                        event: e.clone(),
                    })
                    .collect()
            } else {
                Vec::new()
            }
        }
        _ => Vec::new(),
    }
}

pub(crate) fn parse_cursor(c: &str) -> Result<(u64, i32), Error> {
    let (toid_part, event_index) = c.split('-').collect_tuple().ok_or(Error::InvalidCursor)?;
    let toid_part: u64 = toid_part.parse().map_err(|_| Error::InvalidCursor)?;
    let start_index: i32 = event_index.parse().map_err(|_| Error::InvalidCursor)?;
    Ok((toid_part, start_index))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn simulation_transaction_response_parsing() {
        let s = r#"{
 "minResourceFee": "100000000",
 "cost": { "cpuInsns": "1000", "memBytes": "1000" },
 "transactionData": "",
 "latestLedger": 1234,
 "stateChanges": [{
    "type": "created",
    "key": "AAAAAAAAAABuaCbVXZ2DlXWarV6UxwbW3GNJgpn3ASChIFp5bxSIWg==",
    "before": null,
    "after": "AAAAZAAAAAAAAAAAbmgm1V2dg5V1mq1elMcG1txjSYKZ9wEgoSBaeW8UiFoAAAAAAAAAZAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
  }]
  }"#;

        let resp: SimulateTransactionResponse = serde_json::from_str(s).unwrap();
        assert_eq!(
            resp.state_changes.unwrap()[0],
            LedgerEntryChange::Created { key: "AAAAAAAAAABuaCbVXZ2DlXWarV6UxwbW3GNJgpn3ASChIFp5bxSIWg==".to_string(), after: "AAAAZAAAAAAAAAAAbmgm1V2dg5V1mq1elMcG1txjSYKZ9wEgoSBaeW8UiFoAAAAAAAAAZAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".to_string() },
        );
        assert_eq!(resp.min_resource_fee, 100_000_000);
    }

    #[test]
    fn simulation_transaction_response_parsing_mostly_empty() {
        let s = r#"{
 "latestLedger": 1234
        }"#;

        let resp: SimulateTransactionResponse = serde_json::from_str(s).unwrap();
        assert_eq!(resp.latest_ledger, 1_234);
    }

    #[test]
    fn test_rpc_url_default_ports() {
        // Default ports are added.
        let client = Client::new("http://example.com").unwrap();
        assert_eq!(client.base_url(), "http://example.com:80/");
        let client = Client::new("https://example.com").unwrap();
        assert_eq!(client.base_url(), "https://example.com:443/");

        // Ports are not added when already present.
        let client = Client::new("http://example.com:8080").unwrap();
        assert_eq!(client.base_url(), "http://example.com:8080/");
        let client = Client::new("https://example.com:8080").unwrap();
        assert_eq!(client.base_url(), "https://example.com:8080/");

        // Paths are not modified.
        let client = Client::new("http://example.com/a/b/c").unwrap();
        assert_eq!(client.base_url(), "http://example.com:80/a/b/c");
        let client = Client::new("https://example.com/a/b/c").unwrap();
        assert_eq!(client.base_url(), "https://example.com:443/a/b/c");
        let client = Client::new("http://example.com/a/b/c/").unwrap();
        assert_eq!(client.base_url(), "http://example.com:80/a/b/c/");
        let client = Client::new("https://example.com/a/b/c/").unwrap();
        assert_eq!(client.base_url(), "https://example.com:443/a/b/c/");
        let client = Client::new("http://example.com/a/b:80/c/").unwrap();
        assert_eq!(client.base_url(), "http://example.com:80/a/b:80/c/");
        let client = Client::new("https://example.com/a/b:80/c/").unwrap();
        assert_eq!(client.base_url(), "https://example.com:443/a/b:80/c/");
    }

    #[test]
    // Taken from [RPC server
    // tests](https://github.com/stellar/soroban-tools/blob/main/cmd/soroban-rpc/internal/methods/get_events_test.go#L21).
    fn test_does_topic_match() {
        struct TestCase<'a> {
            name: &'a str,
            filter: Vec<&'a str>,
            includes: Vec<Vec<&'a str>>,
            excludes: Vec<Vec<&'a str>>,
        }

        let xfer = "AAAABQAAAAh0cmFuc2Zlcg==";
        let number = "AAAAAQB6Mcc=";
        let star = "*";

        for tc in vec![
            // No filter means match nothing.
            TestCase {
                name: "<empty>",
                filter: vec![],
                includes: vec![],
                excludes: vec![vec![xfer]],
            },
            // "*" should match "transfer/" but not "transfer/transfer" or
            // "transfer/amount", because * is specified as a SINGLE segment
            // wildcard.
            TestCase {
                name: "*",
                filter: vec![star],
                includes: vec![vec![xfer]],
                excludes: vec![vec![xfer, xfer], vec![xfer, number]],
            },
            // "*/transfer" should match anything preceding "transfer", but
            // nothing that isn't exactly two segments long.
            TestCase {
                name: "*/transfer",
                filter: vec![star, xfer],
                includes: vec![vec![number, xfer], vec![xfer, xfer]],
                excludes: vec![
                    vec![number],
                    vec![number, number],
                    vec![number, xfer, number],
                    vec![xfer],
                    vec![xfer, number],
                    vec![xfer, xfer, xfer],
                ],
            },
            // The inverse case of before: "transfer/*" should match any single
            // segment after a segment that is exactly "transfer", but no
            // additional segments.
            TestCase {
                name: "transfer/*",
                filter: vec![xfer, star],
                includes: vec![vec![xfer, number], vec![xfer, xfer]],
                excludes: vec![
                    vec![number],
                    vec![number, number],
                    vec![number, xfer, number],
                    vec![xfer],
                    vec![number, xfer],
                    vec![xfer, xfer, xfer],
                ],
            },
            // Here, we extend to exactly two wild segments after transfer.
            TestCase {
                name: "transfer/*/*",
                filter: vec![xfer, star, star],
                includes: vec![vec![xfer, number, number], vec![xfer, xfer, xfer]],
                excludes: vec![
                    vec![number],
                    vec![number, number],
                    vec![number, xfer],
                    vec![number, xfer, number, number],
                    vec![xfer],
                    vec![xfer, xfer, xfer, xfer],
                ],
            },
            // Here, we ensure wildcards can be in the middle of a filter: only
            // exact matches happen on the ends, while the middle can be
            // anything.
            TestCase {
                name: "transfer/*/number",
                filter: vec![xfer, star, number],
                includes: vec![vec![xfer, number, number], vec![xfer, xfer, number]],
                excludes: vec![
                    vec![number],
                    vec![number, number],
                    vec![number, number, number],
                    vec![number, xfer, number],
                    vec![xfer],
                    vec![number, xfer],
                    vec![xfer, xfer, xfer],
                    vec![xfer, number, xfer],
                ],
            },
        ] {
            for topic in tc.includes {
                assert!(
                    does_topic_match(
                        &topic
                            .iter()
                            .map(std::string::ToString::to_string)
                            .collect::<Vec<String>>(),
                        &tc.filter
                            .iter()
                            .map(std::string::ToString::to_string)
                            .collect::<Vec<String>>()
                    ),
                    "test: {}, topic ({:?}) should be matched by filter ({:?})",
                    tc.name,
                    topic,
                    tc.filter
                );
            }

            for topic in tc.excludes {
                assert!(
                    !does_topic_match(
                        // make deep copies of the vecs
                        &topic
                            .iter()
                            .map(std::string::ToString::to_string)
                            .collect::<Vec<String>>(),
                        &tc.filter
                            .iter()
                            .map(std::string::ToString::to_string)
                            .collect::<Vec<String>>()
                    ),
                    "test: {}, topic ({:?}) should NOT be matched by filter ({:?})",
                    tc.name,
                    topic,
                    tc.filter
                );
            }
        }
    }
}