subxt 0.50.0

Interact with Substrate based chains on the Polkadot Network
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
// Copyright 2019-2026 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.

//! Types representing the errors that can be returned.

mod dispatch_error;
mod hex;

use std::borrow::Cow;
use thiserror::Error as DeriveError;

#[cfg(feature = "light-client")]
pub use subxt_lightclient::LightClientError;

// Re-export dispatch error types:
pub use dispatch_error::{
    ArithmeticError, DispatchError, ModuleError, TokenError, TransactionalError,
};

// Re-expose the errors we use from other crates here:
pub use hex::Hex;
pub use scale_decode::Error as DecodeError;
pub use scale_encode::Error as EncodeError;
pub use subxt_metadata::Metadata;
pub use subxt_metadata::TryFromError as MetadataTryFromError;

/// A global error type. Any of the errors exposed here can convert into this
/// error via `.into()`, but this error isn't itself exposed from anything.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum Error {
    #[error(transparent)]
    OnlineClientError(#[from] OnlineClientError),
    #[error(transparent)]
    OfflineClientAtBlockError(#[from] OfflineClientAtBlockError),
    #[error(transparent)]
    OnlineClientAtBlockError(#[from] OnlineClientAtBlockError),
    #[error(transparent)]
    ExtrinsicDecodeErrorAt(#[from] ExtrinsicDecodeErrorAt),
    #[error(transparent)]
    BlockError(#[from] BlockError),
    #[error(transparent)]
    ConstantError(#[from] ConstantError),
    #[error(transparent)]
    CustomValueError(#[from] CustomValueError),
    #[error(transparent)]
    StorageKeyError(#[from] StorageKeyError),
    #[error(transparent)]
    StorageValueError(#[from] StorageValueError),
    #[error(transparent)]
    BackendError(#[from] BackendError),
    #[error(transparent)]
    BlocksError(#[from] BlocksError),
    #[error(transparent)]
    AccountNonceError(#[from] AccountNonceError),
    #[error(transparent)]
    RuntimeApiError(#[from] RuntimeApiError),
    #[error(transparent)]
    EventsError(#[from] EventsError),
    #[error(transparent)]
    ExtrinsicError(#[from] ExtrinsicError),
    #[error(transparent)]
    ViewFunctionError(#[from] ViewFunctionError),
    #[error(transparent)]
    TransactionProgressError(#[from] TransactionProgressError),
    #[error(transparent)]
    TransactionStatusError(#[from] TransactionStatusError),
    #[error(transparent)]
    TransactionEventsError(#[from] TransactionEventsError),
    #[error(transparent)]
    TransactionFinalizedSuccessError(#[from] TransactionFinalizedSuccessError),
    #[error(transparent)]
    ModuleErrorDetailsError(#[from] ModuleErrorDetailsError),
    #[error(transparent)]
    ModuleErrorDecodeError(#[from] ModuleErrorDecodeError),
    #[error(transparent)]
    DispatchErrorDecodeError(#[from] DispatchErrorDecodeError),
    #[error(transparent)]
    StorageError(#[from] StorageError),
    #[error(transparent)]
    CombinedBackendError(#[from] CombinedBackendError),
    // Dev note: Subxt doesn't directly return Raw* errors. These exist so that when
    // users use common crates (like parity-scale-codec and subxt-rpcs), errors returned
    // there can be handled automatically using ? when the expected error is subxt::Error.
    #[error("Other RPC client error: {0}")]
    OtherRpcClientError(#[from] subxt_rpcs::Error),
    #[error("Other codec error: {0}")]
    OtherCodecError(#[from] codec::Error),
    #[cfg(feature = "light-client")]
    #[error("Other light client error: {0}")]
    OtherLightClientError(#[from] subxt_lightclient::LightClientError),
    #[cfg(feature = "light-client")]
    #[error("Other light client RPC error: {0}")]
    OtherLightClientRpcError(#[from] subxt_lightclient::LightClientRpcError),
    // Dev note: Nothing in subxt should ever emit this error. It can instead be used
    // to easily map other errors into a subxt::Error for convenience. Some From impls
    // make this automatic for common "other" error types.
    #[error("Other error: {0}")]
    Other(Box<dyn std::error::Error + Send + Sync + 'static>),
}

impl From<std::convert::Infallible> for Error {
    fn from(value: std::convert::Infallible) -> Self {
        match value {}
    }
}

impl Error {
    /// Create a generic error. This is a quick workaround when you are using
    /// [`Error`] and have a non-Subxt error to return.
    pub fn other<E: std::error::Error + Send + Sync + 'static>(error: E) -> Error {
        Error::Other(Box::new(error))
    }

    /// Create a generic error from a string. This is a quick workaround when you are using
    /// [`Error`] and have a non-Subxt error to return.
    pub fn other_str(error: impl Into<String>) -> Error {
        #[derive(thiserror::Error, Debug, Clone)]
        #[error("{0}")]
        struct StrError(String);
        Error::Other(Box::new(StrError(error.into())))
    }

    /// Checks whether the error was caused by a RPC re-connection.
    pub fn is_disconnected_will_reconnect(&self) -> bool {
        matches!(
            self.backend_error(),
            Some(BackendError::Rpc(RpcError::ClientError(
                subxt_rpcs::Error::DisconnectedWillReconnect(_)
            )))
        )
    }

    /// Checks whether the error was caused by a RPC request being rejected.
    pub fn is_rpc_limit_reached(&self) -> bool {
        matches!(
            self.backend_error(),
            Some(BackendError::Rpc(RpcError::LimitReached))
        )
    }

    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            // Many of these contain no backend error, but keep the checks next to
            // the actual error types to make it harder to miss adding any, and be exhaustive
            // here so new error variants are not missed as easily.
            Error::BlocksError(e) => e.backend_error(),
            Error::AccountNonceError(e) => e.backend_error(),
            Error::OnlineClientError(e) => e.backend_error(),
            Error::RuntimeApiError(e) => e.backend_error(),
            Error::EventsError(e) => e.backend_error(),
            Error::BlockError(e) => e.backend_error(),
            Error::ExtrinsicError(e) => e.backend_error(),
            Error::ViewFunctionError(e) => e.backend_error(),
            Error::TransactionProgressError(e) => e.backend_error(),
            Error::TransactionEventsError(e) => e.backend_error(),
            Error::TransactionFinalizedSuccessError(e) => e.backend_error(),
            Error::StorageError(e) => e.backend_error(),
            Error::OfflineClientAtBlockError(e) => e.backend_error(),
            Error::OnlineClientAtBlockError(e) => e.backend_error(),
            Error::ExtrinsicDecodeErrorAt(e) => e.backend_error(),
            Error::ConstantError(e) => e.backend_error(),
            Error::CustomValueError(e) => e.backend_error(),
            Error::StorageKeyError(e) => e.backend_error(),
            Error::StorageValueError(e) => e.backend_error(),
            Error::TransactionStatusError(e) => e.backend_error(),
            Error::ModuleErrorDetailsError(e) => e.backend_error(),
            Error::ModuleErrorDecodeError(e) => e.backend_error(),
            Error::DispatchErrorDecodeError(e) => e.backend_error(),
            Error::CombinedBackendError(e) => e.backend_error(),
            #[cfg(feature = "light-client")]
            Error::OtherLightClientError(_) => None,
            #[cfg(feature = "light-client")]
            Error::OtherLightClientRpcError(_) => None,
            // BackendError is always a BackendError:
            Error::BackendError(e) => Some(e),
            // Other errors come from different crates so can never contain a BackendError:
            Error::OtherRpcClientError(_) => None,
            Error::OtherCodecError(_) => None,
            Error::Other(_) => None,
        }
    }
}

/// Errors constructing an offline client at a specific block number.
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum OfflineClientAtBlockError {
    #[error(
        "Cannot construct OfflineClientAtBlock: spec version not found for block number {block_number}"
    )]
    SpecVersionNotFound {
        /// The block number for which the spec version was not found.
        block_number: u64,
    },
    #[error(
        "Cannot construct OfflineClientAtBlock: metadata not found for spec version {spec_version}"
    )]
    MetadataNotFound {
        /// The spec version for which the metadata was not found.
        spec_version: u32,
    },
}

impl OfflineClientAtBlockError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum OnlineClientError {
    #[error("Cannot construct OnlineClient: {0}")]
    RpcError(#[from] subxt_rpcs::Error),
    #[error("Could not construct the CombinedBackend: {0}")]
    CannotBuildCombinedBackend(CombinedBackendError),
    #[error("Cannot construct OnlineClient: Cannot fetch genesis hash: {0}")]
    CannotGetGenesisHash(BackendError),
}

impl OnlineClientError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            OnlineClientError::CannotGetGenesisHash(e) => Some(e),
            _ => None,
        }
    }
}

/// Errors constructing streams of blocks.
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BlocksError {
    #[error("Cannot construct block stream: cannot get the current block: {0}")]
    CannotGetCurrentBlock(OnlineClientAtBlockError),
    #[error("Cannot construct block stream: cannot get block header stream: {0}")]
    CannotGetBlockHeaderStream(BackendError),
    #[error("Error streaming blocks: cannot get the next block header: {0}")]
    CannotGetBlockHeader(BackendError),
}

impl BlocksError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            BlocksError::CannotGetCurrentBlock(e) => e.backend_error(),
            BlocksError::CannotGetBlockHeaderStream(e) => Some(e),
            BlocksError::CannotGetBlockHeader(e) => Some(e),
        }
    }
}

/// Errors constructing an online client at a specific block number.
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum OnlineClientAtBlockError {
    #[error("Cannot construct OnlineClientAtBlock: cannot get the current block: {reason}")]
    CannotGetCurrentBlock {
        /// The error we encountered.
        reason: BackendError,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: failed to get block hash from node for block {block_number}: {reason}"
    )]
    CannotGetBlockHash {
        /// Block number we failed to get the hash for.
        block_number: u64,
        /// The error we encountered.
        reason: BackendError,
    },
    #[error("Cannot construct OnlineClientAtBlock: block number {block_number} not found")]
    BlockNotFound {
        /// The block number for which a block was not found.
        block_number: u64,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: cannot get the block header for block {block_hash}: {reason}"
    )]
    CannotGetBlockHeader {
        /// Block hash that we failed to fetch the header for.
        block_hash: Hex,
        /// The error we encountered.
        reason: BackendError,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: cannot find the block header for block {block_hash}"
    )]
    BlockHeaderNotFound {
        /// Block hash that we failed to find the header for.
        block_hash: Hex,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: failed to obtain spec version for block {block_hash}: {reason}"
    )]
    CannotGetSpecVersion {
        /// The block hash for which we failed to obtain the spec version.
        block_hash: Hex,
        /// The error we encountered.
        reason: BackendError,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: failed to decode spec version for block {block_hash}: {reason}"
    )]
    CannotDecodeSpecVersion {
        /// The block hash for which we failed to decode the spec version.
        block_hash: Hex,
        /// The error we encountered.
        reason: codec::Error,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: failed to get metadata for block {block_hash}: {reason}"
    )]
    CannotGetMetadata {
        /// The block hash for which we failed to get the metadata.
        block_hash: Hex,
        /// The error we encountered.
        reason: String,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: Metadata V{version} (required at block {block_hash} is not supported."
    )]
    UnsupportedMetadataVersion {
        /// The block hash that requires the unsupported version.
        block_hash: Hex,
        /// The unsupported metadata version.
        version: u32,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: No legacy types were provided but we're trying to access a block that requires them."
    )]
    MissingLegacyTypes,
    #[error(
        "Cannot construct OnlineClientAtBlock: unable to convert legacy metadata (required at block {block_hash}): {reason}"
    )]
    CannotConvertLegacyMetadata {
        /// The block hash that requires legacy types.
        block_hash: Hex,
        /// The metadata version.
        metadata_version: u32,
        /// Reason the conversion failed.
        reason: subxt_metadata::LegacyFromError,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: unable to convert modern metadata (required at block {block_hash}): {reason}"
    )]
    CannotConvertModernMetadata {
        /// The block hash that requires legacy types.
        block_hash: Hex,
        /// The metadata version.
        metadata_version: u32,
        /// Reason the conversion failed.
        reason: subxt_metadata::TryFromError,
    },
    #[error(
        "Cannot construct OnlineClientAtBlock: cannot inject types from metadata: failure to parse a type found in the metadata: {parse_error}"
    )]
    CannotInjectMetadataTypes {
        /// Error parsing a type found in the metadata.
        parse_error: scale_info_legacy::lookup_name::ParseError,
    },
}

impl OnlineClientAtBlockError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            OnlineClientAtBlockError::CannotGetCurrentBlock { reason }
            | OnlineClientAtBlockError::CannotGetBlockHash { reason, .. }
            | OnlineClientAtBlockError::CannotGetBlockHeader { reason, .. }
            | OnlineClientAtBlockError::CannotGetSpecVersion { reason, .. } => Some(reason),
            _ => None,
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum BlockError {
    #[error("Could not find the block with hash {block_hash}")]
    BlockNotFound { block_hash: Hex },
    #[error("Could not download the block header with hash {block_hash}: {reason}")]
    CouldNotDownloadBlockHeader {
        block_hash: Hex,
        reason: BackendError,
    },
}

impl BlockError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            BlockError::CouldNotDownloadBlockHeader { reason, .. } => Some(reason),
            _ => None,
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum BackendError {
    #[error("Backend error: RPC error: {0}")]
    Rpc(#[from] RpcError),
    // This is for errors in `Backend` implementations which aren't any of the "pre-defined" set above:
    #[error("Custom backend error: {0}")]
    Other(Cow<'static, str>),
}

impl BackendError {
    /// Checks whether the error was caused by a RPC re-connection.
    pub fn is_disconnected_will_reconnect(&self) -> bool {
        matches!(
            self,
            BackendError::Rpc(RpcError::ClientError(
                subxt_rpcs::Error::DisconnectedWillReconnect(_)
            ))
        )
    }

    /// Checks whether the error was caused by a RPC request being rejected.
    pub fn is_rpc_limit_reached(&self) -> bool {
        matches!(self, BackendError::Rpc(RpcError::LimitReached))
    }

    /// Create a [`BackendError::Other`] given a message.
    pub fn other(message: impl Into<Cow<'static, str>>) -> Self {
        BackendError::Other(message.into())
    }
}

impl From<subxt_rpcs::Error> for BackendError {
    fn from(value: subxt_rpcs::Error) -> Self {
        BackendError::Rpc(RpcError::ClientError(value))
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum CombinedBackendError {
    #[error("Could not obtain the list of RPC methods to determine which backends can be used")]
    CouldNotObtainRpcMethodList(subxt_rpcs::Error),
}

impl CombinedBackendError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

/// An RPC error. Since we are generic over the RPC client that is used,
/// the error is boxed and could be casted.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RpcError {
    /// Error related to the RPC client.
    #[error("RPC error: {0}")]
    ClientError(#[from] subxt_rpcs::Error),
    /// This error signals that we got back a [`subxt_rpcs::methods::chain_head::MethodResponse::LimitReached`],
    /// which is not technically an RPC error but is treated as an error in our own APIs.
    #[error("RPC error: limit reached")]
    LimitReached,
    /// The RPC subscription was dropped.
    #[error("RPC error: subscription dropped.")]
    SubscriptionDropped,
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum AccountNonceError {
    #[error("Could not retrieve account nonce: {0}")]
    CouldNotRetrieve(BackendError),
    #[error("Could not decode account nonce: {0}")]
    CouldNotDecode(codec::Error),
    #[error("Wrong number of account nonce bytes returned: {0} (expected 2, 4 or 8)")]
    WrongNumberOfBytes(usize),
}

impl AccountNonceError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            AccountNonceError::CouldNotRetrieve(e) => Some(e),
            _ => None,
        }
    }
}

/// Error working with Runtime APIs
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum RuntimeApiError {
    #[error("The static Runtime API address used is not compatible with the live chain")]
    IncompatibleCodegen,
    #[error("Runtime API trait not found: {0}")]
    TraitNotFound(String),
    #[error("Runtime API method {method_name} not found in trait {trait_name}")]
    MethodNotFound {
        trait_name: String,
        method_name: String,
    },
    #[error("Failed to encode Runtime API inputs: {0}")]
    CouldNotEncodeInputs(frame_decode::runtime_apis::RuntimeApiInputsEncodeError),
    #[error("Failed to decode Runtime API: {0}")]
    CouldNotDecodeResponse(frame_decode::runtime_apis::RuntimeApiDecodeError<u32>),
    #[error("Cannot call the Runtime API: {0}")]
    CannotCallApi(BackendError),
}

impl RuntimeApiError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            RuntimeApiError::CannotCallApi(e) => Some(e),
            _ => None,
        }
    }
}

/// Error working with events.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum EventsError {
    #[error("Can't decode event: can't decode phase: {0}")]
    CannotDecodePhase(codec::Error),
    #[error("Can't decode event: can't decode pallet index: {0}")]
    CannotDecodePalletIndex(codec::Error),
    #[error("Can't decode event: can't decode variant index: {0}")]
    CannotDecodeVariantIndex(codec::Error),
    #[error("Can't decode event: can't find pallet with index {0}")]
    CannotFindPalletWithIndex(u8),
    #[error(
        "Can't decode event: can't find variant with index {variant_index} in pallet {pallet_name}"
    )]
    CannotFindVariantWithIndex {
        pallet_name: String,
        variant_index: u8,
    },
    #[error("Can't decode field {field_name:?} in event {pallet_name}.{event_name}: {reason}")]
    CannotDecodeFieldInEvent {
        pallet_name: String,
        event_name: String,
        field_name: String,
        reason: scale_decode::visitor::DecodeError,
    },
    #[error("Can't decode event topics: {0}")]
    CannotDecodeEventTopics(codec::Error),
    #[error("Can't decode the fields of event {pallet_name}.{event_name}: {reason}")]
    CannotDecodeEventFields {
        pallet_name: String,
        event_name: String,
        reason: scale_decode::Error,
    },
    #[error("Can't decode event {pallet_name}.{event_name} to Event enum: {reason}")]
    CannotDecodeEventEnum {
        pallet_name: String,
        event_name: String,
        reason: scale_decode::Error,
    },
    #[error("Cannot fetch event bytes: {0}")]
    CannotFetchEventBytes(BackendError),
}

impl EventsError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            EventsError::CannotFetchEventBytes(e) => Some(e),
            _ => None,
        }
    }
}

