Skip to content

Commit

Permalink
Remove derive_more's Display usages (#1601)
Browse files Browse the repository at this point in the history
* Remove derive_more's 'Display' from core

* Remove derive_more's 'Display' from metadata

* Remove derive_more's 'Display' from signer

* Remove derive_more from dependencies (#1602)

closes #1503
  • Loading branch information
pkhry committed May 22, 2024
1 parent 885bbb3 commit d8eb474
Show file tree
Hide file tree
Showing 12 changed files with 204 additions and 90 deletions.
3 changes: 0 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ color-eyre = "0.6.3"
console_error_panic_hook = "0.1.7"
darling = "0.20.8"
derive-where = "1.2.7"
derive_more = "0.99.17"
either = { version = "1.11.0", default-features = false }
frame-metadata = { version = "16.0.0", default-features = false }
futures = { version = "0.3.30", default-features = false, features = ["std"] }
Expand Down
1 change: 0 additions & 1 deletion core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ scale-encode = { workspace = true, default-features = false, features = ["derive
frame-metadata = { workspace = true, default-features = false }
subxt-metadata = { workspace = true, default-features = false }
derive-where = { workspace = true }
derive_more = { workspace = true }
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"] }
Expand Down
166 changes: 116 additions & 50 deletions core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,48 @@

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

use core::fmt::Display;

use alloc::boxed::Box;
use alloc::string::String;
use derive_more::Display;
use subxt_metadata::StorageHasher;

/// The error emitted when something goes wrong.
#[derive(Debug, Display)]
#[derive(Debug)]
pub enum Error {
/// Codec error.
#[display(fmt = "Scale codec error: {_0}")]
Codec(codec::Error),
/// Metadata error.
#[display(fmt = "Metadata Error: {_0}")]
Metadata(MetadataError),
/// Storage address error.
#[display(fmt = "Storage Error: {_0}")]
StorageAddress(StorageAddressError),
/// Error decoding to a [`crate::dynamic::Value`].
#[display(fmt = "Error decoding into dynamic value: {_0}")]
Decode(scale_decode::Error),
/// Error encoding from a [`crate::dynamic::Value`].
#[display(fmt = "Error encoding from dynamic value: {_0}")]
Encode(scale_encode::Error),
/// Error constructing the appropriate extrinsic params.
#[display(fmt = "Extrinsic params error: {_0}")]
ExtrinsicParams(ExtrinsicParamsError),
/// Block body error.
#[display(fmt = "Error working with block body: {_0}")]
Block(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),
}
}
}

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

Expand All @@ -48,114 +59,119 @@ convert_error!(StorageAddressError as Error::StorageAddress);
convert_error!(codec::Error as Error::Codec);

/// Block error
#[derive(Clone, Debug, Display, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BlockError {
/// Extrinsic type ID cannot be resolved with the provided metadata.
#[display(
fmt = "Extrinsic type ID cannot be resolved with the provided metadata. Make sure this is a valid metadata"
)]
MissingType,
/// Unsupported signature.
#[display(fmt = "Unsupported extrinsic version, only version 4 is supported currently")]
/// The extrinsic has an unsupported version.
UnsupportedVersion(u8),
/// Decoding error.
#[display(fmt = "Cannot decode extrinsic: {_0}")]
DecodingError(codec::Error),
}

impl Display for BlockError {
fn fmt(
&self,
f: &mut core::fmt::Formatter<'_>,
) -> core::fmt::Result {
match self {
BlockError::MissingType => write!(f, "Extrinsic type ID cannot be resolved with the provided metadata. Make sure this is a valid metadata"),
BlockError::UnsupportedVersion(_) => write!(f, "Unsupported extrinsic version, only version 4 is supported currently"),
BlockError::DecodingError(e) => write!(f, "Cannot decode extrinsic: {e}"),
}
}
}

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

