pezkuwi-subxt 0.44.0

Submit extrinsics (transactions) to a Pezkuwi/Bizinikiwi node via RPC
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
// Copyright 2019-2025 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;

crate::macros::cfg_unstable_light_client! {
	pub use pezkuwi_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 crate::Metadata;
pub use hex::Hex;
pub use pezkuwi_subxt_metadata::TryFromError as MetadataTryFromError;
pub use scale_decode::Error as DecodeError;
pub use scale_encode::Error as EncodeError;

// Re-export core error types we're just reusing.
pub use pezkuwi_subxt_core::error::{
	ConstantError,
	CustomValueError,
	EventsError as CoreEventsError,
	// These errors are exposed as-is:
	ExtrinsicDecodeErrorAt,
	// These errors are wrapped:
	ExtrinsicError as CoreExtrinsicError,
	RuntimeApiError as CoreRuntimeApiError,
	StorageError as CoreStorageError,
	StorageKeyError,
	StorageValueError,
	ViewFunctionError as CoreViewFunctionError,
};

/// 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)]
	ExtrinsicDecodeErrorAt(#[from] ExtrinsicDecodeErrorAt),
	#[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)]
	BlockError(#[from] BlockError),
	#[error(transparent)]
	AccountNonceError(#[from] AccountNonceError),
	#[error(transparent)]
	OnlineClientError(#[from] OnlineClientError),
	#[error(transparent)]
	RuntimeUpdaterError(#[from] RuntimeUpdaterError),
	#[error(transparent)]
	RuntimeUpdateeApplyError(#[from] RuntimeUpdateeApplyError),
	#[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),
	// 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 pezkuwi_subxt::Error.
	#[error("Other RPC client error: {0}")]
	OtherRpcClientError(#[from] pezkuwi_subxt_rpcs::Error),
	#[error("Other codec error: {0}")]
	OtherCodecError(#[from] codec::Error),
	#[cfg(feature = "unstable-light-client")]
	#[error("Other light client error: {0}")]
	OtherLightClientError(#[from] pezkuwi_subxt_lightclient::LightClientError),
	#[cfg(feature = "unstable-light-client")]
	#[error("Other light client RPC error: {0}")]
	OtherLightClientRpcError(#[from] pezkuwi_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 pezkuwi_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(
				pezkuwi_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 {
			Error::BlockError(e) => e.backend_error(),
			Error::AccountNonceError(e) => e.backend_error(),
			Error::OnlineClientError(e) => e.backend_error(),
			Error::RuntimeUpdaterError(e) => e.backend_error(),
			Error::RuntimeApiError(e) => e.backend_error(),
			Error::EventsError(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(),
			// Any errors that **don't** return a BackendError anywhere will return None:
			_ => None,
		}
	}
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum BackendError {
	#[error("Backend error: RPC error: {0}")]
	Rpc(#[from] RpcError),
	#[error("Backend error: Could not find metadata version {0}")]
	MetadataVersionNotFound(u32),
	#[error("Backend error: Could not codec::Decode Runtime API response: {0}")]
	CouldNotScaleDecodeRuntimeResponse(codec::Error),
	#[error(
		"Backend error: Could not codec::Decode metadata bytes into pezkuwi_subxt::Metadata: {0}"
	)]
	CouldNotDecodeMetadata(codec::Error),
	// This is for errors in `Backend` implementations which aren't any of the "pre-defined" set
	// above:
	#[error("Custom backend error: {0}")]
	Other(String),
}

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(
				pezkuwi_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))
	}
}

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

/// 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] pezkuwi_subxt_rpcs::Error),
	/// This error signals that we got back a
	/// [`pezkuwi_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,
}

/// Block error
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum BlockError {
	#[error(
		"Could not find the block body with hash {block_hash} (perhaps it was on a non-finalized fork?)"
	)]
	BlockNotFound { block_hash: Hex },
	#[error("Could not download the block header with hash {block_hash}: {reason}")]
	CouldNotGetBlockHeader { block_hash: Hex, reason: BackendError },
	#[error("Could not download the latest block header: {0}")]
	CouldNotGetLatestBlock(BackendError),
	#[error("Could not subscribe to all blocks: {0}")]
	CouldNotSubscribeToAllBlocks(BackendError),
	#[error("Could not subscribe to best blocks: {0}")]
	CouldNotSubscribeToBestBlocks(BackendError),
	#[error("Could not subscribe to finalized blocks: {0}")]
	CouldNotSubscribeToFinalizedBlocks(BackendError),
	#[error("Error getting account nonce at block {block_hash}")]
	AccountNonceError { block_hash: Hex, account_id: Hex, reason: AccountNonceError },
}

impl BlockError {
	fn backend_error(&self) -> Option<&BackendError> {
		match self {
			BlockError::CouldNotGetBlockHeader { reason: e, .. }
			| BlockError::CouldNotGetLatestBlock(e)
			| BlockError::CouldNotSubscribeToAllBlocks(e)
			| BlockError::CouldNotSubscribeToBestBlocks(e)
			| BlockError::CouldNotSubscribeToFinalizedBlocks(e) => Some(e),
			_ => None,
		}
	}
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum AccountNonceError {
	#[error("Could not retrieve account nonce: {0}")]
	CouldNotRetrieve(#[from] BackendError),
	#[error("Could not decode account nonce: {0}")]
	CouldNotDecode(#[from] 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,
		}
	}
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum OnlineClientError {
	#[error("Cannot construct OnlineClient: {0}")]
	RpcError(#[from] pezkuwi_subxt_rpcs::Error),
	#[error(
		"Cannot construct OnlineClient: Cannot fetch latest finalized block to obtain init details from: {0}"
	)]
	CannotGetLatestFinalizedBlock(BackendError),
	#[error("Cannot construct OnlineClient: Cannot fetch genesis hash: {0}")]
	CannotGetGenesisHash(BackendError),
	#[error("Cannot construct OnlineClient: Cannot fetch current runtime version: {0}")]
	CannotGetCurrentRuntimeVersion(BackendError),
	#[error("Cannot construct OnlineClient: Cannot fetch metadata: {0}")]
	CannotFetchMetadata(BackendError),
}

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

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum RuntimeUpdaterError {
	#[error("Error subscribing to runtime updates: The update stream ended unexpectedly")]
	UnexpectedEndOfUpdateStream,
	#[error("Error subscribing to runtime updates: The finalized block stream ended unexpectedly")]
	UnexpectedEndOfBlockStream,
	#[error("Error subscribing to runtime updates: Can't stream runtime version: {0}")]
	CannotStreamRuntimeVersion(BackendError),
	#[error("Error subscribing to runtime updates: Can't get next runtime version in stream: {0}")]
	CannotGetNextRuntimeVersion(BackendError),
	#[error("Error subscribing to runtime updates: Cannot stream finalized blocks: {0}")]
	CannotStreamFinalizedBlocks(BackendError),
	#[error(
		"Error subscribing to runtime updates: Cannot get next finalized block in stream: {0}"
	)]
	CannotGetNextFinalizedBlock(BackendError),
	#[error("Cannot fetch new metadata for runtime update: {0}")]
	CannotFetchNewMetadata(BackendError),
	#[error(
		"Error subscribing to runtime updates: Cannot find the System.LastRuntimeUpgrade storage entry"
	)]
	CantFindSystemLastRuntimeUpgrade,
	#[error("Error subscribing to runtime updates: Cannot fetch last runtime upgrade: {0}")]
	CantFetchLastRuntimeUpgrade(StorageError),
	#[error("Error subscribing to runtime updates: Cannot decode last runtime upgrade: {0}")]
	CannotDecodeLastRuntimeUpgrade(StorageValueError),
}

impl RuntimeUpdaterError {
	fn backend_error(&self) -> Option<&BackendError> {
		match self {
			RuntimeUpdaterError::CannotStreamRuntimeVersion(e)
			| RuntimeUpdaterError::CannotGetNextRuntimeVersion(e)
			| RuntimeUpdaterError::CannotStreamFinalizedBlocks(e)
			| RuntimeUpdaterError::CannotGetNextFinalizedBlock(e)
			| RuntimeUpdaterError::CannotFetchNewMetadata(e) => Some(e),
			_ => None,
		}
	}
}

/// Error that can occur during upgrade.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum RuntimeUpdateeApplyError {
	#[error("The proposed runtime update is the same as the current version")]
	SameVersion,
}

