sol_rpc_client 6.0.0

Client to interact with the SOL RPC canister
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
#[cfg(test)]
mod tests;

use crate::{IcError, Runtime, SolRpcClient};
use candid::CandidType;
use derive_more::From;
use serde::de::DeserializeOwned;
use sol_rpc_types::{
    AccountInfo, CommitmentLevel, ConfirmedBlock, ConfirmedTransactionStatusWithSignature,
    ConsensusStrategy, DataSlice, EncodedConfirmedTransactionWithStatusMeta,
    GetAccountInfoEncoding, GetAccountInfoParams, GetBalanceParams, GetBlockCommitmentLevel,
    GetBlockParams, GetRecentPrioritizationFeesParams, GetRecentPrioritizationFeesRpcConfig,
    GetSignatureStatusesParams, GetSignaturesForAddressLimit, GetSignaturesForAddressParams,
    GetSlotParams, GetSlotRpcConfig, GetTokenAccountBalanceParams, GetTransactionEncoding,
    GetTransactionParams, Lamport, MultiRpcResult, NonZeroU8, PrioritizationFee, RoundingError,
    RpcConfig, RpcError, RpcResult, RpcSource, RpcSources, SendTransactionParams, Signature, Slot,
    TokenAmount, TransactionDetails, TransactionStatus,
};
use solana_account_decoder_client_types::token::UiTokenAmount;
use solana_transaction_status_client_types::UiConfirmedBlock;
use std::{
    fmt::{Debug, Formatter},
    num::NonZeroUsize,
};
use strum::EnumIter;
use thiserror::Error;

/// Solana RPC endpoint supported by the SOL RPC canister.
pub trait SolRpcRequest {
    /// Type of RPC config for that request.
    type Config;
    /// The type of parameters taken by this endpoint.
    type Params;
    /// The Candid type returned when executing this request which is then converted to [`Self::Output`].
    type CandidOutput;
    /// The type returned by this endpoint.
    type Output;

    /// The name of the endpoint on the SOL RPC canister.
    fn endpoint(&self) -> SolRpcEndpoint;

    /// Return the request parameters.
    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params;
}

/// Endpoint on the SOL RPC canister triggering a call to Solana providers.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, EnumIter)]
pub enum SolRpcEndpoint {
    /// `getAccountInfo` endpoint.
    GetAccountInfo,
    /// `getBalance` endpoint.
    GetBalance,
    /// `getBlock` endpoint.
    GetBlock,
    /// `getRecentPrioritizationFees` endpoint.
    GetRecentPrioritizationFees,
    /// `getSignaturesForAddress` endpoint.
    GetSignaturesForAddress,
    /// `getSignatureStatuses` endpoint.
    GetSignatureStatuses,
    /// `getSlot` endpoint.
    GetSlot,
    /// `getTokenAccountBalance` endpoint.
    GetTokenAccountBalance,
    /// `getTransaction` endpoint.
    GetTransaction,
    /// `jsonRequest` endpoint.
    JsonRequest,
    /// `sendTransaction` endpoint.
    SendTransaction,
}

impl SolRpcEndpoint {
    /// Method name on the SOL RPC canister
    pub fn rpc_method(&self) -> &'static str {
        match &self {
            SolRpcEndpoint::GetAccountInfo => "getAccountInfo",
            SolRpcEndpoint::GetBalance => "getBalance",
            SolRpcEndpoint::GetBlock => "getBlock",
            SolRpcEndpoint::GetRecentPrioritizationFees => "getRecentPrioritizationFees",
            SolRpcEndpoint::GetSignatureStatuses => "getSignatureStatuses",
            SolRpcEndpoint::GetSignaturesForAddress => "getSignaturesForAddress",
            SolRpcEndpoint::GetSlot => "getSlot",
            SolRpcEndpoint::GetTokenAccountBalance => "getTokenAccountBalance",
            SolRpcEndpoint::GetTransaction => "getTransaction",
            SolRpcEndpoint::JsonRequest => "jsonRequest",
            SolRpcEndpoint::SendTransaction => "sendTransaction",
        }
    }

    /// Method name on the SOL RPC canister to estimate the amount of cycles for that request.
    pub fn cycles_cost_method(&self) -> &'static str {
        match &self {
            SolRpcEndpoint::GetAccountInfo => "getAccountInfoCyclesCost",
            SolRpcEndpoint::GetBalance => "getBalanceCyclesCost",
            SolRpcEndpoint::GetBlock => "getBlockCyclesCost",
            SolRpcEndpoint::GetRecentPrioritizationFees => "getRecentPrioritizationFeesCyclesCost",
            SolRpcEndpoint::GetSignaturesForAddress => "getSignaturesForAddressCyclesCost",
            SolRpcEndpoint::GetSignatureStatuses => "getSignatureStatusesCyclesCost",
            SolRpcEndpoint::GetSlot => "getSlotCyclesCost",
            SolRpcEndpoint::GetTransaction => "getTransactionCyclesCost",
            SolRpcEndpoint::GetTokenAccountBalance => "getTokenAccountBalanceCyclesCost",
            SolRpcEndpoint::JsonRequest => "jsonRequestCyclesCost",
            SolRpcEndpoint::SendTransaction => "sendTransactionCyclesCost",
        }
    }
}

/// Specifies the default number of cycles attached with a request if it was not set.
pub trait DefaultRequestCycles {
    /// The default number of cycles to attach with this request.
    ///
    /// This method will be called just before sending the request and only if the user did not set a number of cycles to attach.
    fn default_request_cycles(&self) -> u128;
}