/// Error working with extrinsics.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum ExtrinsicError {
    #[error("Failed to construct extrinsic: {0}")]
    EncodeError(#[from] frame_decode::extrinsics::ExtrinsicEncodeError),
    #[error("The extrinsic payload is not compatible with the live chain")]
    IncompatibleCodegen,
    #[error("Can't find extrinsic: pallet with name {0} not found")]
    PalletNameNotFound(String),
    #[error("Can't find extrinsic: call name {call_name} doesn't exist in pallet {pallet_name}")]
    CallNameNotFound {
        pallet_name: String,
        call_name: String,
    },
    #[error("Failed to encode an extrinsic: the genesis hash was not provided")]
    GenesisHashNotProvided,
    #[error("Subxt does not support the extrinsic versions expected by the chain")]
    UnsupportedVersion,
    #[error("Cannot construct the required transaction extensions: {0}")]
    Params(#[from] TransactionExtensionError),
    #[error("Cannot decode transaction extension '{name}': {error}")]
    CouldNotDecodeTransactionExtension {
        /// The extension name.
        name: String,
        /// The decode error.
        error: scale_decode::Error,
    },
    #[error("Failed to decode the fields of an extrinsic at index {extrinsic_index}: {error}")]
    CannotDecodeFields {
        /// Index of the extrinsic whose fields we could not decode
        extrinsic_index: usize,
        /// The decode error.
        error: scale_decode::Error,
    },
    #[error("Failed to decode the extrinsic at index {extrinsic_index} to a root enum: {error}")]
    CannotDecodeIntoRootExtrinsic {
        /// Index of the extrinsic that we failed to decode
        extrinsic_index: usize,
        /// The decode error.
        error: scale_decode::Error,
    },
    #[error("Could not download block body to extract extrinsics from: {0}")]
    CannotGetBlockBody(BackendError),
    #[error("Block not found: {0}")]
    BlockNotFound(Hex),
    #[error("Error getting account nonce at block {block_hash}")]
    AccountNonceError {
        block_hash: Hex,
        account_id: Hex,
        reason: AccountNonceError,
    },
    #[error("Cannot submit extrinsic: {0}")]
    ErrorSubmittingTransaction(BackendError),
    #[error("A transaction status error was returned while submitting the extrinsic: {0}")]
    TransactionStatusError(TransactionStatusError),
    #[error(
        "The transaction status stream encountered an error while submitting the extrinsic: {0}"
    )]
    TransactionStatusStreamError(BackendError),
    #[error(
        "The transaction status stream unexpectedly ended, so we don't know the status of the submitted extrinsic"
    )]
    UnexpectedEndOfTransactionStatusStream,
    #[error("Cannot get fee info from Runtime API: {0}")]
    CannotGetFeeInfo(BackendError),
    #[error("Cannot decode fee info from Runtime API: {0}")]
    CannotDecodeFeeInfo(codec::Error),
    #[error("Cannot get validation info from Runtime API: {0}")]
    CannotGetValidationInfo(BackendError),
    #[error("Cannot decode ValidationResult bytes: {0}")]
    CannotDecodeValidationResult(codec::Error),
    #[error("ValidationResult bytes could not be decoded")]
    UnexpectedValidationResultBytes(Vec<u8>),
}