/// Error working with Runtime APIs
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum RuntimeApiError {
	#[error(
		"Cannot access Runtime APIs at latest block: Cannot fetch latest finalized block: {0}"
	)]
	CannotGetLatestFinalizedBlock(BackendError),
	#[error("{0}")]
	OfflineError(#[from] CoreRuntimeApiError),
	#[error("Cannot call the Runtime API: {0}")]
	CannotCallApi(BackendError),
}

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

/// Error working with events.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum EventsError {
	#[error("{0}")]
	OfflineError(#[from] CoreEventsError),
	#[error("Cannot access events at latest block: Cannot fetch latest finalized block: {0}")]
	CannotGetLatestFinalizedBlock(BackendError),
	#[error("Cannot fetch event bytes: {0}")]
	CannotFetchEventBytes(BackendError),
}

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

/// Error working with extrinsics.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum ExtrinsicError {
	#[error("{0}")]
	OfflineError(#[from] CoreExtrinsicError),
	#[error("Could not download block body to extract extrinsics from: {0}")]
	CannotGetBlockBody(BackendError),
	#[error("Block not found: {0}")]
	BlockNotFound(Hex),
	#[error("{0}")]
	CouldNotDecodeExtrinsics(#[from] ExtrinsicDecodeErrorAt),
	#[error(
		"Extrinsic submission error: Cannot get latest finalized block to grab account nonce at: {0}"
	)]
	CannotGetLatestFinalizedBlock(BackendError),
	#[error("Cannot find block header for block {block_hash}")]
	CannotFindBlockHeader { block_hash: 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 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::CannotGetLatestFinalizedBlock(e)
			| ExtrinsicError::ErrorSubmittingTransaction(e)
			| ExtrinsicError::TransactionStatusStreamError(e)
			| ExtrinsicError::CannotGetFeeInfo(e)
			| ExtrinsicError::CannotGetValidationInfo(e) => Some(e),
			ExtrinsicError::AccountNonceError { reason, .. } => reason.backend_error(),
			_ => None,
		}
	}
}

/// Error working with View Functions.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum ViewFunctionError {
	#[error("{0}")]
	OfflineError(#[from] CoreViewFunctionError),
	#[error(
		"Cannot access View Functions at latest block: Cannot fetch latest finalized block: {0}"
	)]
	CannotGetLatestFinalizedBlock(BackendError),
	#[error("Cannot call the View Function Runtime API: {0}")]
	CannotCallApi(BackendError),
}

impl ViewFunctionError {
	fn backend_error(&self) -> Option<&BackendError> {
		match self {
			ViewFunctionError::CannotGetLatestFinalizedBlock(e)
			| 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),
}

/// 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 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 },
}

/// 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);

/// 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>,
	},
}

/// Error working with storage.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum StorageError {
	#[error("{0}")]
	Offline(#[from] CoreStorageError),
	#[error("Cannot access storage at latest block: Cannot fetch latest finalized block: {0}")]
	CannotGetLatestFinalizedBlock(BackendError),
	#[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::CannotGetLatestFinalizedBlock(e)
			| StorageError::CannotFetchValue(e)
			| StorageError::CannotIterateValues(e)
			| StorageError::StreamFailure(e) => Some(e),
			_ => None,
		}
	}
}