#[derive(Debug, Clone)]
pub struct GetAccountInfoRequest(GetAccountInfoParams);

impl GetAccountInfoRequest {
    pub fn new(params: GetAccountInfoParams) -> Self {
        Self(params)
    }
}

impl SolRpcRequest for GetAccountInfoRequest {
    type Config = RpcConfig;
    type Params = GetAccountInfoParams;
    type CandidOutput = MultiRpcResult<Option<AccountInfo>>;
    type Output = MultiRpcResult<Option<solana_account_decoder_client_types::UiAccount>>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetAccountInfo
    }

    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        let mut params = self.0;
        set_default(default_commitment_level, &mut params.commitment);
        params
    }
}

pub type GetAccountInfoRequestBuilder<R> = RequestBuilder<
    R,
    RpcConfig,
    GetAccountInfoParams,
    MultiRpcResult<Option<AccountInfo>>,
    MultiRpcResult<Option<solana_account_decoder_client_types::UiAccount>>,
>;

impl<R> DefaultRequestCycles for GetAccountInfoRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        10_000_000_000
    }
}

impl<R> GetAccountInfoRequestBuilder<R> {
    /// Change the `commitment` parameter for a `getAccountInfo` request.
    pub fn with_commitment(mut self, commitment: impl Into<CommitmentLevel>) -> Self {
        self.request.params.commitment = Some(commitment.into());
        self
    }

    /// Change the `encoding` parameter for a `getAccountInfo` request.
    pub fn with_encoding(mut self, encoding: impl Into<GetAccountInfoEncoding>) -> Self {
        self.request.params.encoding = Some(encoding.into());
        self
    }

    /// Change the `dataSlice` parameter for a `getAccountInfo` request.
    pub fn with_data_slice(mut self, data_slice: impl Into<DataSlice>) -> Self {
        self.request.params.data_slice = Some(data_slice.into());
        self
    }

    /// Change the `minContextSlot` parameter for a `getAccountInfo` request.
    pub fn with_min_context_slot(mut self, slot: Slot) -> Self {
        self.request.params.min_context_slot = Some(slot);
        self
    }
}

#[derive(Debug, Clone)]
pub struct GetBalanceRequest(GetBalanceParams);

impl GetBalanceRequest {
    pub fn new(params: GetBalanceParams) -> Self {
        Self(params)
    }
}

impl SolRpcRequest for GetBalanceRequest {
    type Config = RpcConfig;
    type Params = GetBalanceParams;
    type CandidOutput = MultiRpcResult<Lamport>;
    type Output = MultiRpcResult<Lamport>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetBalance
    }

    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        let mut params = self.0;
        set_default(default_commitment_level, &mut params.commitment);
        params
    }
}

pub type GetBalanceRequestBuilder<R> = RequestBuilder<
    R,
    RpcConfig,
    GetBalanceParams,
    MultiRpcResult<Lamport>,
    MultiRpcResult<Lamport>,
>;

impl<R> DefaultRequestCycles for GetBalanceRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        10_000_000_000
    }
}

impl<R> GetBalanceRequestBuilder<R> {
    /// Change the `commitment` parameter for a `getBalance` request.
    pub fn with_commitment(mut self, commitment_level: impl Into<CommitmentLevel>) -> Self {
        self.request.params.commitment = Some(commitment_level.into());
        self
    }

    /// Change the `minContextSlot` parameter for a `getBalance` request.
    pub fn with_min_context_slot(mut self, slot: Slot) -> Self {
        self.request.params.min_context_slot = Some(slot);
        self
    }
}

#[derive(Debug, Clone)]
pub struct GetBlockRequest(GetBlockParams);

impl GetBlockRequest {
    pub fn new(params: GetBlockParams) -> Self {
        Self(params)
    }
}

impl SolRpcRequest for GetBlockRequest {
    type Config = RpcConfig;
    type Params = GetBlockParams;
    type CandidOutput = MultiRpcResult<Option<ConfirmedBlock>>;
    type Output = MultiRpcResult<Option<UiConfirmedBlock>>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetBlock
    }

    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        let mut params = self.0;
        let default_block_commitment_level =
            default_commitment_level.map(|commitment| match commitment {
                CommitmentLevel::Processed => {
                    // The minimum commitment level for `getBlock` is `confirmed,
                    // `processed` is not supported.
                    // Not setting a value here would be equivalent to requiring the block to be `finalized`,
                    // which seems to go against the chosen `default_commitment_level` of `processed` and so `confirmed`
                    // is the best we can do here.
                    GetBlockCommitmentLevel::Confirmed
                }
                CommitmentLevel::Confirmed => GetBlockCommitmentLevel::Confirmed,
                CommitmentLevel::Finalized => GetBlockCommitmentLevel::Finalized,
            });
        set_default(default_block_commitment_level, &mut params.commitment);
        params
    }
}

pub type GetBlockRequestBuilder<R> = RequestBuilder<
    R,
    RpcConfig,
    GetBlockParams,
    MultiRpcResult<Option<ConfirmedBlock>>,
    MultiRpcResult<Option<UiConfirmedBlock>>,
>;

impl<R> DefaultRequestCycles for GetBlockRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        match self.request.params.transaction_details.unwrap_or_default() {
            TransactionDetails::Accounts => 1_000_000_000_000,
            TransactionDetails::Signatures => 100_000_000_000,
            TransactionDetails::None => match self.request.params.rewards {
                Some(true) | None => 20_000_000_000,
                Some(false) => 10_000_000_000,
            },
        }
    }
}

