error type implementations

This commit is contained in:
Tadeo hepperle
2024-01-22 18:53:04 +01:00
parent a349daaf45
commit 2c40b14230
32 changed files with 269 additions and 207 deletions
Generated
+1 -1
View File
@@ -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",
+1
View File
@@ -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"] }
+1 -1
View File
@@ -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 }
+1 -1
View File
@@ -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:
+3 -3
View File
@@ -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<T> {
client: RpcClient,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
impl<T: Config> LegacyRpcMethods<T> {
@@ -28,7 +28,7 @@ impl<T: Config> LegacyRpcMethods<T> {
pub fn new(client: RpcClient) -> Self {
LegacyRpcMethods {
client,
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
+2 -2
View File
@@ -181,7 +181,7 @@ impl RpcParams {
/// [`StreamExt`] extension trait.
pub struct RpcSubscription<Res> {
inner: RawRpcSubscription,
_marker: std::marker::PhantomData<Res>,
_marker: PhantomData<Res>,
}
impl<Res> std::fmt::Debug for RpcSubscription<Res> {
@@ -198,7 +198,7 @@ impl<Res> RpcSubscription<Res> {
pub fn new(inner: RawRpcSubscription) -> Self {
Self {
inner,
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
+3 -3
View File
@@ -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<T> {
max_block_life: usize,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
impl<T: Config> Default for UnstableBackendBuilder<T> {
@@ -57,7 +57,7 @@ impl<T: Config> UnstableBackendBuilder<T> {
pub fn new() -> Self {
Self {
max_block_life: usize::MAX,
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
+7 -6
View File
@@ -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<T> {
client: RpcClient,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
impl<T: Config> UnstableRpcMethods<T> {
@@ -31,7 +31,7 @@ impl<T: Config> UnstableRpcMethods<T> {
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 <https://github.com/paritytech/json-rpc-interface-spec/issues/83>
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<N>(std::marker::PhantomData<N>);
struct NumberVisitor<N>(PhantomData<N>);
impl<'de, N: From<u64>> Visitor<'de> for NumberVisitor<N> {
type Value = N;
@@ -794,11 +795,11 @@ pub(crate) mod unsigned_number_as_string {
///
/// Adapted from <https://tikv.github.io/doc/serde_with/rust/hashmap_as_tuple_list>
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<HashMap<K, V, BH>, D::Error>
+13 -13
View File
@@ -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<T: Config, C> {
cached_events: CachedEvents<T>,
/// Subxt metadata to fetch the extrinsic metadata.
metadata: Metadata,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
/// 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<T: Config> ExtrinsicEvents<T> {
pub struct ExtrinsicSignedExtensions<'a, T: Config> {
bytes: &'a [u8],
metadata: &'a Metadata,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
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<T>,
_marker: PhantomData<T>,
}
impl<'a, T: Config> ExtrinsicSignedExtension<'a, T> {
+3 -3
View File
@@ -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<T: Config> {
max_subscriptions: u32,
bootnodes: Option<Vec<serde_json::Value>>,
potential_relay_chains: Option<Vec<smoldot::ChainId>>,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
impl<T: Config> Default for LightClientBuilder<T> {
@@ -30,7 +30,7 @@ impl<T: Config> Default for LightClientBuilder<T> {
max_subscriptions: 1024,
bootnodes: None,
potential_relay_chains: None,
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
}
+1 -1
View File
@@ -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};
+11 -5
View File
@@ -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<dyn std::error::Error + Send + Sync + 'static>;
+3 -3
View File
@@ -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<T: Config> SignedExtension<T> for ChargeTransactionPayment {
/// is a sensible default, and allows for a single configuration to work across multiple chains.
pub struct AnyOf<T, Params> {
params: Vec<Box<dyn ExtrinsicParamsEncoder>>,
_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
})
}
}
+4 -4
View File
@@ -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<ReturnTy> {
pallet_name: Cow<'static, str>,
constant_name: Cow<'static, str>,
constant_hash: Option<[u8; 32]>,
_marker: std::marker::PhantomData<ReturnTy>,
_marker: PhantomData<ReturnTy>,
}
/// The type of address typically used to return dynamic constant values.
@@ -47,7 +47,7 @@ impl<ReturnTy> Address<ReturnTy> {
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<ReturnTy> Address<ReturnTy> {
pallet_name: Cow::Borrowed(pallet_name),
constant_name: Cow::Borrowed(constant_name),
constant_hash: Some(hash),
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
+3 -3
View File
@@ -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<T, Client> {
client: Client,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
impl<T, Client> ConstantsClient<T, Client> {
@@ -25,7 +25,7 @@ impl<T, Client> ConstantsClient<T, Client> {
pub fn new(client: Client) -> Self {
Self {
client,
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
}
@@ -1,5 +1,5 @@
use derivative::Derivative;
use std::marker::PhantomData;
use PhantomData;
use crate::dynamic::DecodedValueThunk;
use crate::metadata::DecodeWithMetadata;
@@ -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<T, Client> {
client: Client,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
impl<T, Client> CustomValuesClient<T, Client> {
@@ -19,7 +19,7 @@ impl<T, Client> CustomValuesClient<T, Client> {
pub fn new(client: Client) -> Self {
Self {
client,
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
}
+56 -38
View File
@@ -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<ModuleErrorDetails, MetadataError> {
+98 -67
View File
@@ -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<E>`] 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<u8>),
/// 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<std::convert::Infallible> 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<dyn std::error::Error + Send + Sync + 'static>),
/// 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: Into<String>>(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 {}
+3 -3
View File
@@ -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<T, Client> {
client: Client,
_marker: std::marker::PhantomData<T>,
_marker: PhantomData<T>,
}
impl<T, Client> EventsClient<T, Client> {
@@ -21,7 +21,7 @@ impl<T, Client> EventsClient<T, Client> {
pub fn new(client: Client) -> Self {
Self {
client,
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
}
+9 -6
View File
@@ -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,
};
}
}
+2 -3
View File
@@ -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<ReturnTy, ArgsData> Payload<ArgsData, ReturnTy> {
method_name: Cow::Borrowed(method_name),
args_data,
validation_hash: Some(hash),
_marker: std::marker::PhantomData,
_marker: PhantomData,
}
}
+5 -5
View File
@@ -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<StorageKey, ReturnTy, Fetchable, Defaultable, Iterable> {
entry_name: Cow<'static, str>,
storage_entry_keys: Vec<StorageKey>,
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() {
+3 -3
View File
@@ -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<T, C> {
client: C,
encoded: Encoded,
marker: std::marker::PhantomData<T>,
marker: PhantomData<T>,
}
impl<T, C> SubmittableExtrinsic<T, C>
@@ -405,7 +405,7 @@ where
Self {
client,
encoded: Encoded(tx_bytes),
marker: std::marker::PhantomData,
marker: PhantomData,
}
}
+9 -10
View File
@@ -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<T: Config, C> {
client: C,
}
impl<T: Config, C> std::fmt::Debug for TxProgress<T, C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl<T: Config, C> fmt::Debug for TxProgress<T, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TxProgress")
.field("sub", &"<subscription>")
.field("ext_hash", &self.ext_hash)
@@ -125,9 +124,9 @@ impl<T: Config, C: Clone> Stream for TxProgress<T, C> {
type Item = Result<TxStatus<T, C>, Error>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
mut self: core::pin::Pin<&mut Self>,
cx: &mut core::task::Context<'_>,
) -> core::task::Poll<Option<Self::Item>> {
let sub = match self.sub.as_mut() {
Some(sub) => sub,
None => return Poll::Ready(None),
@@ -169,7 +168,7 @@ impl<T: Config, C: Clone> Stream for TxProgress<T, C> {
/// 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<T: Config, C> {
/// Transaction is part of the future queue.
Validated,
@@ -223,7 +222,7 @@ impl<T: Config, C> TxStatus<T, C> {
/// 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<T: Config, C> {
block_ref: BlockRef<T::Hash>,
ext_hash: T::Hash,
+10 -8
View File
@@ -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<Self, Self::Err> {
AccountId32::from_ss58check(s)
+2 -2
View File
@@ -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<Store: BitStore, Order: BitOrder> codec::Encode for DecodedBits<Store, Orde
}
#[doc(hidden)]
pub struct DecodedBitsVisitor<S, O>(std::marker::PhantomData<(S, O)>);
pub struct DecodedBitsVisitor<S, O>(PhantomData<(S, O)>);
impl<Store, Order> scale_decode::Visitor for DecodedBitsVisitor<Store, Order> {
type Value<'scale, 'info> = DecodedBits<Store, Order>;
type Error = scale_decode::Error;
+2 -2
View File
@@ -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)]
+1
View File
@@ -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
+5 -4
View File
@@ -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<T: Encode> EncodeAsType for Static<T> {
}
}
pub struct StaticDecodeAsTypeVisitor<T>(std::marker::PhantomData<T>);
pub struct StaticDecodeAsTypeVisitor<T>(PhantomData<T>);
impl<T: Decode> Visitor for StaticDecodeAsTypeVisitor<T> {
type Value<'scale, 'info> = Static<T>;
@@ -52,7 +53,7 @@ impl<T: Decode> Visitor for StaticDecodeAsTypeVisitor<T> {
impl<T: Decode> IntoVisitor for Static<T> {
type Visitor = StaticDecodeAsTypeVisitor<T>;
fn into_visitor() -> Self::Visitor {
StaticDecodeAsTypeVisitor(std::marker::PhantomData)
StaticDecodeAsTypeVisitor(PhantomData)
}
}
@@ -64,14 +65,14 @@ impl<T> From<T> for Static<T> {
}
// Static<T> is just a marker type and should be as transparent as possible:
impl<T> std::ops::Deref for Static<T> {
impl<T> ops::Deref for Static<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> std::ops::DerefMut for Static<T> {
impl<T> ops::DerefMut for Static<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
+1 -2
View File
@@ -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};
+2 -1
View File
@@ -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<T> EncodeAsType for WrapperKeepOpaque<T> {
}
}
pub struct WrapperKeepOpaqueVisitor<T>(std::marker::PhantomData<T>);
pub struct WrapperKeepOpaqueVisitor<T>(PhantomData<T>);
impl<T> Visitor for WrapperKeepOpaqueVisitor<T> {
type Value<'scale, 'info> = WrapperKeepOpaque<T>;
type Error = scale_decode::Error;