From 2c40b14230eee81238dc8314561eddfc030b8000 Mon Sep 17 00:00:00 2001 From: Tadeo hepperle Date: Mon, 22 Jan 2024 18:53:04 +0100 Subject: [PATCH] error type implementations --- Cargo.lock | 2 +- Cargo.toml | 1 + cli/Cargo.toml | 2 +- subxt/Cargo.toml | 2 +- subxt/src/backend/legacy/rpc_methods.rs | 6 +- subxt/src/backend/rpc/rpc_client.rs | 4 +- subxt/src/backend/unstable/mod.rs | 6 +- subxt/src/backend/unstable/rpc_methods.rs | 13 +- subxt/src/blocks/extrinsic_types.rs | 26 +-- subxt/src/client/light_client/builder.rs | 6 +- subxt/src/client/online_client.rs | 2 +- subxt/src/config/extrinsic_params.rs | 16 +- subxt/src/config/signed_extensions.rs | 6 +- subxt/src/constants/constant_address.rs | 8 +- subxt/src/constants/constants_client.rs | 6 +- .../src/custom_values/custom_value_address.rs | 2 +- .../src/custom_values/custom_values_client.rs | 6 +- subxt/src/error/dispatch_error.rs | 94 ++++++---- subxt/src/error/mod.rs | 165 +++++++++++------- subxt/src/events/events_client.rs | 6 +- subxt/src/prelude.rs | 15 +- subxt/src/runtime_api/runtime_payload.rs | 5 +- subxt/src/storage/storage_address.rs | 10 +- subxt/src/tx/tx_client.rs | 6 +- subxt/src/tx/tx_progress.rs | 19 +- subxt/src/utils/account_id.rs | 18 +- subxt/src/utils/bits.rs | 4 +- subxt/src/utils/mod.rs | 4 +- subxt/src/utils/multi_address.rs | 1 + subxt/src/utils/static_type.rs | 9 +- subxt/src/utils/unchecked_extrinsic.rs | 3 +- subxt/src/utils/wrapper_opaque.rs | 3 +- 32 files changed, 269 insertions(+), 207 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c1f907556e..5d2303d88c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4388,6 +4388,7 @@ dependencies = [ "blake2", "cfg-if", "derivative", + "derive_more", "either", "frame-metadata 16.0.0", "futures", @@ -4412,7 +4413,6 @@ dependencies = [ "subxt-macro", "subxt-metadata", "subxt-signer", - "thiserror", "tokio", "tokio-stream", "tokio-util", diff --git a/Cargo.toml b/Cargo.toml index 8f1ee54a8f..a34eb075d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,6 +65,7 @@ color-eyre = "0.6.1" console_error_panic_hook = "0.1.7" darling = "0.20.3" derivative = "2.2.0" +derive_more = "0.99.17" either = "1.9.0" frame-metadata = { version = "16.0.0", default-features = false, features = ["current", "std"] } futures = { version = "0.3.30", default-features = false, features = ["std"] } diff --git a/cli/Cargo.toml b/cli/Cargo.toml index f569a30005..b656518b91 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -41,4 +41,4 @@ syn = { workspace = true } jsonrpsee = { workspace = true, features = ["async-client", "client-ws-transport-native-tls", "http-client"] } tokio = { workspace = true, features = ["rt-multi-thread"] } thiserror = { workspace = true } -smoldot = { workspace = true, optional = true} +smoldot = { workspace = true, optional = true } diff --git a/subxt/Cargo.toml b/subxt/Cargo.toml index a7df1696a1..bc1a06bc4e 100644 --- a/subxt/Cargo.toml +++ b/subxt/Cargo.toml @@ -63,10 +63,10 @@ futures = { workspace = true } hex = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = ["raw_value"] } -thiserror = { workspace = true } tracing = { workspace = true } frame-metadata = { workspace = true } derivative = { workspace = true, features = ["use_core"] } +derive_more = { workspace = true } either = { workspace = true } # Provides some deserialization, types like U256/H256 and hashing impls like twox/blake256: diff --git a/subxt/src/backend/legacy/rpc_methods.rs b/subxt/src/backend/legacy/rpc_methods.rs index 82fd2a1af6..c020133453 100644 --- a/subxt/src/backend/legacy/rpc_methods.rs +++ b/subxt/src/backend/legacy/rpc_methods.rs @@ -6,8 +6,8 @@ use crate::backend::rpc::{rpc_params, RpcClient, RpcSubscription}; use crate::metadata::Metadata; -use crate::{Config, Error}; use crate::prelude::*; +use crate::{Config, Error}; use codec::Decode; use derivative::Derivative; use primitive_types::U256; @@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize}; #[derivative(Clone(bound = ""), Debug(bound = ""))] pub struct LegacyRpcMethods { client: RpcClient, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl LegacyRpcMethods { @@ -28,7 +28,7 @@ impl LegacyRpcMethods { pub fn new(client: RpcClient) -> Self { LegacyRpcMethods { client, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } diff --git a/subxt/src/backend/rpc/rpc_client.rs b/subxt/src/backend/rpc/rpc_client.rs index 12a854c684..7f5da8e634 100644 --- a/subxt/src/backend/rpc/rpc_client.rs +++ b/subxt/src/backend/rpc/rpc_client.rs @@ -181,7 +181,7 @@ impl RpcParams { /// [`StreamExt`] extension trait. pub struct RpcSubscription { inner: RawRpcSubscription, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl std::fmt::Debug for RpcSubscription { @@ -198,7 +198,7 @@ impl RpcSubscription { pub fn new(inner: RawRpcSubscription) -> Self { Self { inner, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } diff --git a/subxt/src/backend/unstable/mod.rs b/subxt/src/backend/unstable/mod.rs index 49af9b9208..409181ad3a 100644 --- a/subxt/src/backend/unstable/mod.rs +++ b/subxt/src/backend/unstable/mod.rs @@ -27,8 +27,8 @@ use crate::backend::{ }; use crate::config::BlockHash; use crate::error::{Error, RpcError}; -use crate::Config; use crate::prelude::*; +use crate::Config; use async_trait::async_trait; use follow_stream_driver::{FollowStreamDriver, FollowStreamDriverHandle}; use futures::{Stream, StreamExt}; @@ -43,7 +43,7 @@ pub use rpc_methods::UnstableRpcMethods; /// Configure and build an [`UnstableBackend`]. pub struct UnstableBackendBuilder { max_block_life: usize, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl Default for UnstableBackendBuilder { @@ -57,7 +57,7 @@ impl UnstableBackendBuilder { pub fn new() -> Self { Self { max_block_life: usize::MAX, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } diff --git a/subxt/src/backend/unstable/rpc_methods.rs b/subxt/src/backend/unstable/rpc_methods.rs index ea48dbf6c2..a3e914983f 100644 --- a/subxt/src/backend/unstable/rpc_methods.rs +++ b/subxt/src/backend/unstable/rpc_methods.rs @@ -8,8 +8,8 @@ use crate::backend::rpc::{rpc_params, RpcClient, RpcSubscription}; use crate::config::BlockHash; -use crate::{Config, Error}; use crate::prelude::*; +use crate::{Config, Error}; use derivative::Derivative; use futures::{Stream, StreamExt}; use serde::{Deserialize, Serialize}; @@ -23,7 +23,7 @@ use std::task::Poll; #[derivative(Clone(bound = ""), Debug(bound = ""))] pub struct UnstableRpcMethods { client: RpcClient, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl UnstableRpcMethods { @@ -31,7 +31,7 @@ impl UnstableRpcMethods { pub fn new(client: RpcClient) -> Self { UnstableRpcMethods { client, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } @@ -747,6 +747,7 @@ fn to_hex(bytes: impl AsRef<[u8]>) -> String { /// Attempt to deserialize either a string or integer into an integer. /// See pub(crate) mod unsigned_number_as_string { + use crate::prelude::*; use serde::de::{Deserializer, Visitor}; use std::fmt; @@ -755,10 +756,10 @@ pub(crate) mod unsigned_number_as_string { where D: Deserializer<'de>, { - deserializer.deserialize_any(NumberVisitor(std::marker::PhantomData)) + deserializer.deserialize_any(NumberVisitor(PhantomData)) } - struct NumberVisitor(std::marker::PhantomData); + struct NumberVisitor(PhantomData); impl<'de, N: From> Visitor<'de> for NumberVisitor { type Value = N; @@ -794,11 +795,11 @@ pub(crate) mod unsigned_number_as_string { /// /// Adapted from pub(crate) mod hashmap_as_tuple_list { + use crate::prelude::*; use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor}; use std::collections::HashMap; use std::fmt; use std::hash::{BuildHasher, Hash}; - use std::marker::PhantomData; /// Deserialize a [`HashMap`] from a list of tuples or object pub fn deserialize<'de, K, V, BH, D>(deserializer: D) -> Result, D::Error> diff --git a/subxt/src/blocks/extrinsic_types.rs b/subxt/src/blocks/extrinsic_types.rs index d35bd444de..5d71dd8a33 100644 --- a/subxt/src/blocks/extrinsic_types.rs +++ b/subxt/src/blocks/extrinsic_types.rs @@ -2,6 +2,13 @@ // This file is dual-licensed as Apache-2.0 or GPL-3.0. // see LICENSE for license details. +use crate::config::signed_extensions::{ + ChargeAssetTxPayment, ChargeTransactionPayment, CheckNonce, +}; +use crate::config::SignedExtension; +use crate::dynamic::DecodedValue; +use crate::prelude::*; +use crate::utils::strip_compact_prefix; use crate::{ blocks::block_types::{get_events, CachedEvents}, client::{OfflineClientT, OnlineClientT}, @@ -11,13 +18,6 @@ use crate::{ metadata::types::PalletMetadata, Metadata, }; -use crate::prelude::*; -use crate::config::signed_extensions::{ - ChargeAssetTxPayment, ChargeTransactionPayment, CheckNonce, -}; -use crate::config::SignedExtension; -use crate::dynamic::DecodedValue; -use crate::utils::strip_compact_prefix; use codec::Decode; use derivative::Derivative; use scale_decode::{DecodeAsFields, DecodeAsType}; @@ -177,7 +177,7 @@ pub struct ExtrinsicDetails { cached_events: CachedEvents, /// Subxt metadata to fetch the extrinsic metadata. metadata: Metadata, - _marker: std::marker::PhantomData, + _marker: PhantomData, } /// Details only available in signed extrinsics. @@ -290,7 +290,7 @@ where client, cached_events, metadata, - _marker: std::marker::PhantomData, + _marker: PhantomData, }) } @@ -376,7 +376,7 @@ where Some(ExtrinsicSignedExtensions { bytes: extra_bytes, metadata: &self.metadata, - _marker: std::marker::PhantomData, + _marker: PhantomData, }) } @@ -613,7 +613,7 @@ impl ExtrinsicEvents { pub struct ExtrinsicSignedExtensions<'a, T: Config> { bytes: &'a [u8], metadata: &'a Metadata, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl<'a, T: Config> ExtrinsicSignedExtensions<'a, T> { @@ -655,7 +655,7 @@ impl<'a, T: Config> ExtrinsicSignedExtensions<'a, T> { ty_id, identifier: extension.identifier(), metadata, - _marker: std::marker::PhantomData, + _marker: PhantomData, })) }) } @@ -713,7 +713,7 @@ pub struct ExtrinsicSignedExtension<'a, T: Config> { ty_id: u32, identifier: &'a str, metadata: &'a Metadata, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl<'a, T: Config> ExtrinsicSignedExtension<'a, T> { diff --git a/subxt/src/client/light_client/builder.rs b/subxt/src/client/light_client/builder.rs index f121f08464..77cef9e992 100644 --- a/subxt/src/client/light_client/builder.rs +++ b/subxt/src/client/light_client/builder.rs @@ -6,9 +6,9 @@ use super::{rpc::LightClientRpc, LightClient, LightClientError}; use crate::backend::rpc::RpcClient; use crate::client::RawLightClient; use crate::macros::{cfg_jsonrpsee_native, cfg_jsonrpsee_web}; +use crate::prelude::*; use crate::utils::validate_url_is_secure; use crate::{config::Config, error::Error, OnlineClient}; -use crate::prelude::*; use std::num::NonZeroU32; use subxt_lightclient::{smoldot, AddedChain}; @@ -19,7 +19,7 @@ pub struct LightClientBuilder { max_subscriptions: u32, bootnodes: Option>, potential_relay_chains: Option>, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl Default for LightClientBuilder { @@ -30,7 +30,7 @@ impl Default for LightClientBuilder { max_subscriptions: 1024, bootnodes: None, potential_relay_chains: None, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } } diff --git a/subxt/src/client/online_client.rs b/subxt/src/client/online_client.rs index 6f7879a468..80a5acb6bd 100644 --- a/subxt/src/client/online_client.rs +++ b/subxt/src/client/online_client.rs @@ -4,6 +4,7 @@ use super::{OfflineClient, OfflineClientT}; use crate::custom_values::CustomValuesClient; +use crate::prelude::*; use crate::{ backend::{ legacy::LegacyBackend, rpc::RpcClient, Backend, BackendExt, RuntimeVersion, StreamOfResults, @@ -17,7 +18,6 @@ use crate::{ tx::TxClient, Config, Metadata, }; -use crate::prelude::*; use derivative::Derivative; use futures::future; use std::sync::{Arc, RwLock}; diff --git a/subxt/src/config/extrinsic_params.rs b/subxt/src/config/extrinsic_params.rs index c5a3c3a371..41b706a5df 100644 --- a/subxt/src/config/extrinsic_params.rs +++ b/subxt/src/config/extrinsic_params.rs @@ -7,18 +7,19 @@ //! [`crate::config::DefaultExtrinsicParams`] provides a general-purpose //! implementation of this that will work in many cases. -use crate::{client::OfflineClientT, Config}; use crate::prelude::*; +use crate::{client::OfflineClientT, Config}; use core::fmt::Debug; +use derive_more::Display; /// An error that can be emitted when trying to construct an instance of [`ExtrinsicParams`], /// encode data from the instance, or match on signed extensions. -#[derive(thiserror::Error, Debug)] +#[derive(Display, 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). - #[error("Cannot find type id '{type_id} in the metadata (context: {context})")] + #[display(fmt = "Cannot find type id '{type_id} in the metadata (context: {context})")] MissingTypeId { /// Type ID. type_id: u32, @@ -26,13 +27,18 @@ pub enum ExtrinsicParamsError { 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")] + #[display( + fmt = "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}")] + #[display(fmt = "Error constructing extrinsic parameters: {_0}")] Custom(CustomExtrinsicParamsError), } +#[cfg(feature = "std")] +impl std::error::Error for ExtrinsicParamsError {} + /// A custom error. pub type CustomExtrinsicParamsError = Box; diff --git a/subxt/src/config/signed_extensions.rs b/subxt/src/config/signed_extensions.rs index a3c58d55b0..5d3c10928b 100644 --- a/subxt/src/config/signed_extensions.rs +++ b/subxt/src/config/signed_extensions.rs @@ -8,9 +8,9 @@ //! when interacting with a chain. use super::extrinsic_params::{ExtrinsicParams, ExtrinsicParamsEncoder, ExtrinsicParamsError}; +use crate::prelude::*; use crate::utils::Era; use crate::{client::OfflineClientT, Config}; -use crate::prelude::*; use codec::{Compact, Encode}; use core::fmt::Debug; use derivative::Derivative; @@ -368,7 +368,7 @@ impl SignedExtension for ChargeTransactionPayment { /// is a sensible default, and allows for a single configuration to work across multiple chains. pub struct AnyOf { params: Vec>, - _marker: std::marker::PhantomData<(T, Params)>, + _marker: PhantomData<(T, Params)>, } macro_rules! impl_tuples { @@ -425,7 +425,7 @@ macro_rules! impl_tuples { Ok(AnyOf { params, - _marker: std::marker::PhantomData + _marker: PhantomData }) } } diff --git a/subxt/src/constants/constant_address.rs b/subxt/src/constants/constant_address.rs index c0d621bc22..ba00db8c53 100644 --- a/subxt/src/constants/constant_address.rs +++ b/subxt/src/constants/constant_address.rs @@ -2,8 +2,8 @@ // This file is dual-licensed as Apache-2.0 or GPL-3.0. // see LICENSE for license details. -use crate::{dynamic::DecodedValueThunk, metadata::DecodeWithMetadata}; use crate::prelude::*; +use crate::{dynamic::DecodedValueThunk, metadata::DecodeWithMetadata}; use derivative::Derivative; use std::borrow::Cow; @@ -34,7 +34,7 @@ pub struct Address { pallet_name: Cow<'static, str>, constant_name: Cow<'static, str>, constant_hash: Option<[u8; 32]>, - _marker: std::marker::PhantomData, + _marker: PhantomData, } /// The type of address typically used to return dynamic constant values. @@ -47,7 +47,7 @@ impl Address { pallet_name: Cow::Owned(pallet_name.into()), constant_name: Cow::Owned(constant_name.into()), constant_hash: None, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } @@ -63,7 +63,7 @@ impl Address { pallet_name: Cow::Borrowed(pallet_name), constant_name: Cow::Borrowed(constant_name), constant_hash: Some(hash), - _marker: std::marker::PhantomData, + _marker: PhantomData, } } diff --git a/subxt/src/constants/constants_client.rs b/subxt/src/constants/constants_client.rs index 47138d71ac..72b5c88248 100644 --- a/subxt/src/constants/constants_client.rs +++ b/subxt/src/constants/constants_client.rs @@ -3,13 +3,13 @@ // see LICENSE for license details. use super::ConstantAddress; +use crate::prelude::*; use crate::{ client::OfflineClientT, error::{Error, MetadataError}, metadata::DecodeWithMetadata, Config, }; -use crate::prelude::*; use derivative::Derivative; /// A client for accessing constants. @@ -17,7 +17,7 @@ use derivative::Derivative; #[derivative(Clone(bound = "Client: Clone"))] pub struct ConstantsClient { client: Client, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl ConstantsClient { @@ -25,7 +25,7 @@ impl ConstantsClient { pub fn new(client: Client) -> Self { Self { client, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } } diff --git a/subxt/src/custom_values/custom_value_address.rs b/subxt/src/custom_values/custom_value_address.rs index 59097a7441..922f380074 100644 --- a/subxt/src/custom_values/custom_value_address.rs +++ b/subxt/src/custom_values/custom_value_address.rs @@ -1,5 +1,5 @@ use derivative::Derivative; -use std::marker::PhantomData; +use PhantomData; use crate::dynamic::DecodedValueThunk; use crate::metadata::DecodeWithMetadata; diff --git a/subxt/src/custom_values/custom_values_client.rs b/subxt/src/custom_values/custom_values_client.rs index b634ac4553..9f193f394d 100644 --- a/subxt/src/custom_values/custom_values_client.rs +++ b/subxt/src/custom_values/custom_values_client.rs @@ -2,8 +2,8 @@ use crate::client::OfflineClientT; use crate::custom_values::custom_value_address::{CustomValueAddress, Yes}; use crate::error::MetadataError; use crate::metadata::DecodeWithMetadata; -use crate::{Config, Error}; use crate::prelude::*; +use crate::{Config, Error}; use derivative::Derivative; /// A client for accessing custom values stored in the metadata. @@ -11,7 +11,7 @@ use derivative::Derivative; #[derivative(Clone(bound = "Client: Clone"))] pub struct CustomValuesClient { client: Client, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl CustomValuesClient { @@ -19,7 +19,7 @@ impl CustomValuesClient { pub fn new(client: Client) -> Self { Self { client, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } } diff --git a/subxt/src/error/dispatch_error.rs b/subxt/src/error/dispatch_error.rs index b510de6c6f..bada63c640 100644 --- a/subxt/src/error/dispatch_error.rs +++ b/subxt/src/error/dispatch_error.rs @@ -6,124 +6,139 @@ //! something fails in trying to submit/execute a transaction. use crate::metadata::{DecodeWithMetadata, Metadata}; +use crate::prelude::*; use core::fmt::Debug; +use derive_more::Display; use scale_decode::{visitor::DecodeAsTypeResult, DecodeAsType}; use std::borrow::Cow; -use crate::prelude::*; use super::{Error, MetadataError}; /// An error dispatching a transaction. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, Display, PartialEq, Eq)] #[non_exhaustive] pub enum DispatchError { /// Some error occurred. - #[error("Some unknown error occurred.")] + #[display(fmt = "Some unknown error occurred.")] Other, /// Failed to lookup some data. - #[error("Failed to lookup some data.")] + #[display(fmt = "Failed to lookup some data.")] CannotLookup, /// A bad origin. - #[error("Bad origin.")] + #[display(fmt = "Bad origin.")] BadOrigin, /// A custom error in a module. - #[error("Pallet error: {0}")] + #[display(fmt = "Pallet error: {_0}")] Module(ModuleError), /// At least one consumer is remaining so the account cannot be destroyed. - #[error("At least one consumer is remaining so the account cannot be destroyed.")] + #[display(fmt = "At least one consumer is remaining so the account cannot be destroyed.")] ConsumerRemaining, /// There are no providers so the account cannot be created. - #[error("There are no providers so the account cannot be created.")] + #[display(fmt = "There are no providers so the account cannot be created.")] NoProviders, /// There are too many consumers so the account cannot be created. - #[error("There are too many consumers so the account cannot be created.")] + #[display(fmt = "There are too many consumers so the account cannot be created.")] TooManyConsumers, /// An error to do with tokens. - #[error("Token error: {0}")] + #[display(fmt = "Token error: {_0}")] Token(TokenError), /// An arithmetic error. - #[error("Arithmetic error: {0}")] + #[display(fmt = "Arithmetic error: {_0}")] Arithmetic(ArithmeticError), /// The number of transactional layers has been reached, or we are not in a transactional layer. - #[error("Transactional error: {0}")] + #[display(fmt = "Transactional error: {_0}")] Transactional(TransactionalError), /// Resources exhausted, e.g. attempt to read/write data which is too large to manipulate. - #[error( - "Resources exhausted, e.g. attempt to read/write data which is too large to manipulate." + #[display( + fmt = "Resources exhausted, e.g. attempt to read/write data which is too large to manipulate." )] Exhausted, /// The state is corrupt; this is generally not going to fix itself. - #[error("The state is corrupt; this is generally not going to fix itself.")] + #[display(fmt = "The state is corrupt; this is generally not going to fix itself.")] Corruption, /// Some resource (e.g. a preimage) is unavailable right now. This might fix itself later. - #[error( - "Some resource (e.g. a preimage) is unavailable right now. This might fix itself later." + #[display( + fmt = "Some resource (e.g. a preimage) is unavailable right now. This might fix itself later." )] Unavailable, } +#[cfg(feature = "std")] +impl std::error::Error for DispatchError {} + /// An error relating to tokens when dispatching a transaction. -#[derive(scale_decode::DecodeAsType, Debug, thiserror::Error, PartialEq, Eq)] +#[derive(scale_decode::DecodeAsType, Display, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum TokenError { /// Funds are unavailable. - #[error("Funds are unavailable.")] + #[display(fmt = "Funds are unavailable.")] FundsUnavailable, /// Some part of the balance gives the only provider reference to the account and thus cannot be (re)moved. - #[error("Some part of the balance gives the only provider reference to the account and thus cannot be (re)moved.")] + #[display( + fmt = "Some part of the balance gives the only provider reference to the account and thus cannot be (re)moved." + )] OnlyProvider, /// Account cannot exist with the funds that would be given. - #[error("Account cannot exist with the funds that would be given.")] + #[display(fmt = "Account cannot exist with the funds that would be given.")] BelowMinimum, /// Account cannot be created. - #[error("Account cannot be created.")] + #[display(fmt = "Account cannot be created.")] CannotCreate, /// The asset in question is unknown. - #[error("The asset in question is unknown.")] + #[display(fmt = "The asset in question is unknown.")] UnknownAsset, /// Funds exist but are frozen. - #[error("Funds exist but are frozen.")] + #[display(fmt = "Funds exist but are frozen.")] Frozen, /// Operation is not supported by the asset. - #[error("Operation is not supported by the asset.")] + #[display(fmt = "Operation is not supported by the asset.")] Unsupported, /// Account cannot be created for a held balance. - #[error("Account cannot be created for a held balance.")] + #[display(fmt = "Account cannot be created for a held balance.")] CannotCreateHold, /// Withdrawal would cause unwanted loss of account. - #[error("Withdrawal would cause unwanted loss of account.")] + #[display(fmt = "Withdrawal would cause unwanted loss of account.")] NotExpendable, } +#[cfg(feature = "std")] +impl std::error::Error for TokenError {} + /// An error relating to arithmetic when dispatching a transaction. -#[derive(scale_decode::DecodeAsType, Debug, thiserror::Error, PartialEq, Eq)] +#[derive(scale_decode::DecodeAsType, Debug, Display, PartialEq, Eq)] #[non_exhaustive] pub enum ArithmeticError { /// Underflow. - #[error("Underflow.")] + #[display(fmt = "Underflow.")] Underflow, /// Overflow. - #[error("Overflow.")] + #[display(fmt = "Overflow.")] Overflow, /// Division by zero. - #[error("Division by zero.")] + #[display(fmt = "Division by zero.")] DivisionByZero, } +#[cfg(feature = "std")] +impl std::error::Error for ArithmeticError {} + /// An error relating to thr transactional layers when dispatching a transaction. -#[derive(scale_decode::DecodeAsType, Debug, thiserror::Error, PartialEq, Eq)] +#[derive(scale_decode::DecodeAsType, Debug, Display, PartialEq, Eq)] #[non_exhaustive] pub enum TransactionalError { /// Too many transactional layers have been spawned. - #[error("Too many transactional layers have been spawned.")] + #[display(fmt = "Too many transactional layers have been spawned.")] LimitReached, /// A transactional layer was expected, but does not exist. - #[error("A transactional layer was expected, but does not exist.")] + #[display(fmt = "A transactional layer was expected, but does not exist.")] NoLayer, } +#[cfg(feature = "std")] +impl std::error::Error for TransactionalError {} + /// Details about a module error that has occurred. -#[derive(Clone, thiserror::Error)] +#[derive(Clone)] #[non_exhaustive] pub struct ModuleError { metadata: Metadata, @@ -146,19 +161,22 @@ impl Eq for ModuleError {} /// Custom `Debug` implementation, ignores the very large `metadata` field, using it instead (as /// intended) to resolve the actual pallet and error names. This is much more useful for debugging. impl Debug for ModuleError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let details = self.details_string(); write!(f, "ModuleError(<{details}>)") } } -impl std::fmt::Display for ModuleError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Display for ModuleError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let details = self.details_string(); write!(f, "{details}") } } +#[cfg(feature = "std")] +impl std::error::Error for ModuleError {} + impl ModuleError { /// Return more details about this error. pub fn details(&self) -> Result { diff --git a/subxt/src/error/mod.rs b/subxt/src/error/mod.rs index f7f622bdc0..c958ab8589 100644 --- a/subxt/src/error/mod.rs +++ b/subxt/src/error/mod.rs @@ -21,69 +21,75 @@ pub use dispatch_error::{ pub use crate::config::ExtrinsicParamsError; pub use crate::metadata::Metadata; use crate::prelude::*; +use derive_more::{Display, From}; pub use scale_decode::Error as DecodeError; pub use scale_encode::Error as EncodeError; pub use subxt_metadata::TryFromError as MetadataTryFromError; - /// The underlying error enum, generic over the type held by the `Runtime` /// variant. Prefer to use the [`Error`] and [`Error`] aliases over /// using this type directly. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, Display, From)] #[non_exhaustive] pub enum Error { /// Io error. - #[error("Io error: {0}")] - Io(#[from] std::io::Error), + #[display(fmt = "Io error: {_0}")] + Io(std::io::Error), /// Codec error. - #[error("Scale codec error: {0}")] - Codec(#[from] codec::Error), + #[display(fmt = "Scale codec error: {_0}")] + Codec(codec::Error), /// Rpc error. - #[error("Rpc error: {0}")] - Rpc(#[from] RpcError), + #[cfg(feature = "std")] + #[display(fmt = "Rpc error: {_0}")] + Rpc(RpcError), /// Serde serialization error - #[error("Serde json error: {0}")] - Serialization(#[from] serde_json::error::Error), + #[display(fmt = "Serde json error: {_0}")] + Serialization(serde_json::error::Error), /// Error working with metadata. - #[error("Metadata error: {0}")] - Metadata(#[from] MetadataError), + #[display(fmt = "Metadata error: {_0}")] + Metadata(MetadataError), /// Error decoding metadata. - #[error("Metadata Decoding error: {0}")] - MetadataDecoding(#[from] MetadataTryFromError), + #[display(fmt = "Metadata Decoding error: {_0}")] + MetadataDecoding(MetadataTryFromError), /// Runtime error. - #[error("Runtime error: {0}")] - Runtime(#[from] DispatchError), + #[display(fmt = "Runtime error: {_0}")] + Runtime(DispatchError), /// Error decoding to a [`crate::dynamic::Value`]. - #[error("Error decoding into dynamic value: {0}")] - Decode(#[from] DecodeError), + #[display(fmt = "Error decoding into dynamic value: {_0}")] + Decode(DecodeError), /// Error encoding from a [`crate::dynamic::Value`]. - #[error("Error encoding from dynamic value: {0}")] - Encode(#[from] EncodeError), + #[display(fmt = "Error encoding from dynamic value: {_0}")] + Encode(EncodeError), /// Transaction progress error. - #[error("Transaction error: {0}")] - Transaction(#[from] TransactionError), + #[display(fmt = "Transaction error: {_0}")] + Transaction(TransactionError), /// Error constructing the appropriate extrinsic params. - #[error("Extrinsic params error: {0}")] - ExtrinsicParams(#[from] ExtrinsicParamsError), + #[display(fmt = "Extrinsic params error: {_0}")] + ExtrinsicParams(ExtrinsicParamsError), /// Block related error. - #[error("Block error: {0}")] - Block(#[from] BlockError), + #[display(fmt = "Block error: {_0}")] + Block(BlockError), /// An error encoding a storage address. - #[error("Error encoding storage address: {0}")] - StorageAddress(#[from] StorageAddressError), + #[display(fmt = "Error encoding storage address: {_0}")] + StorageAddress(StorageAddressError), /// The bytes representing an error that we were unable to decode. - #[error("An error occurred but it could not be decoded: {0:?}")] + #[display(fmt = "An error occurred but it could not be decoded: {_0:?}")] + #[from(ignore)] Unknown(Vec), /// Light client error. #[cfg(feature = "unstable-light-client")] #[cfg_attr(docsrs, doc(cfg(feature = "unstable-light-client")))] - #[error("An error occurred but it could not be decoded: {0}")] - LightClient(#[from] LightClientError), + #[display(fmt = "An error occurred but it could not be decoded: {_0}")] + LightClient(LightClientError), /// Other error. - #[error("Other error: {0}")] + #[display(fmt = "Other error: {_0}")] + #[from(ignore)] Other(String), } +#[cfg(feature = "std")] +impl std::error::Error for Error {} + impl<'a> From<&'a str> for Error { fn from(error: &'a str) -> Self { Error::Other(error.into()) @@ -104,26 +110,32 @@ impl From for Error { /// 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)] + +#[cfg(feature = "std")] +#[derive(Debug, Display)] #[non_exhaustive] pub enum RpcError { // Dev note: We need the error to be safely sent between threads // for `subscribe_to_block_headers_filling_in_gaps` and friends. /// Error related to the RPC client. - #[error("RPC error: {0}")] + #[display(fmt = "RPC error: {_0}")] ClientError(Box), /// This error signals that the request was rejected for some reason. /// The specific reason is provided. - #[error("RPC error: request rejected: {0}")] + #[display(fmt = "RPC error: request rejected: {_0}")] RequestRejected(String), /// The RPC subscription dropped. - #[error("RPC error: subscription dropped.")] + #[display(fmt = "RPC error: subscription dropped.")] SubscriptionDropped, /// The requested URL is insecure. - #[error("RPC error: insecure URL: {0}")] + #[display(fmt = "RPC error: insecure URL: {_0}")] InsecureUrl(String), } +#[cfg(feature = "std")] +impl std::error::Error for RpcError {} + +#[cfg(feature = "std")] impl RpcError { /// Create a `RequestRejected` error from anything that can be turned into a string. pub fn request_rejected>(s: S) -> RpcError { @@ -132,21 +144,25 @@ impl RpcError { } /// Block error -#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)] +#[derive(Clone, Debug, Eq, Display, PartialEq)] #[non_exhaustive] pub enum BlockError { /// An error containing the hash of the block that was not found. - #[error("Could not find a block with hash {0} (perhaps it was on a non-finalized fork?)")] + #[display( + fmt = "Could not find a block with hash {_0} (perhaps it was on a non-finalized fork?)" + )] NotFound(String), /// Extrinsic type ID cannot be resolved with the provided metadata. - #[error("Extrinsic type ID cannot be resolved with the provided metadata. Make sure this is a valid metadata")] + #[display( + fmt = "Extrinsic type ID cannot be resolved with the provided metadata. Make sure this is a valid metadata" + )] MissingType, /// Unsupported signature. - #[error("Unsupported extrinsic version, only version 4 is supported currently")] + #[display(fmt = "Unsupported extrinsic version, only version 4 is supported currently")] /// The extrinsic has an unsupported version. UnsupportedVersion(u8), /// Decoding error. - #[error("Cannot decode extrinsic: {0}")] + #[display(fmt = "Cannot decode extrinsic: {_0}")] DecodingError(codec::Error), } @@ -157,35 +173,42 @@ impl BlockError { BlockError::NotFound(hash) } } +#[cfg(feature = "std")] +impl std::error::Error for BlockError {} /// Transaction error. -#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)] +#[derive(Clone, Debug, Eq, Display, PartialEq)] #[non_exhaustive] pub enum TransactionError { /// The block hash that the transaction was added to could not be found. /// This is probably because the block was retracted before being finalized. - #[error("The block containing the transaction can no longer be found (perhaps it was on a non-finalized fork?)")] + #[display( + fmt = "The block containing the transaction can no longer be found (perhaps it was on a non-finalized fork?)" + )] BlockNotFound, /// An error happened on the node that the transaction was submitted to. - #[error("Error handling transaction: {0}")] + #[display(fmt = "Error handling transaction: {_0}")] Error(String), /// The transaction was deemed invalid. - #[error("The transaction is not valid: {0}")] + #[display(fmt = "The transaction is not valid: {_0}")] Invalid(String), /// The transaction was dropped. - #[error("The transaction was dropped: {0}")] + #[display(fmt = "The transaction was dropped: {_0}")] Dropped(String), } +#[cfg(feature = "std")] +impl std::error::Error for TransactionError {} + /// Something went wrong trying to encode a storage address. -#[derive(Clone, Debug, thiserror::Error)] +#[derive(Clone, Debug, Display)] #[non_exhaustive] pub enum StorageAddressError { /// Storage map type must be a composite type. - #[error("Storage map type must be a composite type")] + #[display(fmt = "Storage map type must be a composite type")] MapTypeMustBeTuple, /// Storage lookup does not have the expected number of keys. - #[error("Storage lookup requires {expected} keys but got {actual} keys")] + #[display(fmt = "Storage lookup requires {expected} keys but got {actual} keys")] WrongNumberOfKeys { /// The actual number of keys needed, based on the metadata. actual: usize, @@ -193,7 +216,9 @@ pub enum StorageAddressError { 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")] + #[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, @@ -202,53 +227,59 @@ pub enum StorageAddressError { }, } +#[cfg(feature = "std")] +impl std::error::Error for StorageAddressError {} + /// Something went wrong trying to access details in the metadata. -#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, Display)] #[non_exhaustive] pub enum MetadataError { /// The DispatchError type isn't available in the metadata - #[error("The DispatchError type isn't available")] + #[display(fmt = "The DispatchError type isn't available")] DispatchErrorNotFound, /// Type not found in metadata. - #[error("Type with ID {0} not found")] + #[display(fmt = "Type with ID {_0} not found")] TypeNotFound(u32), /// Pallet not found (index). - #[error("Pallet with index {0} not found")] + #[display(fmt = "Pallet with index {_0} not found")] PalletIndexNotFound(u8), /// Pallet not found (name). - #[error("Pallet with name {0} not found")] + #[display(fmt = "Pallet with name {_0} not found")] PalletNameNotFound(String), /// Variant not found. - #[error("Variant with index {0} not found")] + #[display(fmt = "Variant with index {_0} not found")] VariantIndexNotFound(u8), /// Constant not found. - #[error("Constant with name {0} not found")] + #[display(fmt = "Constant with name {_0} not found")] ConstantNameNotFound(String), /// Call not found. - #[error("Call with name {0} not found")] + #[display(fmt = "Call with name {_0} not found")] CallNameNotFound(String), /// Runtime trait not found. - #[error("Runtime trait with name {0} not found")] + #[display(fmt = "Runtime trait with name {_0} not found")] RuntimeTraitNotFound(String), /// Runtime method not found. - #[error("Runtime method with name {0} not found")] + #[display(fmt = "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}")] + #[display(fmt = "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}")] + #[display(fmt = "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}")] + #[display(fmt = "Storage details not found in pallet with name {_0}")] StorageNotFoundInPallet(String), /// Storage entry not found. - #[error("Storage entry {0} not found")] + #[display(fmt = "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")] + #[display(fmt = "The generated code is not compatible with the node")] IncompatibleCodegen, /// Custom value not found. - #[error("Custom value with name {0} not found")] + #[display(fmt = "Custom value with name {_0} not found")] CustomValueNameNotFound(String), } + +#[cfg(feature = "std")] +impl std::error::Error for MetadataError {} diff --git a/subxt/src/events/events_client.rs b/subxt/src/events/events_client.rs index 7b0dc1e2e9..8c8e8b489d 100644 --- a/subxt/src/events/events_client.rs +++ b/subxt/src/events/events_client.rs @@ -3,8 +3,8 @@ // see LICENSE for license details. use crate::backend::{Backend, BackendExt, BlockRef}; -use crate::{client::OnlineClientT, error::Error, events::Events, Config}; use crate::prelude::*; +use crate::{client::OnlineClientT, error::Error, events::Events, Config}; use derivative::Derivative; use std::future::Future; @@ -13,7 +13,7 @@ use std::future::Future; #[derivative(Clone(bound = "Client: Clone"))] pub struct EventsClient { client: Client, - _marker: std::marker::PhantomData, + _marker: PhantomData, } impl EventsClient { @@ -21,7 +21,7 @@ impl EventsClient { pub fn new(client: Client) -> Self { Self { client, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } } diff --git a/subxt/src/prelude.rs b/subxt/src/prelude.rs index 85d2641a4e..2bd5855fd2 100644 --- a/subxt/src/prelude.rs +++ b/subxt/src/prelude.rs @@ -26,25 +26,27 @@ cfg_if! { mem, num, ops, - string, + string::{String}, + str, sync, time, - vec::{vec, Vec}, + vec, rc, iter, }; + pub use std::vec::Vec; } else { pub use alloc::{ borrow, boxed::{Box}, collections, format, - string, + string::{String}, sync, - vec::{vec, Vec}, - rc + vec::{Vec}, + rc, }; - + pub use std::vec::Vec; pub use core::{ any, cmp, @@ -56,6 +58,7 @@ cfg_if! { ops, time, iter, + str, }; } } diff --git a/subxt/src/runtime_api/runtime_payload.rs b/subxt/src/runtime_api/runtime_payload.rs index b05258548d..8e79c0a9cb 100644 --- a/subxt/src/runtime_api/runtime_payload.rs +++ b/subxt/src/runtime_api/runtime_payload.rs @@ -2,7 +2,6 @@ // This file is dual-licensed as Apache-2.0 or GPL-3.0. // see LICENSE for license details. -use core::marker::PhantomData; use derivative::Derivative; use scale_encode::EncodeAsFields; use scale_value::Composite; @@ -10,8 +9,8 @@ use std::borrow::Cow; use crate::dynamic::DecodedValueThunk; use crate::error::MetadataError; -use crate::{metadata::DecodeWithMetadata, Error, Metadata}; use crate::prelude::*; +use crate::{metadata::DecodeWithMetadata, Error, Metadata}; /// This represents a runtime API payload that can call into the runtime of node. /// @@ -147,7 +146,7 @@ impl Payload { method_name: Cow::Borrowed(method_name), args_data, validation_hash: Some(hash), - _marker: std::marker::PhantomData, + _marker: PhantomData, } } diff --git a/subxt/src/storage/storage_address.rs b/subxt/src/storage/storage_address.rs index 78c6674cdc..3973251636 100644 --- a/subxt/src/storage/storage_address.rs +++ b/subxt/src/storage/storage_address.rs @@ -2,13 +2,13 @@ // This file is dual-licensed as Apache-2.0 or GPL-3.0. // see LICENSE for license details. +use crate::prelude::*; use crate::{ dynamic::DecodedValueThunk, error::{Error, MetadataError, StorageAddressError}, metadata::{DecodeWithMetadata, EncodeWithMetadata, Metadata}, utils::{Encoded, Static}, }; -use crate::prelude::*; use derivative::Derivative; use scale_info::TypeDef; use std::borrow::Cow; @@ -63,7 +63,7 @@ pub struct Address { entry_name: Cow<'static, str>, storage_entry_keys: Vec, validation_hash: Option<[u8; 32]>, - _marker: std::marker::PhantomData<(ReturnTy, Fetchable, Defaultable, Iterable)>, + _marker: PhantomData<(ReturnTy, Fetchable, Defaultable, Iterable)>, } /// A typical storage address constructed at runtime rather than via the `subxt` macro; this @@ -87,7 +87,7 @@ where entry_name: Cow::Owned(entry_name.into()), storage_entry_keys: storage_entry_keys.into_iter().collect(), validation_hash: None, - _marker: std::marker::PhantomData, + _marker: PhantomData, } } @@ -105,7 +105,7 @@ where entry_name: Cow::Borrowed(entry_name), storage_entry_keys: storage_entry_keys.into_iter().collect(), validation_hash: Some(hash), - _marker: std::marker::PhantomData, + _marker: PhantomData, } } @@ -185,7 +185,7 @@ where TypeDef::Tuple(tuple) => { either::Either::Left(tuple.fields.iter().map(|f| f.id)) } - _other => either::Either::Right(std::iter::once(*key_ty)), + _other => either::Either::Right(core::iter::once(*key_ty)), }; if type_ids.len() < self.storage_entry_keys.len() { diff --git a/subxt/src/tx/tx_client.rs b/subxt/src/tx/tx_client.rs index 57400facd9..cb569e9ffd 100644 --- a/subxt/src/tx/tx_client.rs +++ b/subxt/src/tx/tx_client.rs @@ -4,6 +4,7 @@ use std::borrow::Cow; +use crate::prelude::*; use crate::{ backend::{BackendExt, BlockRef, TransactionStatus}, client::{OfflineClientT, OnlineClientT}, @@ -13,7 +14,6 @@ use crate::{ tx::{Signer as SignerT, TxPayload, TxProgress}, utils::{Encoded, PhantomDataSendSync}, }; -use crate::prelude::*; use codec::{Compact, Decode, Encode}; use derivative::Derivative; use sp_core_hashing::blake2_256; @@ -386,7 +386,7 @@ where pub struct SubmittableExtrinsic { client: C, encoded: Encoded, - marker: std::marker::PhantomData, + marker: PhantomData, } impl SubmittableExtrinsic @@ -405,7 +405,7 @@ where Self { client, encoded: Encoded(tx_bytes), - marker: std::marker::PhantomData, + marker: PhantomData, } } diff --git a/subxt/src/tx/tx_progress.rs b/subxt/src/tx/tx_progress.rs index 45f8afa3b8..2616f009bd 100644 --- a/subxt/src/tx/tx_progress.rs +++ b/subxt/src/tx/tx_progress.rs @@ -4,8 +4,7 @@ //! Types representing extrinsics/transactions that have been submitted to a node. -use std::task::Poll; - +use crate::prelude::*; use crate::utils::strip_compact_prefix; use crate::{ backend::{BlockRef, StreamOfResults, TransactionStatus as BackendTxStatus}, @@ -14,7 +13,7 @@ use crate::{ events::EventsClient, Config, }; -use crate::prelude::*; +use core::task::Poll; use derivative::Derivative; use futures::{Stream, StreamExt}; @@ -25,8 +24,8 @@ pub struct TxProgress { client: C, } -impl std::fmt::Debug for TxProgress { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for TxProgress { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TxProgress") .field("sub", &"") .field("ext_hash", &self.ext_hash) @@ -125,9 +124,9 @@ impl Stream for TxProgress { type Item = Result, Error>; fn poll_next( - mut self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll> { + mut self: core::pin::Pin<&mut Self>, + cx: &mut core::task::Context<'_>, + ) -> core::task::Poll> { let sub = match self.sub.as_mut() { Some(sub) => sub, None => return Poll::Ready(None), @@ -169,7 +168,7 @@ impl Stream for TxProgress { /// Possible transaction statuses returned from our [`TxProgress::next()`] call. #[derive(Derivative)] -#[derivative(Debug(bound = "C: std::fmt::Debug"))] +#[derivative(Debug(bound = "C: fmt::Debug"))] pub enum TxStatus { /// Transaction is part of the future queue. Validated, @@ -223,7 +222,7 @@ impl TxStatus { /// This struct represents a transaction that has made it into a block. #[derive(Derivative)] -#[derivative(Debug(bound = "C: std::fmt::Debug"))] +#[derivative(Debug(bound = "C: fmt::Debug"))] pub struct TxInBlock { block_ref: BlockRef, ext_hash: T::Hash, diff --git a/subxt/src/utils/account_id.rs b/subxt/src/utils/account_id.rs index faa3dbbd4d..907257e471 100644 --- a/subxt/src/utils/account_id.rs +++ b/subxt/src/utils/account_id.rs @@ -6,7 +6,9 @@ //! 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 crate::prelude::*; 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 @@ -100,16 +102,16 @@ impl AccountId32 { } /// An error obtained from trying to interpret an SS58 encoded string into an AccountId32 -#[derive(thiserror::Error, Clone, Copy, Eq, PartialEq, Debug)] +#[derive(Display, Clone, Copy, Eq, PartialEq, Debug)] #[allow(missing_docs)] pub enum FromSs58Error { - #[error("Base 58 requirement is violated")] + #[display(fmt = "Base 58 requirement is violated")] BadBase58, - #[error("Length is bad")] + #[display(fmt = "Length is bad")] BadLength, - #[error("Invalid checksum")] + #[display(fmt = "Invalid checksum")] InvalidChecksum, - #[error("Invalid SS58 prefix byte.")] + #[display(fmt = "Invalid SS58 prefix byte.")] InvalidPrefix, } @@ -142,13 +144,13 @@ impl<'de> Deserialize<'de> for AccountId32 { } } -impl std::fmt::Display for AccountId32 { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { +impl fmt::Display for AccountId32 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_ss58check()) } } -impl std::str::FromStr for AccountId32 { +impl crate::prelude::str::FromStr for AccountId32 { type Err = FromSs58Error; fn from_str(s: &str) -> Result { AccountId32::from_ss58check(s) diff --git a/subxt/src/utils/bits.rs b/subxt/src/utils/bits.rs index ed830a0dea..38ec574a83 100644 --- a/subxt/src/utils/bits.rs +++ b/subxt/src/utils/bits.rs @@ -4,13 +4,13 @@ //! Generic `scale_bits` over `bitvec`-like `BitOrder` and `BitFormat` types. +use crate::prelude::*; use codec::{Compact, Input}; use scale_bits::{ scale::format::{Format, OrderFormat, StoreFormat}, Bits, }; use scale_decode::IntoVisitor; -use std::marker::PhantomData; /// Associates `bitvec::store::BitStore` trait with corresponding, type-erased `scale_bits::StoreFormat` enum. /// @@ -144,7 +144,7 @@ impl codec::Encode for DecodedBits(std::marker::PhantomData<(S, O)>); +pub struct DecodedBitsVisitor(PhantomData<(S, O)>); impl scale_decode::Visitor for DecodedBitsVisitor { type Value<'scale, 'info> = DecodedBits; type Error = scale_decode::Error; diff --git a/subxt/src/utils/mod.rs b/subxt/src/utils/mod.rs index e5e08754e6..95fd1ad64e 100644 --- a/subxt/src/utils/mod.rs +++ b/subxt/src/utils/mod.rs @@ -14,8 +14,8 @@ mod unchecked_extrinsic; mod wrapper_opaque; use crate::error::RpcError; -use crate::Error; use crate::prelude::*; +use crate::Error; use codec::{Compact, Decode, Encode}; use derivative::Derivative; use url::Url; @@ -76,7 +76,7 @@ pub fn validate_url_is_secure(url: &str) -> Result<(), Error> { } } -/// A version of [`std::marker::PhantomData`] that is also Send and Sync (which is fine +/// A version of [`PhantomData`] that is also Send and Sync (which is fine /// because regardless of the generic param, it is always possible to Send + Sync this /// 0 size type). #[derive(Derivative, Encode, Decode, scale_info::TypeInfo)] diff --git a/subxt/src/utils/multi_address.rs b/subxt/src/utils/multi_address.rs index 9b1e556fa9..c056d04e0f 100644 --- a/subxt/src/utils/multi_address.rs +++ b/subxt/src/utils/multi_address.rs @@ -6,6 +6,7 @@ //! This doesn't contain much functionality itself, but is easy to convert to/from an `sp_runtime::MultiAddress` //! for instance, to gain functionality without forcing a dependency on Substrate crates here. +use crate::prelude::*; use codec::{Decode, Encode}; /// A multi-format address wrapper for on-chain accounts. This is a simplified version of Substrate's diff --git a/subxt/src/utils/static_type.rs b/subxt/src/utils/static_type.rs index 2d13e61eba..ad34e821f2 100644 --- a/subxt/src/utils/static_type.rs +++ b/subxt/src/utils/static_type.rs @@ -2,6 +2,7 @@ // This file is dual-licensed as Apache-2.0 or GPL-3.0. // see LICENSE for license details. +use crate::prelude::*; use codec::{Decode, Encode}; use scale_decode::{visitor::DecodeAsTypeResult, IntoVisitor, Visitor}; use scale_encode::EncodeAsType; @@ -29,7 +30,7 @@ impl EncodeAsType for Static { } } -pub struct StaticDecodeAsTypeVisitor(std::marker::PhantomData); +pub struct StaticDecodeAsTypeVisitor(PhantomData); impl Visitor for StaticDecodeAsTypeVisitor { type Value<'scale, 'info> = Static; @@ -52,7 +53,7 @@ impl Visitor for StaticDecodeAsTypeVisitor { impl IntoVisitor for Static { type Visitor = StaticDecodeAsTypeVisitor; fn into_visitor() -> Self::Visitor { - StaticDecodeAsTypeVisitor(std::marker::PhantomData) + StaticDecodeAsTypeVisitor(PhantomData) } } @@ -64,14 +65,14 @@ impl From for Static { } // Static is just a marker type and should be as transparent as possible: -impl std::ops::Deref for Static { +impl ops::Deref for Static { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl std::ops::DerefMut for Static { +impl ops::DerefMut for Static { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } diff --git a/subxt/src/utils/unchecked_extrinsic.rs b/subxt/src/utils/unchecked_extrinsic.rs index 882b490bed..a1f0b18151 100644 --- a/subxt/src/utils/unchecked_extrinsic.rs +++ b/subxt/src/utils/unchecked_extrinsic.rs @@ -9,8 +9,7 @@ //! runtime APIs. Deriving `EncodeAsType` would lead to the inner //! bytes to be re-encoded (length prefixed). -use std::marker::PhantomData; - +use crate::prelude::*; use codec::{Decode, Encode}; use scale_decode::{visitor::DecodeAsTypeResult, DecodeAsType, IntoVisitor, Visitor}; diff --git a/subxt/src/utils/wrapper_opaque.rs b/subxt/src/utils/wrapper_opaque.rs index 0af27d2ee4..a6661092bc 100644 --- a/subxt/src/utils/wrapper_opaque.rs +++ b/subxt/src/utils/wrapper_opaque.rs @@ -3,6 +3,7 @@ // see LICENSE for license details. use super::PhantomDataSendSync; +use crate::prelude::*; use codec::{Compact, Decode, DecodeAll, Encode}; use derivative::Derivative; use scale_decode::{IntoVisitor, Visitor}; @@ -108,7 +109,7 @@ impl EncodeAsType for WrapperKeepOpaque { } } -pub struct WrapperKeepOpaqueVisitor(std::marker::PhantomData); +pub struct WrapperKeepOpaqueVisitor(PhantomData); impl Visitor for WrapperKeepOpaqueVisitor { type Value<'scale, 'info> = WrapperKeepOpaque; type Error = scale_decode::Error;