impl ExtrinsicError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            ExtrinsicError::CannotGetBlockBody(e)
            | ExtrinsicError::ErrorSubmittingTransaction(e)
            | ExtrinsicError::TransactionStatusStreamError(e)
            | ExtrinsicError::CannotGetFeeInfo(e)
            | ExtrinsicError::CannotGetValidationInfo(e) => Some(e),
            ExtrinsicError::AccountNonceError { reason, .. } => reason.backend_error(),
            _ => None,
        }
    }
}

#[derive(Debug, DeriveError)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum CustomValueError {
    #[error("The static custom value address used is not compatible with the live chain")]
    IncompatibleCodegen,
    #[error("The custom value '{0}' was not found")]
    NotFound(String),
    #[error("Failed to decode custom value: {0}")]
    CouldNotDecodeCustomValue(frame_decode::custom_values::CustomValueDecodeError<u32>),
}

impl CustomValueError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

/// Error working with View Functions.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum ViewFunctionError {
    #[error("The static View Function address used is not compatible with the live chain")]
    IncompatibleCodegen,
    #[error("Can't find View Function: pallet {0} not found")]
    PalletNotFound(String),
    #[error("Can't find View Function {function_name} in pallet {pallet_name}")]
    ViewFunctionNotFound {
        pallet_name: String,
        function_name: String,
    },
    #[error("Failed to encode View Function inputs: {0}")]
    CouldNotEncodeInputs(frame_decode::view_functions::ViewFunctionInputsEncodeError),
    #[error("Failed to decode View Function: {0}")]
    CouldNotDecodeResponse(frame_decode::view_functions::ViewFunctionDecodeError<u32>),
    #[error("Cannot call the View Function Runtime API: {0}")]
    CannotCallApi(BackendError),
}