impl<R> GetBlockRequestBuilder<R> {
    /// Change the `commitment` parameter for a `getBlock` request.
    pub fn with_commitment(mut self, commitment_level: impl Into<GetBlockCommitmentLevel>) -> Self {
        self.request.params.commitment = Some(commitment_level.into());
        self
    }

    /// Change the `maxSupportedTransactionVersion` parameter for a `getBlock` request.
    pub fn with_max_supported_transaction_version(mut self, version: u8) -> Self {
        self.request.params.max_supported_transaction_version = Some(version);
        self
    }

    /// Change the `transactionDetails` parameter for a `getBlock` request.
    pub fn with_transaction_details(
        mut self,
        transaction_details: impl Into<TransactionDetails>,
    ) -> Self {
        self.request.params.transaction_details = Some(transaction_details.into());
        self
    }

    /// Change the `rewards` parameter for a `getBlock` request to `false`.
    pub fn without_rewards(mut self) -> Self {
        self.request.params.rewards = Some(false);
        self
    }
}

#[derive(Debug, Clone, Default)]
pub struct GetRecentPrioritizationFeesRequest(GetRecentPrioritizationFeesParams);

impl SolRpcRequest for GetRecentPrioritizationFeesRequest {
    type Config = GetRecentPrioritizationFeesRpcConfig;
    type Params = GetRecentPrioritizationFeesParams;
    type CandidOutput = MultiRpcResult<Vec<PrioritizationFee>>;
    type Output = Self::CandidOutput;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetRecentPrioritizationFees
    }

    fn params(self, _default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        // [getRecentPrioritizationFees](https://solana.com/de/docs/rpc/http/getrecentprioritizationfees)
        // does not use commitment levels
        self.0
    }
}

impl From<GetRecentPrioritizationFeesParams> for GetRecentPrioritizationFeesRequest {
    fn from(value: GetRecentPrioritizationFeesParams) -> Self {
        Self(value)
    }
}

#[derive(Debug, Clone, From)]
pub struct GetSignaturesForAddressRequest(GetSignaturesForAddressParams);

impl SolRpcRequest for GetSignaturesForAddressRequest {
    type Config = RpcConfig;
    type Params = GetSignaturesForAddressParams;
    type CandidOutput = Self::Output;
    type Output = MultiRpcResult<Vec<ConfirmedTransactionStatusWithSignature>>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetSignaturesForAddress
    }

    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        let mut params = self.0;
        set_default(default_commitment_level, &mut params.commitment);
        params
    }
}

pub type GetSignaturesForAddressRequestBuilder<R> = RequestBuilder<
    R,
    RpcConfig,
    GetSignaturesForAddressParams,
    MultiRpcResult<Vec<ConfirmedTransactionStatusWithSignature>>,
    MultiRpcResult<Vec<ConfirmedTransactionStatusWithSignature>>,
>;

impl<R> DefaultRequestCycles for GetSignaturesForAddressRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        2_000_000_000 // TODO XC-338: Check heuristic
    }
}

impl<R> GetSignaturesForAddressRequestBuilder<R> {
    /// Change the `commitment` parameter for a `getSignaturesForAddress` request.
    pub fn with_commitment(mut self, commitment_level: CommitmentLevel) -> Self {
        self.request.params.commitment = Some(commitment_level);
        self
    }

    /// Change the `minContextSlot` parameter for a `getSignaturesForAddress` request.
    pub fn with_min_context_slot(mut self, slot: Slot) -> Self {
        self.request.params.min_context_slot = Some(slot);
        self
    }

    /// Change the `limit` parameter for a `getSignaturesForAddress` request.
    pub fn with_limit(mut self, limit: GetSignaturesForAddressLimit) -> Self {
        self.request.params.limit = Some(limit);
        self
    }

    /// Change the `until` parameter for a `getSignaturesForAddress` request.
    pub fn with_until(mut self, until: impl Into<Signature>) -> Self {
        self.request.params.until = Some(until.into());
        self
    }

    /// Change the `before` parameter for a `getSignaturesForAddress` request.
    pub fn with_before(mut self, before: impl Into<Signature>) -> Self {
        self.request.params.before = Some(before.into());
        self
    }
}

#[derive(Debug, Clone, Default, From)]
pub struct GetSignatureStatusesRequest(GetSignatureStatusesParams);

impl SolRpcRequest for GetSignatureStatusesRequest {
    type Config = RpcConfig;
    type Params = GetSignatureStatusesParams;
    type CandidOutput = MultiRpcResult<Vec<Option<TransactionStatus>>>;
    type Output =
        MultiRpcResult<Vec<Option<solana_transaction_status_client_types::TransactionStatus>>>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetSignatureStatuses
    }

    fn params(self, _default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        self.0
    }
}

pub type GetSignatureStatusesRequestBuilder<R> = RequestBuilder<
    R,
    RpcConfig,
    GetSignatureStatusesParams,
    MultiRpcResult<Vec<Option<TransactionStatus>>>,
    MultiRpcResult<Vec<Option<solana_transaction_status_client_types::TransactionStatus>>>,
>;

impl<R> DefaultRequestCycles for GetSignatureStatusesRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        // TODO XC-338: Check heuristic
        2_000_000_000 + self.request.params.signatures.len() as u128 * 1_000_000
    }
}

