Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate custom error trait impls to thiserror #1856

Merged
merged 9 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
315 changes: 180 additions & 135 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,16 @@ proc-macro2 = "1.0.86"
quote = "1.0.37"
regex = { version = "1.11.0", default-features = false }
scale-info = { version = "2.11.4", default-features = false }
scale-value = { version = "0.17.0", default-features = false }
scale-bits = { version = "0.6.0", default-features = false }
scale-decode = { version = "0.14.0", default-features = false }
scale-encode = { version = "0.8.0", default-features = false }
scale-typegen = "0.9.0"
scale-typegen-description = "0.9.0"
scale-value = { version = "0.18.0", default-features = false }
scale-bits = { version = "0.7.0", default-features = false }
scale-decode = { version = "0.16.0", default-features = false }
scale-encode = { version = "0.10.0", default-features = false }
scale-typegen = "0.10.0"
scale-typegen-description = "0.10.0"
serde = { version = "1.0.210", default-features = false, features = ["derive"] }
serde_json = { version = "1.0.128", default-features = false }
syn = { version = "2.0.77", features = ["full", "extra-traits"] }
thiserror = "1.0.64"
thiserror = { version = "2.0.0", default-features = false }
tokio = { version = "1.40", default-features = false }
tracing = { version = "0.1.40", default-features = false }
tracing-wasm = "0.2.1"
Expand Down
8 changes: 3 additions & 5 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,6 @@ default = ["std"]
std = [
"codec/std",
"scale-info/std",
"scale-value/std",
"scale-bits/std",
"scale-decode/std",
"scale-encode/std",
"frame-metadata/std",
"subxt-metadata/std",
"hex/std",
Expand All @@ -49,6 +45,8 @@ hex = { workspace = true, default-features = false, features = ["alloc"] }
serde = { workspace = true, default-features = false, features = ["derive"] }
serde_json = { workspace = true, default-features = false, features = ["raw_value", "alloc"] }
hashbrown = { workspace = true }
thiserror = { workspace = true, default-features = false }


# For ss58 encoding AccountId32 to serialize them properly:
base58 = { workspace = true }
Expand Down Expand Up @@ -82,4 +80,4 @@ rustdoc-args = ["--cfg", "docsrs"]
default-features = true

[lints]
workspace = true
workspace = true
209 changes: 55 additions & 154 deletions core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,203 +4,156 @@

//! The errors that can be emitted in this crate.

use core::fmt::Display;

use alloc::boxed::Box;
use alloc::string::String;
use subxt_metadata::StorageHasher;
use thiserror::Error as DeriveError;

/// The error emitted when something goes wrong.
#[derive(Debug)]
#[derive(Debug, DeriveError)]
pub enum Error {
/// Codec error.
#[error("Codec error: {0}")]
Codec(codec::Error),
/// Metadata error.
Metadata(MetadataError),
#[error(transparent)]
Metadata(#[from] MetadataError),
/// Storage address error.
StorageAddress(StorageAddressError),
#[error(transparent)]
StorageAddress(#[from] StorageAddressError),
/// Error decoding to a [`crate::dynamic::Value`].
Decode(scale_decode::Error),
#[error("Error decoding into dynamic value: {0}")]
Decode(#[from] scale_decode::Error),
/// Error encoding from a [`crate::dynamic::Value`].
Encode(scale_encode::Error),
#[error("Error encoding from dynamic value: {0}")]
Encode(#[from] scale_encode::Error),
/// Error constructing the appropriate extrinsic params.
ExtrinsicParams(ExtrinsicParamsError),
#[error(transparent)]
ExtrinsicParams(#[from] ExtrinsicParamsError),
/// Block body error.
Block(BlockError),
#[error("Error working with block_body: {0}")]
Block(#[from] BlockError),
}

impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::Codec(e) => write!(f, "Scale codec error: {e}"),
Error::Metadata(e) => write!(f, "Metadata Error: {e}"),
Error::StorageAddress(e) => write!(f, "Storage Error: {e}"),
Error::Decode(e) => write!(f, "Error decoding into dynamic value: {e}"),
Error::Encode(e) => write!(f, "Error encoding from dynamic value: {e}"),
Error::ExtrinsicParams(e) => write!(f, "Extrinsic params error: {e}"),
Error::Block(e) => write!(f, "Error working with block_body: {}", e),
}
impl From<scale_decode::visitor::DecodeError> for Error {
fn from(err: scale_decode::visitor::DecodeError) -> Error {
Error::Decode(err.into())
}
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl_from!(ExtrinsicParamsError => Error::ExtrinsicParams);
impl_from!(BlockError => Error::Block);
impl_from!(MetadataError => Error::Metadata);
impl_from!(scale_decode::Error => Error::Decode);
impl_from!(scale_decode::visitor::DecodeError => Error::Decode);
impl_from!(scale_encode::Error => Error::Encode);
impl_from!(StorageAddressError => Error::StorageAddress);
impl_from!(codec::Error => Error::Codec);
// TODO: when `codec::Error` implements `core::Error`
// remove this impl and replace it by thiserror #[from]
impl From<codec::Error> for Error {
fn from(err: codec::Error) -> Error {
Error::Codec(err)
}
}
Comment on lines +44 to +50
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does not implementing core::Error stop you from using #[from] here?

Copy link
Member

@niklasad1 niklasad1 Nov 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

error[E0599]: the method `as_dyn_error` exists for reference `&Error`, but its trait bounds were not satisfied
  --> core/src/error.rs:17:13
   |
17 |     Codec(#[from] codec::Error),
   |             ^^^^ method cannot be called on `&Error` due to unsatisfied trait bounds
   |
  ::: /home/niklasad1/.cargo/registry/src/index.crates.io-6f17d22bba15001f/parity-scale-codec-3.6.12/src/error.rs:26:1
   |
26 | pub struct Error {
   | ---------------- doesn't satisfy `parity_scale_codec::Error: AsDynError<'_>` or `parity_scale_codec::Error: StdError`
   |
   = note: the following trait bounds were not satisfied:
           `parity_scale_codec::Error: StdError`
           which is required by `parity_scale_codec::Error: AsDynError<'_>`
           `&parity_scale_codec::Error: StdError`
           which is required by `&parity_scale_codec::Error: AsDynError<'_>`

It's probably because codec::Error/no_std doesn't implement core::error::Error/StdError and thus the from impl bounds isn't satisfied.


/// Block error
#[derive(Debug)]
#[derive(Debug, DeriveError)]
pub enum BlockError {
/// Leftover bytes found after decoding the extrinsic.
#[error("After decoding the extrinsic at index {extrinsic_index}, {num_leftover_bytes} bytes were left, suggesting that decoding may have failed")]
LeftoverBytes {
/// Index of the extrinsic that failed to decode.
extrinsic_index: usize,
/// Number of bytes leftover after decoding the extrinsic.
num_leftover_bytes: usize,
},
/// Something went wrong decoding the extrinsic.
#[error("Failed to decode extrinsic at index {extrinsic_index}: {error}")]
ExtrinsicDecodeError {
/// Index of the extrinsic that failed to decode.
extrinsic_index: usize,
/// The decode error.
error: ExtrinsicDecodeError,
},
}
impl Display for BlockError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
BlockError::LeftoverBytes {
extrinsic_index,
num_leftover_bytes,
} => {
write!(
f,
"After decoding the extrinsic at index {extrinsic_index}, {num_leftover_bytes} bytes were left, suggesting that decoding may have failed"
)
}
BlockError::ExtrinsicDecodeError {
extrinsic_index,
error,
} => {
write!(
f,
"Failed to decode extrinsic at index {extrinsic_index}: {error}"
)
}
}
}
}

/// An alias for [`frame_decode::extrinsics::ExtrinsicDecodeError`].
///
pub type ExtrinsicDecodeError = frame_decode::extrinsics::ExtrinsicDecodeError;

/// Something went wrong trying to access details in the metadata.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, DeriveError)]
#[non_exhaustive]
pub enum MetadataError {
/// The DispatchError type isn't available in the metadata
#[error("The DispatchError type isn't available")]
DispatchErrorNotFound,
/// Type not found in metadata.
#[error("Type with ID {0} not found")]
TypeNotFound(u32),
/// Pallet not found (index).
#[error("Pallet with index {0} not found")]
PalletIndexNotFound(u8),
/// Pallet not found (name).
#[error("Pallet with name {0} not found")]
PalletNameNotFound(String),
/// Variant not found.
#[error("Variant with index {0} not found")]
VariantIndexNotFound(u8),
/// Constant not found.
#[error("Constant with name {0} not found")]
ConstantNameNotFound(String),
/// Call not found.
#[error("Call with name {0} not found")]
CallNameNotFound(String),
/// Runtime trait not found.
#[error("Runtime trait with name {0} not found")]
RuntimeTraitNotFound(String),
/// Runtime method not found.
#[error("Runtime method with name {0} not found")]
RuntimeMethodNotFound(String),
/// Call type not found in metadata.
#[error("Call type not found in pallet with index {0}")]
CallTypeNotFoundInPallet(u8),
/// Event type not found in metadata.
#[error("Event type not found in pallet with index {0}")]
EventTypeNotFoundInPallet(u8),
/// Storage details not found in metadata.
#[error("Storage details not found in pallet with name {0}")]
StorageNotFoundInPallet(String),
/// Storage entry not found.
#[error("Storage entry {0} not found")]
StorageEntryNotFound(String),
/// The generated interface used is not compatible with the node.
#[error("The generated code is not compatible with the node")]
IncompatibleCodegen,
/// Custom value not found.
#[error("Custom value with name {0} not found")]
CustomValueNameNotFound(String),
}
impl Display for MetadataError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
MetadataError::DispatchErrorNotFound => {
write!(f, "The DispatchError type isn't available")
}
MetadataError::TypeNotFound(e) => write!(f, "Type with ID {e} not found"),
MetadataError::PalletIndexNotFound(e) => write!(f, "Pallet with index {e} not found"),
MetadataError::PalletNameNotFound(e) => write!(f, "Pallet with name {e} not found"),
MetadataError::VariantIndexNotFound(e) => write!(f, "Variant with index {e} not found"),
MetadataError::ConstantNameNotFound(e) => write!(f, "Constant with name {e} not found"),
MetadataError::CallNameNotFound(e) => write!(f, "Call with name {e} not found"),
MetadataError::RuntimeTraitNotFound(e) => {
write!(f, "Runtime trait with name {e} not found")
}
MetadataError::RuntimeMethodNotFound(e) => {
write!(f, "Runtime method with name {e} not found")
}
MetadataError::CallTypeNotFoundInPallet(e) => {
write!(f, "Call type not found in pallet with index {e}")
}
MetadataError::EventTypeNotFoundInPallet(e) => {
write!(f, "Event type not found in pallet with index {e}")
}
MetadataError::StorageNotFoundInPallet(e) => {
write!(f, "Storage details not found in pallet with name {e}")
}
MetadataError::StorageEntryNotFound(e) => write!(f, "Storage entry {e} not found"),
MetadataError::IncompatibleCodegen => {
write!(f, "The generated code is not compatible with the node")
}
MetadataError::CustomValueNameNotFound(e) => {
write!(f, "Custom value with name {e} not found")
}
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for MetadataError {}

/// Something went wrong trying to encode or decode a storage address.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, DeriveError)]
#[non_exhaustive]
pub enum StorageAddressError {
/// Storage lookup does not have the expected number of keys.
#[error("Storage lookup requires {expected} keys but more keys have been provided.")]
TooManyKeys {
/// The number of keys provided in the storage address.
expected: usize,
},
/// This storage entry in the metadata does not have the correct number of hashers to fields.
#[error("Storage entry in metadata does not have the correct number of hashers to fields")]
WrongNumberOfHashers {
/// The number of hashers in the metadata for this storage entry.
hashers: usize,
/// The number of fields in the metadata for this storage entry.
fields: usize,
},
/// We weren't given enough bytes to decode the storage address/key.
#[error("Not enough remaining bytes to decode the storage address/key")]
NotEnoughBytes,
/// We have leftover bytes after decoding the storage address.
#[error("We have leftover bytes after decoding the storage address")]
TooManyBytes,
/// The bytes of a storage address are not the expected address for decoding the storage keys of the address.
#[error("Storage address bytes are not the expected format. Addresses need to be at least 16 bytes (pallet ++ entry) and follow a structure given by the hashers defined in the metadata")]
UnexpectedAddressBytes,
/// An invalid hasher was used to reconstruct a value from a chunk of bytes that is part of a storage address. Hashers where the hash does not contain the original value are invalid for this purpose.
#[error("An invalid hasher was used to reconstruct a value with type ID {ty_id} from a hash formed by a {hasher:?} hasher. This is only possible for concat-style hashers or the identity hasher")]
HasherCannotReconstructKey {
/// Type id of the key's type.
ty_id: u32,
Expand All @@ -209,77 +162,28 @@ pub enum StorageAddressError {
},
}

impl Display for StorageAddressError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
StorageAddressError::TooManyKeys { expected } => write!(
f,
"Storage lookup requires {expected} keys but more keys have been provided."
),
StorageAddressError::WrongNumberOfHashers { .. } => write!(
f,
"Storage entry in metadata does not have the correct number of hashers to fields"
),
StorageAddressError::NotEnoughBytes => write!(
f,
"Not enough remaining bytes to decode the storage address/key"
),
StorageAddressError::TooManyBytes => write!(
f,
"We have leftover bytes after decoding the storage address"
),
StorageAddressError::UnexpectedAddressBytes => write!(
f,
"Storage address bytes are not the expected format. Addresses need to be at least 16 bytes (pallet ++ entry) and follow a structure given by the hashers defined in the metadata"
),
StorageAddressError::HasherCannotReconstructKey { ty_id, hasher } => write!(
f,
"An invalid hasher was used to reconstruct a value with type ID {ty_id} from a hash formed by a {hasher:?} hasher. This is only possible for concat-style hashers or the identity hasher"
),
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for StorageAddressError {}

/// An error that can be emitted when trying to construct an instance of [`crate::config::ExtrinsicParams`],
/// encode data from the instance, or match on signed extensions.
#[derive(Debug)]
#[derive(Debug, DeriveError)]
#[non_exhaustive]
pub enum ExtrinsicParamsError {
/// Cannot find a type id in the metadata. The context provides some additional
/// information about the source of the error (eg the signed extension name).
#[error("Cannot find type id '{type_id} in the metadata (context: {context})")]
MissingTypeId {
/// Type ID.
type_id: u32,
/// Some arbitrary context to help narrow the source of the error.
context: &'static str,
},
/// A signed extension in use on some chain was not provided.
#[error("The chain expects a signed extension with the name {0}, but we did not provide one")]
UnknownSignedExtension(String),
/// Some custom error.
#[error("Error constructing extrinsic parameters: {0}")]
Custom(Box<dyn CustomError>),
}

impl Display for ExtrinsicParamsError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
ExtrinsicParamsError::MissingTypeId { type_id, context } => write!(
f,
"Cannot find type id '{type_id} in the metadata (context: {context})"
),
ExtrinsicParamsError::UnknownSignedExtension(e) => write!(
f,
"The chain expects a signed extension with the name {e}, but we did not provide one"
),
ExtrinsicParamsError::Custom(e) => {
write!(f, "Error constructing extrinsic parameters: {e}")
}
}
}
}

/// Anything implementing this trait can be used in [`ExtrinsicParamsError::Custom`].
#[cfg(feature = "std")]
pub trait CustomError: std::error::Error + Send + Sync + 'static {}
Expand All @@ -292,9 +196,6 @@ pub trait CustomError: core::fmt::Debug + core::fmt::Display + Send + Sync + 'st
#[cfg(not(feature = "std"))]
impl<T: core::fmt::Debug + core::fmt::Display + Send + Sync + 'static> CustomError for T {}

#[cfg(feature = "std")]
impl std::error::Error for ExtrinsicParamsError {}

impl From<core::convert::Infallible> for ExtrinsicParamsError {
fn from(value: core::convert::Infallible) -> Self {
match value {}
Expand Down
Loading
Loading