impl ViewFunctionError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            ViewFunctionError::CannotCallApi(e) => Some(e),
            _ => None,
        }
    }
}

/// Error during the transaction progress.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum TransactionProgressError {
    #[error("Cannot get the next transaction progress update: {0}")]
    CannotGetNextProgressUpdate(BackendError),
    #[error("Error during transaction progress: {0}")]
    TransactionStatusError(#[from] TransactionStatusError),
    #[error(
        "The transaction status stream unexpectedly ended, so we have no further transaction progress updates"
    )]
    UnexpectedEndOfTransactionStatusStream,
}

impl TransactionProgressError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            TransactionProgressError::CannotGetNextProgressUpdate(e) => Some(e),
            TransactionProgressError::TransactionStatusError(_) => None,
            TransactionProgressError::UnexpectedEndOfTransactionStatusStream => None,
        }
    }
}

/// An error emitted as the result of a transaction progress update.
#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum TransactionStatusError {
    /// An error happened on the node that the transaction was submitted to.
    #[error("Error handling transaction: {0}")]
    Error(String),
    /// The transaction was deemed invalid.
    #[error("The transaction is not valid: {0}")]
    Invalid(String),
    /// The transaction was dropped.
    #[error("The transaction was dropped: {0}")]
    Dropped(String),
}