/// Something went wrong trying to access details in the metadata.
#[derive(Clone, Debug, PartialEq, Display)]
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum MetadataError {
/// The DispatchError type isn't available in the metadata
#[display(fmt = "The DispatchError type isn't available")]
DispatchErrorNotFound,
/// Type not found in metadata.
#[display(fmt = "Type with ID {_0} not found")]
TypeNotFound(u32),
/// Pallet not found (index).
#[display(fmt = "Pallet with index {_0} not found")]
PalletIndexNotFound(u8),
/// Pallet not found (name).
#[display(fmt = "Pallet with name {_0} not found")]
PalletNameNotFound(String),
/// Variant not found.
#[display(fmt = "Variant with index {_0} not found")]
VariantIndexNotFound(u8),
/// Constant not found.
#[display(fmt = "Constant with name {_0} not found")]
ConstantNameNotFound(String),
/// Call not found.
#[display(fmt = "Call with name {_0} not found")]
CallNameNotFound(String),
/// Runtime trait not found.
#[display(fmt = "Runtime trait with name {_0} not found")]
RuntimeTraitNotFound(String),
/// Runtime method not found.
#[display(fmt = "Runtime method with name {_0} not found")]
RuntimeMethodNotFound(String),
/// Call type not found in metadata.
#[display(fmt = "Call type not found in pallet with index {_0}")]
CallTypeNotFoundInPallet(u8),
/// Event type not found in metadata.
#[display(fmt = "Event type not found in pallet with index {_0}")]
EventTypeNotFoundInPallet(u8),
/// Storage details not found in metadata.
#[display(fmt = "Storage details not found in pallet with name {_0}")]
StorageNotFoundInPallet(String),
/// Storage entry not found.
#[display(fmt = "Storage entry {_0} not found")]
StorageEntryNotFound(String),
/// The generated interface used is not compatible with the node.
#[display(fmt = "The generated code is not compatible with the node")]
IncompatibleCodegen,
/// Custom value not found.
#[display(fmt = "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, Display)]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum StorageAddressError {
/// Storage lookup does not have the expected number of keys.
#[display(fmt = "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.
#[display(
fmt = "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.
#[display(fmt = "Not enough remaining bytes to decode the storage address/key")]
NotEnoughBytes,
/// We have leftover bytes after decoding the storage address.
#[display(fmt = "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.
#[display(
fmt = "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.
#[display(
fmt = "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 @@ -164,33 +180,83 @@ 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(Display, Debug)]
#[derive(Debug)]
#[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).
#[display(fmt = "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.
#[display(
fmt = "The chain expects a signed extension with the name {_0}, but we did not provide one"
)]
UnknownSignedExtension(String),
/// Some custom error.
#[display(fmt = "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 Down
20 changes: 14 additions & 6 deletions core/src/utils/account_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
//! This doesn't contain much functionality itself, but is easy to convert to/from an `sp_core::AccountId32`
//! for instance, to gain functionality without forcing a dependency on Substrate crates here.

use core::fmt::Display;

use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use codec::{Decode, Encode};
use derive_more::Display;
use serde::{Deserialize, Serialize};

/// A 32-byte cryptographic identifier. This is a simplified version of Substrate's
Expand Down Expand Up @@ -105,19 +106,26 @@ impl AccountId32 {
}

/// An error obtained from trying to interpret an SS58 encoded string into an AccountId32
#[derive(Clone, Copy, Eq, PartialEq, Debug, Display)]
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
#[allow(missing_docs)]
pub enum FromSs58Error {
#[display(fmt = "Base 58 requirement is violated")]
BadBase58,
#[display(fmt = "Length is bad")]
BadLength,
#[display(fmt = "Invalid checksum")]
InvalidChecksum,
#[display(fmt = "Invalid SS58 prefix byte.")]
InvalidPrefix,
}

impl Display for FromSs58Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
FromSs58Error::BadBase58 => write!(f, "Base 58 requirement is violated"),
FromSs58Error::BadLength => write!(f, "Length is bad"),
FromSs58Error::InvalidChecksum => write!(f, "Invalid checksum"),
FromSs58Error::InvalidPrefix => write!(f, "Invalid SS58 prefix byte."),
}
}
}

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

Expand Down
1 change: 0 additions & 1 deletion metadata/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ frame-metadata = { workspace = true, default-features = false, features = ["curr
codec = { package = "parity-scale-codec", workspace = true, default-features = false, features = ["derive"] }
sp-crypto-hashing = { workspace = true }
hashbrown = { workspace = true }
derive_more = { workspace = true }

[dev-dependencies]
bitvec = { workspace = true, features = ["alloc"] }
Expand Down
Loading

0 comments on commit d8eb474

Please sign in to comment.