impl<R> GetSignatureStatusesRequestBuilder<R> {
    /// Change the `searchTransactionHistory` parameter for a `getSignatureStatuses` request.
    pub fn with_search_transaction_history(mut self, search_transaction_history: bool) -> Self {
        self.request.params.search_transaction_history = Some(search_transaction_history);
        self
    }
}

#[derive(Debug, Clone, Default)]
pub struct GetSlotRequest(Option<GetSlotParams>);

impl SolRpcRequest for GetSlotRequest {
    type Config = GetSlotRpcConfig;
    type Params = Option<GetSlotParams>;
    type CandidOutput = Self::Output;
    type Output = MultiRpcResult<Slot>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetSlot
    }

    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        let mut params = self.0;
        if let Some(slot_params) = params.as_mut() {
            set_default(default_commitment_level, &mut slot_params.commitment);
            return params;
        }
        if let Some(commitment) = default_commitment_level {
            return Some(GetSlotParams {
                commitment: Some(commitment),
                ..Default::default()
            });
        }
        params
    }
}

pub type GetSlotRequestBuilder<R> = RequestBuilder<
    R,
    GetSlotRpcConfig,
    Option<GetSlotParams>,
    MultiRpcResult<Slot>,
    MultiRpcResult<Slot>,
>;

impl<R> DefaultRequestCycles for GetSlotRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        10_000_000_000
    }
}

impl<R> GetSlotRequestBuilder<R> {
    /// Change the `commitment` parameter for a `getSlot` request.
    pub fn with_commitment(mut self, commitment_level: CommitmentLevel) -> Self {
        self.request.params.get_or_insert_default().commitment = Some(commitment_level);
        self
    }

    /// Change the `minContextSlot` parameter for a `getSlot` request.
    pub fn with_min_context_slot(mut self, slot: Slot) -> Self {
        self.request.params.get_or_insert_default().min_context_slot = Some(slot);
        self
    }
}

#[derive(Debug, Clone)]
pub struct GetTokenAccountBalanceRequest(GetTokenAccountBalanceParams);

impl GetTokenAccountBalanceRequest {
    pub fn new(params: GetTokenAccountBalanceParams) -> Self {
        Self(params)
    }
}

impl SolRpcRequest for GetTokenAccountBalanceRequest {
    type Config = RpcConfig;
    type Params = GetTokenAccountBalanceParams;
    type CandidOutput = MultiRpcResult<TokenAmount>;
    type Output = MultiRpcResult<UiTokenAmount>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetTokenAccountBalance
    }

    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        let mut params = self.0;
        set_default(default_commitment_level, &mut params.commitment);
        params
    }
}

pub type GetTokenAccountBalanceRequestBuilder<R> = RequestBuilder<
    R,
    RpcConfig,
    GetTokenAccountBalanceParams,
    MultiRpcResult<TokenAmount>,
    MultiRpcResult<UiTokenAmount>,
>;

impl<R> DefaultRequestCycles for GetTokenAccountBalanceRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        10_000_000_000
    }
}

impl<R> GetTokenAccountBalanceRequestBuilder<R> {
    /// Change the `commitment` parameter for a `getTokenAccountBalance` request.
    pub fn with_commitment(mut self, commitment_level: CommitmentLevel) -> Self {
        self.request.params.commitment = Some(commitment_level);
        self
    }
}

#[derive(Debug, Clone)]
pub struct GetTransactionRequest(GetTransactionParams);

impl GetTransactionRequest {
    pub fn new(params: GetTransactionParams) -> Self {
        Self(params)
    }
}

impl SolRpcRequest for GetTransactionRequest {
    type Config = RpcConfig;
    type Params = GetTransactionParams;
    type CandidOutput = MultiRpcResult<Option<EncodedConfirmedTransactionWithStatusMeta>>;
    type Output = MultiRpcResult<
        Option<solana_transaction_status_client_types::EncodedConfirmedTransactionWithStatusMeta>,
    >;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::GetTransaction
    }

    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        let mut params = self.0;
        set_default(default_commitment_level, &mut params.commitment);
        params
    }
}

pub type GetTransactionRequestBuilder<R> = RequestBuilder<
    R,
    RpcConfig,
    GetTransactionParams,
    MultiRpcResult<Option<EncodedConfirmedTransactionWithStatusMeta>>,
    MultiRpcResult<
        Option<solana_transaction_status_client_types::EncodedConfirmedTransactionWithStatusMeta>,
    >,
>;

impl<R> DefaultRequestCycles for GetTransactionRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        10_000_000_000
    }
}

impl<R> GetTransactionRequestBuilder<R> {
    /// Change the `commitment` parameter for a `getTransaction` request.
    pub fn with_commitment(mut self, commitment_level: CommitmentLevel) -> Self {
        self.request.params.commitment = Some(commitment_level);
        self
    }

    /// Change the `maxSupportedTransaction_version` parameter for a `getTransaction` request.
    pub fn with_max_supported_transaction_version(mut self, version: u8) -> Self {
        self.request.params.max_supported_transaction_version = Some(version);
        self
    }

    /// Change the `encoding` parameter for a `getTransaction` request.
    pub fn with_encoding(mut self, encoding: GetTransactionEncoding) -> Self {
        self.request.params.encoding = Some(encoding);
        self
    }
}

#[derive(Debug, Clone)]
pub struct SendTransactionRequest(SendTransactionParams);

impl SendTransactionRequest {
    pub fn new(params: SendTransactionParams) -> Self {
        Self(params)
    }
}