impl TransactionStatusError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

/// Error fetching events for a just-submitted transaction
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum TransactionEventsError {
    #[error(
        "The block containing the submitted transaction ({block_hash}) could not be downloaded: {error}"
    )]
    CannotFetchBlockBody {
        block_hash: Hex,
        error: BackendError,
    },
    #[error(
        "Cannot find the the submitted transaction (hash: {transaction_hash}) in the block (hash: {block_hash}) it is supposed to be in."
    )]
    CannotFindTransactionInBlock {
        block_hash: Hex,
        transaction_hash: Hex,
    },
    #[error("The block containing the submitted transaction ({block_hash}) could not be found")]
    BlockNotFound { block_hash: Hex },
    #[error(
        "Could not decode event at index {event_index} for the submitted transaction at block {block_hash}: {error}"
    )]
    CannotDecodeEventInBlock {
        event_index: usize,
        block_hash: Hex,
        error: EventsError,
    },
    #[error("Could not instantiate a client at the required block to fetch events: {0}")]
    CannotInstantiateClientAtBlock(OnlineClientAtBlockError),
    #[error("Could not fetch events for the submitted transaction: {error}")]
    CannotFetchEventsForTransaction {
        block_hash: Hex,
        transaction_hash: Hex,
        error: EventsError,
    },
    #[error("The transaction led to a DispatchError, but we failed to decode it: {error}")]
    CannotDecodeDispatchError {
        error: DispatchErrorDecodeError,
        bytes: Vec<u8>,
    },
    #[error("The transaction failed with the following dispatch error: {0}")]
    ExtrinsicFailed(#[from] DispatchError),
}

impl TransactionEventsError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            TransactionEventsError::CannotFetchBlockBody { error, .. } => Some(error),
            TransactionEventsError::CannotDecodeEventInBlock { error, .. }
            | TransactionEventsError::CannotFetchEventsForTransaction { error, .. } => {
                error.backend_error()
            }
            _ => None,
        }
    }
}

/// Error waiting for the transaction to be finalized and successful.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs, clippy::large_enum_variant)]
pub enum TransactionFinalizedSuccessError {
    #[error("Could not finalize the transaction: {0}")]
    FinalizationError(#[from] TransactionProgressError),
    #[error("The transaction did not succeed: {0}")]
    SuccessError(#[from] TransactionEventsError),
}

impl TransactionFinalizedSuccessError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            TransactionFinalizedSuccessError::FinalizationError(e) => e.backend_error(),
            TransactionFinalizedSuccessError::SuccessError(e) => e.backend_error(),
        }
    }
}

/// Error decoding the [`DispatchError`]
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum ModuleErrorDetailsError {
    #[error(
        "Could not get details for the DispatchError: could not find pallet index {pallet_index}"
    )]
    PalletNotFound { pallet_index: u8 },
    #[error(
        "Could not get details for the DispatchError: could not find error index {error_index} in pallet {pallet_name}"
    )]
    ErrorVariantNotFound {
        pallet_name: String,
        error_index: u8,
    },
}