impl SolRpcRequest for SendTransactionRequest {
    type Config = RpcConfig;
    type Params = SendTransactionParams;
    type CandidOutput = MultiRpcResult<Signature>;
    type Output = MultiRpcResult<solana_signature::Signature>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::SendTransaction
    }

    fn params(self, default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        let mut params = self.0;
        set_default(default_commitment_level, &mut params.preflight_commitment);
        params
    }
}

pub type SendTransactionRequestBuilder<R> = RequestBuilder<
    R,
    RpcConfig,
    SendTransactionParams,
    MultiRpcResult<Signature>,
    MultiRpcResult<solana_signature::Signature>,
>;

impl<R> DefaultRequestCycles for SendTransactionRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        10_000_000_000
    }
}

impl<R> SendTransactionRequestBuilder<R> {
    /// Change the `skipPreflight` parameter for a `sendTransaction` request.
    pub fn with_skip_preflight(mut self, skip_preflight: bool) -> Self {
        self.request.params.skip_preflight = Some(skip_preflight);
        self
    }

    /// Change the `preflightCommitment` parameter for a `sendTransaction` request.
    pub fn with_preflight_commitment(mut self, preflight_commitment: CommitmentLevel) -> Self {
        self.request.params.preflight_commitment = Some(preflight_commitment);
        self
    }

    /// Change the `maxRetries` parameter for a `sendTransaction` request.
    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
        self.request.params.max_retries = Some(max_retries);
        self
    }

    /// Change the `minContextSlot` parameter for a `sendTransaction` request.
    pub fn with_min_context_slot(mut self, slot: Slot) -> Self {
        self.request.params.min_context_slot = Some(slot);
        self
    }
}

pub struct JsonRequest(String);

impl TryFrom<serde_json::Value> for JsonRequest {
    type Error = String;

    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        serde_json::to_string(&value)
            .map(JsonRequest)
            .map_err(|e| e.to_string())
    }
}

impl SolRpcRequest for JsonRequest {
    type Config = RpcConfig;
    type Params = String;
    type CandidOutput = MultiRpcResult<String>;
    type Output = MultiRpcResult<String>;

    fn endpoint(&self) -> SolRpcEndpoint {
        SolRpcEndpoint::JsonRequest
    }

    fn params(self, _default_commitment_level: Option<CommitmentLevel>) -> Self::Params {
        self.0
    }
}

pub type JsonRequestBuilder<R> =
    RequestBuilder<R, RpcConfig, String, MultiRpcResult<String>, MultiRpcResult<String>>;

impl<R> DefaultRequestCycles for JsonRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        10_000_000_000
    }
}

/// A builder to construct a [`Request`].
///
/// To construct a [`RequestBuilder`], refer to the [`SolRpcClient`] documentation.
#[must_use = "RequestBuilder does nothing until you 'send' it"]
pub struct RequestBuilder<Runtime, Config, Params, CandidOutput, Output> {
    client: SolRpcClient<Runtime>,
    request: Request<Config, Params, CandidOutput, Output>,
}

pub type GetRecentPrioritizationFeesRequestBuilder<R> = RequestBuilder<
    R,
    GetRecentPrioritizationFeesRpcConfig,
    GetRecentPrioritizationFeesParams,
    MultiRpcResult<Vec<PrioritizationFee>>,
    MultiRpcResult<Vec<PrioritizationFee>>,
>;

impl<R> DefaultRequestCycles for GetRecentPrioritizationFeesRequestBuilder<R> {
    fn default_request_cycles(&self) -> u128 {
        10_000_000_000
    }
}

impl<Runtime, Config: Clone, Params: Clone, CandidOutput, Output> Clone
    for RequestBuilder<Runtime, Config, Params, CandidOutput, Output>
{
    fn clone(&self) -> Self {
        Self {
            client: self.client.clone(),
            request: self.request.clone(),
        }
    }
}

impl<Runtime: Debug, Config: Debug, Params: Debug, CandidOutput, Output> Debug
    for RequestBuilder<Runtime, Config, Params, CandidOutput, Output>
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let RequestBuilder { client, request } = &self;
        f.debug_struct("RequestBuilder")
            .field("client", client)
            .field("request", request)
            .finish()
    }
}

impl<Runtime, Config, Params, CandidOutput, Output>
    RequestBuilder<Runtime, Config, Params, CandidOutput, Output>
{
    pub(super) fn new<RpcRequest>(client: SolRpcClient<Runtime>, rpc_request: RpcRequest) -> Self
    where
        RpcRequest: SolRpcRequest<
            Config = Config,
            Params = Params,
            CandidOutput = CandidOutput,
            Output = Output,
        >,
        Config: From<RpcConfig>,
    {
        let endpoint = rpc_request.endpoint();
        let params = rpc_request.params(client.config.default_commitment_level.clone());
        let request = Request {
            endpoint,
            rpc_sources: client.config.rpc_sources.clone(),
            rpc_config: client.config.rpc_config.clone().map(Config::from),
            params,
            cycles: None,
            _candid_marker: Default::default(),
            _output_marker: Default::default(),
        };
        RequestBuilder::<Runtime, Config, Params, CandidOutput, Output> { client, request }
    }

    /// Query the cycles cost for that request
    pub fn request_cost(self) -> RequestCostBuilder<Runtime, Config, Params> {
        RequestCostBuilder {
            client: self.client,
            request: RequestCost {
                endpoint: self.request.endpoint,
                rpc_sources: self.request.rpc_sources,
                rpc_config: self.request.rpc_config,
                params: self.request.params,
                cycles: None,
                _candid_marker: Default::default(),
                _output_marker: Default::default(),
            },
        }
    }

    /// Change the amount of cycles to send for that request.
    pub fn with_cycles(mut self, cycles: u128) -> Self {
        *self.request.cycles_mut() = Some(cycles);
        self
    }

    /// Change the parameters to send for that request.
    pub fn with_params(mut self, params: impl Into<Params>) -> Self {
        *self.request.params_mut() = params.into();
        self
    }

    /// Modify current parameters to send for that request.
    pub fn modify_params<F>(mut self, mutator: F) -> Self
    where
        F: FnOnce(&mut Params),
    {
        mutator(self.request.params_mut());
        self
    }

    /// Change the RPC configuration to use for that request.
    pub fn with_rpc_config(mut self, rpc_config: impl Into<Config>) -> Self {
        *self.request.rpc_config_mut() = Some(rpc_config.into());
        self
    }
}