impl ModuleErrorDetailsError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

/// Error decoding the [`ModuleError`]
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
#[error("Could not decode the DispatchError::Module payload into the given type: {0}")]
pub struct ModuleErrorDecodeError(scale_decode::Error);

impl ModuleErrorDecodeError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

/// Error decoding the [`DispatchError`]
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum DispatchErrorDecodeError {
    #[error(
        "Could not decode the DispatchError: could not find the corresponding type ID in the metadata"
    )]
    DispatchErrorTypeIdNotFound,
    #[error("Could not decode the DispatchError: {0}")]
    CouldNotDecodeDispatchError(scale_decode::Error),
    #[error("Could not decode the DispatchError::Module variant")]
    CouldNotDecodeModuleError {
        /// The bytes corresponding to the Module variant we were unable to decode:
        bytes: Vec<u8>,
    },
}

impl DispatchErrorDecodeError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

/// Error working with storage.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum StorageError {
    #[error("The static storage address used is not compatible with the live chain")]
    IncompatibleCodegen,
    #[error("Can't find storage value: pallet with name {0} not found")]
    PalletNameNotFound(String),
    #[error(
        "Storage entry '{entry_name}' not found in pallet {pallet_name} in the live chain metadata"
    )]
    StorageEntryNotFound {
        pallet_name: String,
        entry_name: String,
    },
    #[error("Cannot obtain storage information from metadata: {0}")]
    StorageInfoError(frame_decode::storage::StorageInfoError<'static>),
    #[error("Cannot encode storage key: {0}")]
    StorageKeyEncodeError(frame_decode::storage::StorageKeyEncodeError),
    #[error("Cannot create a key to iterate over a plain entry")]
    CannotIterPlainEntry {
        pallet_name: String,
        entry_name: String,
    },
    #[error(
        "Wrong number of key parts provided to iterate a storage address. We expected at most {max_expected} key parts but got {got} key parts"
    )]
    WrongNumberOfKeyPartsProvidedForIterating { max_expected: usize, got: usize },
    #[error(
        "Wrong number of key parts provided to fetch a storage address. We expected {expected} key parts but got {got} key parts"
    )]
    WrongNumberOfKeyPartsProvidedForFetching { expected: usize, got: usize },
    #[error(
        "No storage value found at the given address, and no default value to fall back to using."
    )]
    NoValueFound,
    #[error("Cannot fetch the storage value: {0}")]
    CannotFetchValue(BackendError),
    #[error("Cannot iterate storage values: {0}")]
    CannotIterateValues(BackendError),
    #[error("Encountered an error iterating over storage values: {0}")]
    StreamFailure(BackendError),
    #[error("Cannot decode the storage version for a given entry: {0}")]
    CannotDecodeStorageVersion(codec::Error),
}