/// Common behavior for the RPC config for SOL RPC canister endpoints.
pub trait SolRpcConfig {
    /// Return a new RPC config with the given response size estimate.
    fn with_response_size_estimate(self, response_size_estimate: u64) -> Self;

    /// Return a new RPC config with the given response consensys.
    fn with_response_consensus(self, response_consensus: ConsensusStrategy) -> Self;
}

impl SolRpcConfig for RpcConfig {
    fn with_response_size_estimate(self, response_size_estimate: u64) -> Self {
        Self {
            response_size_estimate: Some(response_size_estimate),
            ..self
        }
    }

    fn with_response_consensus(self, response_consensus: ConsensusStrategy) -> Self {
        Self {
            response_consensus: Some(response_consensus),
            ..self
        }
    }
}

impl SolRpcConfig for GetSlotRpcConfig {
    fn with_response_size_estimate(self, response_size_estimate: u64) -> Self {
        Self {
            response_size_estimate: Some(response_size_estimate),
            ..self
        }
    }

    fn with_response_consensus(self, response_consensus: ConsensusStrategy) -> Self {
        Self {
            response_consensus: Some(response_consensus),
            ..self
        }
    }
}

impl SolRpcConfig for GetRecentPrioritizationFeesRpcConfig {
    fn with_response_size_estimate(mut self, response_size_estimate: u64) -> Self {
        self.set_response_size_estimate(response_size_estimate);
        self
    }

    fn with_response_consensus(mut self, response_consensus: ConsensusStrategy) -> Self {
        self.set_response_consensus(response_consensus);
        self
    }
}

impl<Runtime, Config: SolRpcConfig + Default, Params, CandidOutput, Output>
    RequestBuilder<Runtime, Config, Params, CandidOutput, Output>
{
    /// Change the response size estimate to use for that request.
    pub fn with_response_size_estimate(mut self, response_size_estimate: u64) -> Self {
        self.request.rpc_config = Some(
            self.request
                .rpc_config
                .unwrap_or_default()
                .with_response_size_estimate(response_size_estimate),
        );
        self
    }

    /// Change the consensus strategy to use for that request.
    pub fn with_response_consensus(mut self, response_consensus: ConsensusStrategy) -> Self {
        self.request.rpc_config = Some(
            self.request
                .rpc_config
                .unwrap_or_default()
                .with_response_consensus(response_consensus),
        );
        self
    }
}

impl<R: Runtime, Config, Params, CandidOutput, Output>
    RequestBuilder<R, Config, Params, CandidOutput, Output>
{
    /// Constructs the [`Request`] and sends it using the [`SolRpcClient`] returning the response.
    ///
    /// # Panics
    ///
    /// If the request was not successful.
    pub async fn send(self) -> Output
    where
        Config: CandidType + Send,
        Params: CandidType + Send,
        CandidOutput: Into<Output> + CandidType + DeserializeOwned,
        RequestBuilder<R, Config, Params, CandidOutput, Output>: DefaultRequestCycles,
    {
        let rpc_method = self.request.endpoint.rpc_method();
        self.try_send()
            .await
            .unwrap_or_else(|e| panic!("Client error: failed to call `{}`: {e:?}", rpc_method))
    }

    /// Constructs the [`Request`] and sends it using the [`SolRpcClient`]. This method returns
    /// either the request response or any error that occurs while sending the request.
    pub async fn try_send(self) -> Result<Output, IcError>
    where
        Config: CandidType + Send,
        Params: CandidType + Send,
        CandidOutput: Into<Output> + CandidType + DeserializeOwned,
        RequestBuilder<R, Config, Params, CandidOutput, Output>: DefaultRequestCycles,
    {
        let cycles = self
            .request
            .cycles
            .unwrap_or_else(|| self.default_request_cycles());
        self.client
            .try_execute_request::<Config, Params, CandidOutput, Output>(self.request, cycles)
            .await
    }
}

impl<Runtime, Params, CandidOutput, Output>
    RequestBuilder<Runtime, GetRecentPrioritizationFeesRpcConfig, Params, CandidOutput, Output>
{
    /// Change the rounding error for the maximum slot value for a `getRecentPrioritizationFees` request.
    pub fn with_max_slot_rounding_error<T: Into<RoundingError>>(
        mut self,
        rounding_error: T,
    ) -> Self {
        let config = self.request.rpc_config_mut().get_or_insert_default();
        config.max_slot_rounding_error = Some(rounding_error.into());
        self
    }

    /// Change the maximum number of entries for a `getRecentPrioritizationFees` response.
    pub fn with_max_length<T: Into<NonZeroU8>>(mut self, len: T) -> Self {
        let config = self.request.rpc_config_mut().get_or_insert_default();
        config.set_max_length(len.into());
        self
    }
}

impl<Runtime, Params, CandidOutput, Output>
    RequestBuilder<Runtime, GetSlotRpcConfig, Params, CandidOutput, Output>
{
    /// Change the rounding error for `getSlot` request.
    pub fn with_rounding_error<T: Into<RoundingError>>(mut self, rounding_error: T) -> Self {
        let config = self.request.rpc_config_mut().get_or_insert_default();
        config.rounding_error = Some(rounding_error.into());
        self
    }
}

/// A request which can be executed with `SolRpcClient::execute_request` or `SolRpcClient::execute_query_request`.
pub struct Request<Config, Params, CandidOutput, Output> {
    pub(super) endpoint: SolRpcEndpoint,
    pub(super) rpc_sources: RpcSources,
    pub(super) rpc_config: Option<Config>,
    pub(super) params: Params,
    pub(super) cycles: Option<u128>,
    pub(super) _candid_marker: std::marker::PhantomData<CandidOutput>,
    pub(super) _output_marker: std::marker::PhantomData<Output>,
}

impl<Config: Debug, Params: Debug, CandidOutput, Output> Debug
    for Request<Config, Params, CandidOutput, Output>
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let Request {
            endpoint,
            rpc_sources,
            rpc_config,
            params,
            cycles,
            _candid_marker,
            _output_marker,
        } = &self;
        f.debug_struct("Request")
            .field("endpoint", endpoint)
            .field("rpc_sources", rpc_sources)
            .field("rpc_config", rpc_config)
            .field("params", params)
            .field("cycles", cycles)
            .field("_candid_marker", _candid_marker)
            .field("_output_marker", _output_marker)
            .finish()
    }
}

impl<Config: PartialEq, Params: PartialEq, CandidOutput, Output> PartialEq
    for Request<Config, Params, CandidOutput, Output>
{
    fn eq(
        &self,
        Request {
            endpoint,
            rpc_sources,
            rpc_config,
            params,
            cycles,
            _candid_marker,
            _output_marker,
        }: &Self,
    ) -> bool {
        &self.endpoint == endpoint
            && &self.rpc_sources == rpc_sources
            && &self.rpc_config == rpc_config
            && &self.params == params
            && &self.cycles == cycles
            && &self._candid_marker == _candid_marker
            && &self._output_marker == _output_marker
    }
}

impl<Config: Clone, Params: Clone, CandidOutput, Output> Clone
    for Request<Config, Params, CandidOutput, Output>
{
    fn clone(&self) -> Self {
        Self {
            endpoint: self.endpoint.clone(),
            rpc_sources: self.rpc_sources.clone(),
            rpc_config: self.rpc_config.clone(),
            params: self.params.clone(),
            cycles: self.cycles,
            _candid_marker: self._candid_marker,
            _output_marker: self._output_marker,
        }
    }
}

impl<Config, Params, CandidOutput, Output> Request<Config, Params, CandidOutput, Output> {
    /// Get a mutable reference to the cycles.
    #[inline]
    pub fn cycles_mut(&mut self) -> &mut Option<u128> {
        &mut self.cycles
    }

    /// Get a mutable reference to the RPC configuration.
    #[inline]
    pub fn rpc_config_mut(&mut self) -> &mut Option<Config> {
        &mut self.rpc_config
    }

    /// Get a mutable reference to the request parameters.
    #[inline]
    pub fn params_mut(&mut self) -> &mut Params {
        &mut self.params
    }
}

pub type RequestCost<Config, Params> = Request<Config, Params, RpcResult<u128>, RpcResult<u128>>;

#[must_use = "RequestCostBuilder does nothing until you 'send' it"]
pub struct RequestCostBuilder<Runtime, Config, Params> {
    client: SolRpcClient<Runtime>,
    request: RequestCost<Config, Params>,
}

impl<R: Runtime, Config, Params> RequestCostBuilder<R, Config, Params> {
    /// Constructs the [`Request`] and send it using the [`SolRpcClient`].
    pub async fn send(self) -> RpcResult<u128>
    where
        Config: CandidType + Send,
        Params: CandidType + Send,
    {
        self.client.execute_cycles_cost_request(self.request).await
    }
}

fn set_default<T>(default_value: Option<T>, value: &mut Option<T>) {
    if value.is_none() {
        if let Some(default) = default_value {
            *value = Some(default);
        }
    }
}

/// An error that occurred while trying to fetch a recent block.
/// See [`SolRpcClient::get_recent_block`]
#[derive(Debug, Clone, PartialEq, Error)]
pub enum GetRecentBlockError {
    /// The results from the different providers were not consistent for a `getSlot` call.
    #[error("Inconsistent result while fetching slot: {0:?}")]
    GetSlotConsensusError(Vec<(RpcSource, RpcResult<Slot>)>),
    /// The results from the different providers were not consistent for a `getBlock` call.
    #[error("Inconsistent result while fetching block: {0:?}")]
    GetBlockConsensusError(Vec<(RpcSource, RpcResult<Option<UiConfirmedBlock>>)>),
    /// An error occurred during a `getSlot` call.
    #[error("Error while fetching slot: {0}")]
    GetSlotRpcError(RpcError),
    /// An error occurred during a `getBlock` call.
    #[error("Error while fetching block: {0}")]
    GetBlockRpcError(RpcError),
    /// There was no matching block for the fetched slot.
    #[error("No block for slot: {0}")]
    MissingBlock(Slot),
    /// An IC error occurred while making the request.
    #[error("IC error: {0}")]
    IcError(IcError),
}