impl StorageError {
    fn backend_error(&self) -> Option<&BackendError> {
        match self {
            StorageError::CannotFetchValue(e)
            | StorageError::CannotIterateValues(e)
            | StorageError::StreamFailure(e) => Some(e),
            _ => None,
        }
    }
}

/// Something went wrong working with a constant.
#[derive(Debug, DeriveError)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum ConstantError {
    #[error("The static constant address used is not compatible with the live chain")]
    IncompatibleCodegen,
    #[error("Can't find constant: pallet with name {0} not found")]
    PalletNameNotFound(String),
    #[error(
        "Constant '{constant_name}' not found in pallet {pallet_name} in the live chain metadata"
    )]
    ConstantNameNotFound {
        pallet_name: String,
        constant_name: String,
    },
    #[error("Failed to decode constant: {0}")]
    CouldNotDecodeConstant(frame_decode::constants::ConstantDecodeError<u32>),
    #[error("Cannot obtain constant information from metadata: {0}")]
    ConstantInfoError(frame_decode::constants::ConstantInfoError<'static>),
}

impl ConstantError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

#[derive(Debug, DeriveError)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum StorageKeyError {
    #[error("Can't decode the storage key: {error}")]
    StorageKeyDecodeError {
        bytes: Vec<u8>,
        error: frame_decode::storage::StorageKeyDecodeError<u32>,
    },
    #[error("Can't decode the values from the storage key: {0}")]
    CannotDecodeValuesInKey(frame_decode::storage::StorageKeyValueDecodeError),
    #[error(
        "Cannot decode storage key: there were leftover bytes, indicating that the decoding failed"
    )]
    LeftoverBytes { bytes: Vec<u8> },
    #[error("Can't decode a single value from the storage key part at index {index}: {error}")]
    CannotDecodeValueInKey {
        index: usize,
        error: scale_decode::Error,
    },
}

impl StorageKeyError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

#[derive(Debug, DeriveError)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum StorageValueError {
    #[error("Cannot decode storage value: {0}")]
    CannotDecode(frame_decode::storage::StorageValueDecodeError<u32>),
    #[error(
        "Cannot decode storage value: there were leftover bytes, indicating that the decoding failed"
    )]
    LeftoverBytes { bytes: Vec<u8> },
}

impl StorageValueError {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
#[error("Cannot decode extrinsic at index {extrinsic_index}: {error}")]
pub struct ExtrinsicDecodeErrorAt {
    pub extrinsic_index: usize,
    pub error: ExtrinsicDecodeErrorAtReason,
}

impl ExtrinsicDecodeErrorAt {
    fn backend_error(&self) -> Option<&BackendError> {
        None
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum ExtrinsicDecodeErrorAtReason {
    #[error("{0}")]
    DecodeError(frame_decode::extrinsics::ExtrinsicDecodeError),
    #[error("Leftover bytes")]
    LeftoverBytes(Vec<u8>),
}

/// An error that can be emitted when trying to construct a [`crate::config::TransactionExtension`],
/// encode data from the instance, or match on signed extensions.
#[derive(Debug, DeriveError)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum TransactionExtensionError {
    #[error("Error constructing extrinsic parameters: {0}")]
    Custom(Box<dyn core::error::Error + Send + Sync + 'static>),
}

impl TransactionExtensionError {
    /// Create a custom [`TransactionExtensionError`] from a string.
    pub fn custom<S: Into<String>>(error: S) -> Self {
        let error: String = error.into();
        let error: Box<dyn core::error::Error + Send + Sync + 'static> = Box::from(error);
        TransactionExtensionError::Custom(error)
    }
}

impl From<core::convert::Infallible> for TransactionExtensionError {
    fn from(value: core::convert::Infallible) -> Self {
        match value {}
    }
}