type GetRecentBlockResult<T> = Result<T, GetRecentBlockError>;

/// A builder to build a request to fetch a recent block.
/// See [`SolRpcClient::get_recent_block`].
#[must_use = "GetRecentBlockRequestBuilder does nothing until you 'send' it"]
pub struct GetRecentBlockRequestBuilder<R> {
    client: SolRpcClient<R>,
    num_tries: NonZeroUsize,
    rounding_error: Option<RoundingError>,
    rpc_config: Option<RpcConfig>,
}

impl<R> GetRecentBlockRequestBuilder<R> {
    /// Create a new [`GetRecentBlockRequestBuilder`] request with the given [`SolRpcClient`]
    /// and default parameters.
    ///
    /// The maximum number of attempts that will be performed to retrieve a recent block is set to 3.
    pub fn new(client: SolRpcClient<R>) -> Self {
        Self {
            client,
            num_tries: NonZeroUsize::new(3).unwrap(),
            rounding_error: None,
            rpc_config: None,
        }
    }

    /// Sets the maximum number of attempts that will be performed to retrieve a recent block.
    ///
    /// Each attempt consists of at most one `getSlot` and one `getBlock` call, such that the
    /// maximum number of RPC calls performed is `2 * num_tries`.
    pub fn with_num_tries(mut self, num_tries: NonZeroUsize) -> Self {
        self.num_tries = num_tries;
        self
    }

    /// Sets an [`RpcConfig`] for the `getSlot` and `getBlock` calls. If not set, the default
    /// client [`RpcConfig`] is used.
    pub fn with_rpc_config(mut self, rpc_config: RpcConfig) -> Self {
        self.rpc_config = Some(rpc_config);
        self
    }

    /// Sets a [`RoundingError`] for the `getSlot` calls. If not set, the default value for the
    /// rounding error is used.
    pub fn with_get_slot_rounding_error(mut self, rounding_error: RoundingError) -> Self {
        self.rounding_error = Some(rounding_error);
        self
    }
}

impl<R: Runtime> GetRecentBlockRequestBuilder<R> {
    /// Constructs the required [`getSlot`] and [`getBlock`] requests and tries to fetch
    /// a recent block using the [`SolRpcClient`], possibly with re-tries (see the
    /// [`get_recent_block`] method).
    ///
    /// [`getSlot`]: https://solana.com/docs/rpc/http/getslot
    /// [`getBlock`]: https://solana.com/docs/rpc/http/getblock
    /// [`get_recent_block`]: SolRpcClient::get_recent_block
    pub async fn try_send(self) -> Result<(Slot, UiConfirmedBlock), Vec<GetRecentBlockError>> {
        let mut errors = Vec::with_capacity(self.num_tries.into());
        while errors.len() < usize::from(self.num_tries) {
            match self.get_slot_then_get_block().await {
                Ok(result) => return Ok(result),
                Err(error) => errors.push(error),
            }
        }
        Err(errors)
    }

    async fn get_slot_then_get_block(&self) -> GetRecentBlockResult<(Slot, UiConfirmedBlock)> {
        let slot = self.get_slot().await?;
        let block = self.get_block(slot).await?;
        Ok((slot, block))
    }

    async fn get_slot(&self) -> GetRecentBlockResult<Slot> {
        let mut request = self.client.get_slot();
        if let Some(rpc_config) = self.rpc_config.as_ref() {
            request = request.with_rpc_config(rpc_config.clone());
        }
        if let Some(rounding_error) = self.rounding_error {
            request = request.with_rounding_error(rounding_error);
        }
        match request.try_send().await {
            Ok(MultiRpcResult::Consistent(Ok(slot))) => Ok(slot),
            Ok(MultiRpcResult::Consistent(Err(e))) => Err(GetRecentBlockError::GetSlotRpcError(e)),
            Ok(MultiRpcResult::Inconsistent(results)) => {
                Err(GetRecentBlockError::GetSlotConsensusError(results))
            }
            Err(e) => Err(GetRecentBlockError::IcError(e)),
        }
    }

    async fn get_block(&self, slot: Slot) -> GetRecentBlockResult<UiConfirmedBlock> {
        let mut request = self
            .client
            .get_block(slot)
            .with_transaction_details(TransactionDetails::None)
            .with_max_supported_transaction_version(0)
            .without_rewards();
        if let Some(rpc_config) = self.rpc_config.as_ref() {
            request = request.with_rpc_config(rpc_config.clone());
        }
        match request.try_send().await {
            Ok(MultiRpcResult::Consistent(Ok(Some(block)))) => Ok(block),
            Ok(MultiRpcResult::Consistent(Ok(None))) => {
                Err(GetRecentBlockError::MissingBlock(slot))
            }
            Ok(MultiRpcResult::Consistent(Err(e))) => Err(GetRecentBlockError::GetBlockRpcError(e)),
            Ok(MultiRpcResult::Inconsistent(results)) => {
                Err(GetRecentBlockError::GetBlockConsensusError(results))
            }
            Err(e) => Err(GetRecentBlockError::IcError(e)),
        }
    }
}