diff --git a/client/src/lib.rs b/client/src/lib.rs index e6c02ad05ee..bfbbe3e9c3e 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -21,50 +21,26 @@ use async_std::task; use futures::{ channel::mpsc, - compat::{ - Compat01As03, - Sink01CompatExt, - Stream01CompatExt, - }, - future::{ - select, - FutureExt, - }, + compat::{Compat01As03, Sink01CompatExt, Stream01CompatExt}, + future::{select, FutureExt}, sink::SinkExt, stream::StreamExt, }; use futures01::sync::mpsc as mpsc01; use jsonrpsee::{ - common::{ - Request, - Response, - }, + common::{Request, Response}, transport::TransportClient, }; use sc_network::config::TransportConfig; pub use sc_service::{ - config::{ - DatabaseConfig, - KeystoreConfig, - }, + config::{DatabaseConfig, KeystoreConfig}, Error as ServiceError, }; use sc_service::{ - config::{ - NetworkConfiguration, - TaskType, - TelemetryEndpoints, - }, - ChainSpec, - Configuration, - RpcHandlers, - RpcSession, - TaskManager, -}; -use std::{ - future::Future, - pin::Pin, + config::{NetworkConfiguration, TaskType, TelemetryEndpoints}, + ChainSpec, Configuration, RpcHandlers, RpcSession, TaskManager, }; +use std::{future::Future, pin::Pin}; use thiserror::Error; /// Error thrown by the client. @@ -177,11 +153,9 @@ impl From for sc_service::Role { fn from(role: Role) -> Self { match role { Role::Light => Self::Light, - Role::Authority(_) => { - Self::Authority { - sentry_nodes: Default::default(), - } - } + Role::Authority(_) => Self::Authority { + sentry_nodes: Default::default(), + }, } } } @@ -250,11 +224,9 @@ impl SubxtClientConfig { impl_version: self.impl_version.to_string(), chain_spec: Box::new(self.chain_spec), role: self.role.into(), - task_executor: (move |fut, ty| { - match ty { - TaskType::Async => task::spawn(fut), - TaskType::Blocking => task::spawn_blocking(|| task::block_on(fut)), - } + task_executor: (move |fut, ty| match ty { + TaskType::Async => task::spawn(fut), + TaskType::Blocking => task::spawn_blocking(|| task::block_on(fut)), }) .into(), database: self.db, @@ -308,9 +280,7 @@ mod tests { use async_std::path::Path; use sp_keyring::AccountKeyring; use substrate_subxt::{ - balances::TransferCallExt, - ClientBuilder, - KusamaRuntime as NodeTemplateRuntime, + balances::TransferCallExt, ClientBuilder, KusamaRuntime as NodeTemplateRuntime, PairSigner, }; use tempdir::TempDir; diff --git a/examples/fetch_all_accounts.rs b/examples/fetch_all_accounts.rs index b202f2992fa..a63c12eac44 100644 --- a/examples/fetch_all_accounts.rs +++ b/examples/fetch_all_accounts.rs @@ -14,11 +14,7 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use substrate_subxt::{ - system::AccountStoreExt, - ClientBuilder, - DefaultNodeRuntime, -}; +use substrate_subxt::{system::AccountStoreExt, ClientBuilder, DefaultNodeRuntime}; #[async_std::main] async fn main() -> Result<(), Box> { diff --git a/examples/fetch_remote.rs b/examples/fetch_remote.rs index e2c0af06f12..d9948cc30f3 100644 --- a/examples/fetch_remote.rs +++ b/examples/fetch_remote.rs @@ -14,10 +14,7 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use substrate_subxt::{ - ClientBuilder, - KusamaRuntime, -}; +use substrate_subxt::{ClientBuilder, KusamaRuntime}; #[async_std::main] async fn main() -> Result<(), Box> { diff --git a/examples/kusama_balance_transfer.rs b/examples/kusama_balance_transfer.rs index dba35b8771a..5296189eecf 100644 --- a/examples/kusama_balance_transfer.rs +++ b/examples/kusama_balance_transfer.rs @@ -15,12 +15,7 @@ // along with substrate-subxt. If not, see . use sp_keyring::AccountKeyring; -use substrate_subxt::{ - balances::*, - ClientBuilder, - KusamaRuntime, - PairSigner, -}; +use substrate_subxt::{balances::*, ClientBuilder, KusamaRuntime, PairSigner}; #[async_std::main] async fn main() -> Result<(), Box> { diff --git a/examples/submit_and_watch.rs b/examples/submit_and_watch.rs index c75137f994b..6730e4eadf4 100644 --- a/examples/submit_and_watch.rs +++ b/examples/submit_and_watch.rs @@ -16,13 +16,8 @@ use sp_keyring::AccountKeyring; use substrate_subxt::{ - balances::{ - TransferCallExt, - TransferEventExt, - }, - ClientBuilder, - DefaultNodeRuntime, - PairSigner, + balances::{TransferCallExt, TransferEventExt}, + ClientBuilder, DefaultNodeRuntime, PairSigner, }; #[async_std::main] diff --git a/examples/transfer_subscribe.rs b/examples/transfer_subscribe.rs index 706d3fdc6f3..5f35aa46dc4 100644 --- a/examples/transfer_subscribe.rs +++ b/examples/transfer_subscribe.rs @@ -16,17 +16,9 @@ use sp_keyring::AccountKeyring; use substrate_subxt::{ - balances::{ - BalancesEventsDecoder, - TransferCallExt, - TransferEvent, - }, + balances::{BalancesEventsDecoder, TransferCallExt, TransferEvent}, sp_core::Decode, - ClientBuilder, - DefaultNodeRuntime, - EventSubscription, - EventsDecoder, - PairSigner, + ClientBuilder, DefaultNodeRuntime, EventSubscription, EventsDecoder, PairSigner, }; #[async_std::main] diff --git a/proc-macro/src/call.rs b/proc-macro/src/call.rs index cedf993fe01..51a42840da1 100644 --- a/proc-macro/src/call.rs +++ b/proc-macro/src/call.rs @@ -15,15 +15,9 @@ // along with substrate-subxt. If not, see . use crate::utils; -use heck::{ - CamelCase, - SnakeCase, -}; +use heck::{CamelCase, SnakeCase}; use proc_macro2::TokenStream; -use quote::{ - format_ident, - quote, -}; +use quote::{format_ident, quote}; use synstructure::Structure; pub fn call(s: Structure) -> TokenStream { diff --git a/proc-macro/src/event.rs b/proc-macro/src/event.rs index 6c03551fd0a..bab2eac6694 100644 --- a/proc-macro/src/event.rs +++ b/proc-macro/src/event.rs @@ -15,15 +15,9 @@ // along with substrate-subxt. If not, see . use crate::utils; -use heck::{ - CamelCase, - SnakeCase, -}; +use heck::{CamelCase, SnakeCase}; use proc_macro2::TokenStream; -use quote::{ - format_ident, - quote, -}; +use quote::{format_ident, quote}; use synstructure::Structure; pub fn event(s: Structure) -> TokenStream { diff --git a/proc-macro/src/lib.rs b/proc-macro/src/lib.rs index c6daa1e68a8..a05334c946c 100644 --- a/proc-macro/src/lib.rs +++ b/proc-macro/src/lib.rs @@ -25,10 +25,7 @@ mod utils; use proc_macro::TokenStream; use proc_macro_error::proc_macro_error; -use synstructure::{ - decl_derive, - Structure, -}; +use synstructure::{decl_derive, Structure}; /// Register type sizes for [EventsDecoder](struct.EventsDecoder.html) and set the `MODULE`. /// diff --git a/proc-macro/src/module.rs b/proc-macro/src/module.rs index b1d989235be..11c559b2251 100644 --- a/proc-macro/src/module.rs +++ b/proc-macro/src/module.rs @@ -18,14 +18,8 @@ use crate::utils; use heck::SnakeCase; use proc_macro2::TokenStream; use proc_macro_error::abort; -use quote::{ - format_ident, - quote, -}; -use syn::parse::{ - Parse, - ParseStream, -}; +use quote::{format_ident, quote}; +use syn::parse::{Parse, ParseStream}; mod kw { use syn::custom_keyword; @@ -54,7 +48,7 @@ fn ignore(attrs: &[syn::Attribute]) -> bool { .map_err(|err| abort!("{}", err)) .unwrap(); if !attrs.attrs.is_empty() { - return true + return true; } } } @@ -76,7 +70,7 @@ pub fn module(_args: TokenStream, tokens: TokenStream) -> TokenStream { input } else { // handle #[module(ignore)] by just returning the tokens - return tokens + return tokens; }; let subxt = utils::use_crate("substrate-subxt"); @@ -99,7 +93,7 @@ pub fn module(_args: TokenStream, tokens: TokenStream) -> TokenStream { let types = input.items.iter().filter_map(|item| { if let syn::TraitItem::Type(ty) = item { if ignore(&ty.attrs) { - return None + return None; } let ident = &ty.ident; let ident_str = ident.to_string(); diff --git a/proc-macro/src/store.rs b/proc-macro/src/store.rs index 19c4568f4a3..00e69393d1c 100644 --- a/proc-macro/src/store.rs +++ b/proc-macro/src/store.rs @@ -15,20 +15,11 @@ // along with substrate-subxt. If not, see . use crate::utils; -use heck::{ - CamelCase, - SnakeCase, -}; +use heck::{CamelCase, SnakeCase}; use proc_macro2::TokenStream; use proc_macro_error::abort; -use quote::{ - format_ident, - quote, -}; -use syn::parse::{ - Parse, - ParseStream, -}; +use quote::{format_ident, quote}; +use syn::parse::{Parse, ParseStream}; use synstructure::Structure; mod kw { diff --git a/proc-macro/src/test.rs b/proc-macro/src/test.rs index fc5ebfeb52a..7a6c4a43f0e 100644 --- a/proc-macro/src/test.rs +++ b/proc-macro/src/test.rs @@ -17,15 +17,9 @@ use crate::utils; use proc_macro2::TokenStream; use proc_macro_error::abort; -use quote::{ - format_ident, - quote, -}; +use quote::{format_ident, quote}; use syn::{ - parse::{ - Parse, - ParseStream, - }, + parse::{Parse, ParseStream}, punctuated::Punctuated, }; diff --git a/proc-macro/src/utils.rs b/proc-macro/src/utils.rs index a595d42fe6f..e52c70a80c4 100644 --- a/proc-macro/src/utils.rs +++ b/proc-macro/src/utils.rs @@ -14,25 +14,13 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use proc_macro2::{ - Span, - TokenStream, -}; -use quote::{ - format_ident, - quote, -}; +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote}; use syn::{ - parse::{ - Parse, - ParseStream, - }, + parse::{Parse, ParseStream}, punctuated::Punctuated, }; -use synstructure::{ - BindingInfo, - Structure, -}; +use synstructure::{BindingInfo, Structure}; pub fn use_crate(name: &str) -> syn::Ident { opt_crate(name).unwrap_or_else(|| syn::Ident::new("crate", Span::call_site())) @@ -151,18 +139,16 @@ pub fn type_params(generics: &syn::Generics) -> Vec { generics .params .iter() - .filter_map(|g| { - match g { - syn::GenericParam::Type(p) => { - let ident = &p.ident; - Some(quote!(#ident)) - } - syn::GenericParam::Lifetime(p) => { - let lifetime = &p.lifetime; - Some(quote!(#lifetime)) - } - syn::GenericParam::Const(_) => None, + .filter_map(|g| match g { + syn::GenericParam::Type(p) => { + let ident = &p.ident; + Some(quote!(#ident)) + } + syn::GenericParam::Lifetime(p) => { + let lifetime = &p.lifetime; + Some(quote!(#lifetime)) } + syn::GenericParam::Const(_) => None, }) .collect() } @@ -173,7 +159,7 @@ pub fn parse_option(ty: &syn::Type) -> Option { if &seg.ident == "Option" { if let syn::PathArguments::AngleBracketed(args) = &seg.arguments { if let Some(syn::GenericArgument::Type(ty)) = args.args.first() { - return Some(ty.clone()) + return Some(ty.clone()); } } } diff --git a/proc-macro/tests/balances.rs b/proc-macro/tests/balances.rs index 0f167e98037..fc899e93051 100644 --- a/proc-macro/tests/balances.rs +++ b/proc-macro/tests/balances.rs @@ -17,26 +17,13 @@ #[macro_use] extern crate substrate_subxt; -use codec::{ - Codec, - Decode, - Encode, -}; +use codec::{Codec, Decode, Encode}; use sp_keyring::AccountKeyring; use std::fmt::Debug; use substrate_subxt::{ - sp_runtime::traits::{ - AtLeast32Bit, - MaybeSerialize, - Member, - }, - system::{ - System, - SystemEventsDecoder, - }, - ClientBuilder, - KusamaRuntime, - PairSigner, + sp_runtime::traits::{AtLeast32Bit, MaybeSerialize, Member}, + system::{System, SystemEventsDecoder}, + ClientBuilder, KusamaRuntime, PairSigner, }; #[module] diff --git a/src/error.rs b/src/error.rs index 195a2d22da0..e3f0dca0814 100644 --- a/src/error.rs +++ b/src/error.rs @@ -14,21 +14,12 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use jsonrpsee::{ - client::RequestError, - transport::ws::WsNewDnsError, -}; +use jsonrpsee::{client::RequestError, transport::ws::WsNewDnsError}; use sp_core::crypto::SecretStringError; -use sp_runtime::{ - transaction_validity::TransactionValidityError, - DispatchError, -}; +use sp_runtime::{transaction_validity::TransactionValidityError, DispatchError}; use thiserror::Error; -use crate::metadata::{ - Metadata, - MetadataError, -}; +use crate::metadata::{Metadata, MetadataError}; /// Error enum. #[derive(Debug, Error)] diff --git a/src/events.rs b/src/events.rs index 9a05de14cc5..0d7656e3742 100644 --- a/src/events.rs +++ b/src/events.rs @@ -14,41 +14,18 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use codec::{ - Codec, - Compact, - Decode, - Encode, - Input, - Output, -}; +use codec::{Codec, Compact, Decode, Encode, Input, Output}; use frame_support::dispatch::DispatchInfo; -use sp_runtime::{ - DispatchError, - DispatchResult, -}; +use sp_runtime::{DispatchError, DispatchResult}; use std::{ - collections::{ - HashMap, - HashSet, - }, - marker::{ - PhantomData, - Send, - }, + collections::{HashMap, HashSet}, + marker::{PhantomData, Send}, }; use crate::{ - error::{ - Error, - RuntimeError, - }, - metadata::{ - EventArg, - Metadata, - }, - Phase, - System, + error::{Error, RuntimeError}, + metadata::{EventArg, Metadata}, + Phase, System, }; /// Raw bytes for an Event @@ -154,6 +131,11 @@ impl EventsDecoder { self.decode_raw_bytes(&[*arg.clone()], input, output)? } } + EventArg::Option(arg) => { + if let Some(item) = arg { + self.decode_raw_bytes(&[*item.clone()], input, output)? + } + } EventArg::Tuple(args) => self.decode_raw_bytes(args, input, output)?, EventArg::Primitive(name) => { let result = match name.as_str() { @@ -166,14 +148,14 @@ impl EventsDecoder { output.write(&buf); Ok(()) } else { - return Err(Error::TypeSizeUnavailable(name.to_owned())) + return Err(Error::TypeSizeUnavailable(name.to_owned())); } } }; if let Err(error) = result { return Err( RuntimeError::from_dispatch(&self.metadata, error)?.into() - ) + ); } } } diff --git a/src/extrinsic/extra.rs b/src/extrinsic/extra.rs index f31cec25b85..4959ac2bbc3 100644 --- a/src/extrinsic/extra.rs +++ b/src/extrinsic/extra.rs @@ -14,25 +14,14 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use codec::{ - Decode, - Encode, -}; -use core::{ - fmt::Debug, - marker::PhantomData, -}; +use codec::{Decode, Encode}; +use core::{fmt::Debug, marker::PhantomData}; use sp_runtime::{ - generic::Era, - traits::SignedExtension, - transaction_validity::TransactionValidityError, + generic::Era, traits::SignedExtension, transaction_validity::TransactionValidityError, }; use crate::{ - frame::{ - balances::Balances, - system::System, - }, + frame::{balances::Balances, system::System}, runtimes::Runtime, }; diff --git a/src/extrinsic/mod.rs b/src/extrinsic/mod.rs index 70b50c9a113..0bdda3dc02e 100644 --- a/src/extrinsic/mod.rs +++ b/src/extrinsic/mod.rs @@ -20,26 +20,14 @@ mod extra; mod signer; pub use self::{ - extra::{ - DefaultExtra, - Extra, - SignedExtra, - }, - signer::{ - PairSigner, - Signer, - }, + extra::{DefaultExtra, Extra, SignedExtra}, + signer::{PairSigner, Signer}, }; use sp_runtime::traits::SignedExtension; use sp_version::RuntimeVersion; -use crate::{ - frame::system::System, - runtimes::Runtime, - Encoded, - Error, -}; +use crate::{frame::system::System, runtimes::Runtime, Encoded, Error}; /// UncheckedExtrinsic type. pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic< diff --git a/src/extrinsic/signer.rs b/src/extrinsic/signer.rs index 13ff50a3663..232f2035a30 100644 --- a/src/extrinsic/signer.rs +++ b/src/extrinsic/signer.rs @@ -17,23 +17,12 @@ //! A library to **sub**mit e**xt**rinsics to a //! [substrate](https://github.com/paritytech/substrate) node via RPC. -use super::{ - SignedExtra, - SignedPayload, - UncheckedExtrinsic, -}; +use super::{SignedExtra, SignedPayload, UncheckedExtrinsic}; use crate::runtimes::Runtime; use codec::Encode; use sp_core::Pair; -use sp_runtime::traits::{ - IdentifyAccount, - SignedExtension, - Verify, -}; -use std::{ - future::Future, - pin::Pin, -}; +use sp_runtime::traits::{IdentifyAccount, SignedExtension, Verify}; +use std::{future::Future, pin::Pin}; /// Extrinsic signer. pub trait Signer { diff --git a/src/frame/balances.rs b/src/frame/balances.rs index 9ebf6d63880..d8d28b94be5 100644 --- a/src/frame/balances.rs +++ b/src/frame/balances.rs @@ -16,21 +16,11 @@ //! Implements support for the pallet_balances module. -use crate::frame::system::{ - System, - SystemEventsDecoder, -}; -use codec::{ - Decode, - Encode, -}; +use crate::frame::system::{System, SystemEventsDecoder}; +use codec::{Decode, Encode}; use core::marker::PhantomData; use frame_support::Parameter; -use sp_runtime::traits::{ - AtLeast32Bit, - MaybeSerialize, - Member, -}; +use sp_runtime::traits::{AtLeast32Bit, MaybeSerialize, Member}; use std::fmt::Debug; /// The subset of the `pallet_balances::Trait` that a client must implement. @@ -110,27 +100,14 @@ pub struct TransferEvent { mod tests { use super::*; use crate::{ - error::{ - Error, - ModuleError, - RuntimeError, - }, + error::{Error, ModuleError, RuntimeError}, events::EventsDecoder, - extrinsic::{ - PairSigner, - Signer, - }, + extrinsic::{PairSigner, Signer}, subscription::EventSubscription, system::AccountStoreExt, - tests::{ - test_client, - TestRuntime, - }, - }; - use sp_core::{ - sr25519::Pair, - Pair as _, + tests::{test_client, TestRuntime}, }; + use sp_core::{sr25519::Pair, Pair as _}; use sp_keyring::AccountKeyring; #[async_std::test] diff --git a/src/frame/contracts.rs b/src/frame/contracts.rs index 0a0bc1da346..223c64dd95b 100644 --- a/src/frame/contracts.rs +++ b/src/frame/contracts.rs @@ -17,19 +17,10 @@ //! Implements support for the pallet_contracts module. use crate::frame::{ - balances::{ - Balances, - BalancesEventsDecoder, - }, - system::{ - System, - SystemEventsDecoder, - }, -}; -use codec::{ - Decode, - Encode, + balances::{Balances, BalancesEventsDecoder}, + system::{System, SystemEventsDecoder}, }; +use codec::{Decode, Encode}; use core::marker::PhantomData; /// Gas units are chosen to be represented by u64 so that gas metering diff --git a/src/frame/mod.rs b/src/frame/mod.rs index 1d7e262ed77..5f2e062a47e 100644 --- a/src/frame/mod.rs +++ b/src/frame/mod.rs @@ -18,15 +18,9 @@ use crate::{ events::EventsDecoder, - metadata::{ - Metadata, - MetadataError, - }, -}; -use codec::{ - Decode, - Encode, + metadata::{Metadata, MetadataError}, }; +use codec::{Decode, Encode}; use sp_core::storage::StorageKey; pub mod balances; diff --git a/src/frame/sudo.rs b/src/frame/sudo.rs index 733e1290d86..60098a9819e 100644 --- a/src/frame/sudo.rs +++ b/src/frame/sudo.rs @@ -17,10 +17,7 @@ //! Implements support for the frame_sudo module. use crate::{ - frame::system::{ - System, - SystemEventsDecoder, - }, + frame::system::{System, SystemEventsDecoder}, Encoded, }; use codec::Encode; @@ -43,16 +40,10 @@ pub struct SudoCall<'a, T: Sudo> { mod tests { use super::*; use crate::{ - error::{ - Error, - RuntimeError, - }, + error::{Error, RuntimeError}, extrinsic::PairSigner, frame::balances::TransferCall, - tests::{ - test_client, - TestRuntime, - }, + tests::{test_client, TestRuntime}, }; use sp_keyring::AccountKeyring; @@ -70,12 +61,10 @@ mod tests { .unwrap(); let res = client.sudo_and_watch(&alice, &call).await; - assert!( - if let Err(Error::Runtime(RuntimeError::BadOrigin)) = res { - true - } else { - false - } - ); + assert!(if let Err(Error::Runtime(RuntimeError::BadOrigin)) = res { + true + } else { + false + }); } } diff --git a/src/frame/system.rs b/src/frame/system.rs index b6ae0626bdd..28de649117d 100644 --- a/src/frame/system.rs +++ b/src/frame/system.rs @@ -16,32 +16,15 @@ //! Implements support for the frame_system module. -use codec::{ - Codec, - Decode, - Encode, -}; +use codec::{Codec, Decode, Encode}; use core::marker::PhantomData; -use frame_support::{ - weights::DispatchInfo, - Parameter, -}; +use frame_support::{weights::DispatchInfo, Parameter}; use serde::de::DeserializeOwned; use sp_runtime::{ traits::{ - AtLeast32Bit, - AtLeast32BitUnsigned, - Bounded, - CheckEqual, - Extrinsic, - Hash, - Header, - MaybeDisplay, - MaybeMallocSizeOf, - MaybeSerialize, - MaybeSerializeDeserialize, - Member, - SimpleBitOps, + AtLeast32Bit, AtLeast32BitUnsigned, Bounded, CheckEqual, Extrinsic, Hash, Header, + MaybeDisplay, MaybeMallocSizeOf, MaybeSerialize, MaybeSerializeDeserialize, + Member, SimpleBitOps, }, DispatchError, }; diff --git a/src/lib.rs b/src/lib.rs index 260fff9e2b8..5e1ee10abc8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,11 +53,7 @@ use futures::future; use jsonrpsee::client::Subscription; use sc_rpc_api::state::ReadProof; use sp_core::{ - storage::{ - StorageChangeSet, - StorageData, - StorageKey, - }, + storage::{StorageChangeSet, StorageData, StorageKey}, Bytes, }; pub use sp_runtime::traits::SignedExtension; @@ -75,39 +71,18 @@ mod subscription; pub use crate::{ error::Error, - events::{ - EventsDecoder, - RawEvent, - }, - extrinsic::{ - PairSigner, - SignedExtra, - Signer, - UncheckedExtrinsic, - }, + events::{EventsDecoder, RawEvent}, + extrinsic::{PairSigner, SignedExtra, Signer, UncheckedExtrinsic}, frame::*, - metadata::{ - Metadata, - MetadataError, - }, - rpc::{ - BlockNumber, - ExtrinsicSuccess, - }, + metadata::{Metadata, MetadataError}, + rpc::{BlockNumber, ExtrinsicSuccess}, runtimes::*, subscription::*, substrate_subxt_proc_macro::*, }; use crate::{ - frame::system::{ - AccountStoreExt, - Phase, - System, - }, - rpc::{ - ChainBlock, - Rpc, - }, + frame::system::{AccountStoreExt, Phase, System}, + rpc::{ChainBlock, Rpc}, }; /// ClientBuilder for constructing a Client. @@ -216,7 +191,7 @@ impl> KeyIter { pub async fn next(&mut self) -> Result, Error> { loop { if let Some((k, v)) = self.buffer.pop() { - return Ok(Some((k, Decode::decode(&mut &v.0[..])?))) + return Ok(Some((k, Decode::decode(&mut &v.0[..])?))); } else { let keys = self .client @@ -224,7 +199,7 @@ impl> KeyIter { .await?; if keys.is_empty() { - return Ok(None) + return Ok(None); } self.start_key = keys.last().cloned(); @@ -561,17 +536,10 @@ impl codec::Encode for Encoded { #[cfg(test)] mod tests { use super::*; - use sp_core::storage::{ - well_known_keys, - StorageKey, - }; + use sp_core::storage::{well_known_keys, StorageKey}; use sp_keyring::AccountKeyring; use substrate_subxt_client::{ - DatabaseConfig, - KeystoreConfig, - Role, - SubxtClient, - SubxtClientConfig, + DatabaseConfig, KeystoreConfig, Role, SubxtClient, SubxtClientConfig, }; use tempdir::TempDir; diff --git a/src/metadata.rs b/src/metadata.rs index 3ef160cfc93..28e83222d93 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -14,27 +14,13 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use std::{ - collections::HashMap, - convert::TryFrom, - marker::PhantomData, - str::FromStr, -}; +use std::{collections::HashMap, convert::TryFrom, marker::PhantomData, str::FromStr}; -use codec::{ - Decode, - Encode, - Error as CodecError, -}; +use codec::{Decode, Encode, Error as CodecError}; use frame_metadata::{ - DecodeDifferent, - RuntimeMetadata, - RuntimeMetadataPrefixed, - StorageEntryModifier, - StorageEntryType, - StorageHasher, - META_RESERVED, + DecodeDifferent, RuntimeMetadata, RuntimeMetadataPrefixed, StorageEntryModifier, + StorageEntryType, StorageHasher, META_RESERVED, }; use sp_core::storage::StorageKey; @@ -274,13 +260,11 @@ impl StorageMetadata { StorageHasher::Blake2_256 => sp_core::blake2_256(bytes).to_vec(), StorageHasher::Twox128 => sp_core::twox_128(bytes).to_vec(), StorageHasher::Twox256 => sp_core::twox_256(bytes).to_vec(), - StorageHasher::Twox64Concat => { - sp_core::twox_64(bytes) - .iter() - .chain(bytes) - .cloned() - .collect() - } + StorageHasher::Twox64Concat => sp_core::twox_64(bytes) + .iter() + .chain(bytes) + .cloned() + .collect(), } } @@ -290,24 +274,20 @@ impl StorageMetadata { pub fn plain(&self) -> Result { match &self.ty { - StorageEntryType::Plain(_) => { - Ok(StoragePlain { - prefix: self.prefix().0, - }) - } + StorageEntryType::Plain(_) => Ok(StoragePlain { + prefix: self.prefix().0, + }), _ => Err(MetadataError::StorageTypeError), } } pub fn map(&self) -> Result, MetadataError> { match &self.ty { - StorageEntryType::Map { hasher, .. } => { - Ok(StorageMap { - _marker: PhantomData, - prefix: self.prefix().0, - hasher: hasher.clone(), - }) - } + StorageEntryType::Map { hasher, .. } => Ok(StorageMap { + _marker: PhantomData, + prefix: self.prefix().0, + hasher: hasher.clone(), + }), _ => Err(MetadataError::StorageTypeError), } } @@ -320,14 +300,12 @@ impl StorageMetadata { hasher, key2_hasher, .. - } => { - Ok(StorageDoubleMap { - _marker: PhantomData, - prefix: self.prefix().0, - hasher1: hasher.clone(), - hasher2: key2_hasher.clone(), - }) - } + } => Ok(StorageDoubleMap { + _marker: PhantomData, + prefix: self.prefix().0, + hasher1: hasher.clone(), + hasher2: key2_hasher.clone(), + }), _ => Err(MetadataError::StorageTypeError), } } @@ -398,6 +376,7 @@ pub enum EventArg { Primitive(String), Vec(Box), Tuple(Vec), + Option(Option>), } impl FromStr for EventArg { @@ -413,6 +392,15 @@ impl FromStr for EventArg { "Expected closing `>` for `Vec`", )) } + } else if s.starts_with("Option<") { + if s.ends_with('>') { + Ok(EventArg::Option(Some(Box::new(s[7..s.len() - 1].parse()?)))) + } else { + Err(ConversionError::InvalidEventArg( + s.to_string(), + "Expected closing `>` for `Option`", + )) + } } else if s.starts_with('(') { if s.ends_with(')') { let mut args = Vec::new(); @@ -439,6 +427,13 @@ impl EventArg { match self { EventArg::Primitive(p) => vec![p.clone()], EventArg::Vec(arg) => arg.primitives(), + EventArg::Option(arg) => { + if let Some(item) = arg { + item.primitives() + } else { + vec![] + } + } EventArg::Tuple(args) => { let mut primitives = Vec::new(); for arg in args { @@ -467,7 +462,7 @@ impl TryFrom for Metadata { fn try_from(metadata: RuntimeMetadataPrefixed) -> Result { if metadata.0 != META_RESERVED { - return Err(ConversionError::InvalidPrefix.into()) + return Err(ConversionError::InvalidPrefix.into()); } let meta = match metadata.1 { RuntimeMetadata::V11(meta) => meta, diff --git a/src/rpc.rs b/src/rpc.rs index dd2aeff40e7..b40bbd8b8cd 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -19,44 +19,23 @@ // Related: https://github.com/paritytech/substrate-subxt/issues/66 #![allow(irrefutable_let_patterns)] -use codec::{ - Decode, - Encode, - Error as CodecError, -}; -use core::{ - convert::TryInto, - marker::PhantomData, -}; +use codec::{Decode, Encode, Error as CodecError}; +use core::{convert::TryInto, marker::PhantomData}; use frame_metadata::RuntimeMetadataPrefixed; use jsonrpsee::{ client::Subscription, - common::{ - to_value as to_json_value, - Params, - }, + common::{to_value as to_json_value, Params}, Client, }; use sc_rpc_api::state::ReadProof; use serde::Serialize; use sp_core::{ - storage::{ - StorageChangeSet, - StorageData, - StorageKey, - }, - twox_128, - Bytes, -}; -use sp_rpc::{ - list::ListOrValue, - number::NumberOrHex, + storage::{StorageChangeSet, StorageData, StorageKey}, + twox_128, Bytes, }; +use sp_rpc::{list::ListOrValue, number::NumberOrHex}; use sp_runtime::{ - generic::{ - Block, - SignedBlock, - }, + generic::{Block, SignedBlock}, traits::Hash, }; use sp_transaction_pool::TransactionStatus; @@ -64,14 +43,8 @@ use sp_version::RuntimeVersion; use crate::{ error::Error, - events::{ - EventsDecoder, - RawEvent, - }, - frame::{ - system::System, - Event, - }, + events::{EventsDecoder, RawEvent}, + frame::{system::System, Event}, metadata::Metadata, runtimes::Runtime, subscription::EventSubscription, @@ -411,7 +384,7 @@ impl Rpc { None => { Err(format!("Failed to find block {:?}", block_hash).into()) } - } + }; } TransactionStatus::Invalid => return Err("Extrinsic Invalid".into()), TransactionStatus::Usurped(_) => return Err("Extrinsic Usurped".into()), diff --git a/src/runtimes.rs b/src/runtimes.rs index 13779d71b86..846ce553ab3 100644 --- a/src/runtimes.rs +++ b/src/runtimes.rs @@ -17,25 +17,14 @@ use codec::Encode; use sp_runtime::{ generic::Header, - traits::{ - BlakeTwo256, - IdentifyAccount, - Verify, - }, - MultiSignature, - OpaqueExtrinsic, + traits::{BlakeTwo256, IdentifyAccount, Verify}, + MultiSignature, OpaqueExtrinsic, }; use crate::{ - extrinsic::{ - DefaultExtra, - SignedExtra, - }, + extrinsic::{DefaultExtra, SignedExtra}, frame::{ - balances::{ - AccountData, - Balances, - }, + balances::{AccountData, Balances}, contracts::Contracts, sudo::Sudo, system::System, diff --git a/src/subscription.rs b/src/subscription.rs index 6f352edeb8e..30d43b0ca23 100644 --- a/src/subscription.rs +++ b/src/subscription.rs @@ -20,15 +20,8 @@ use std::collections::VecDeque; use crate::{ error::Error, - events::{ - EventsDecoder, - Raw, - RawEvent, - }, - frame::{ - system::Phase, - Event, - }, + events::{EventsDecoder, Raw, RawEvent}, + frame::{system::Phase, Event}, runtimes::Runtime, }; @@ -81,17 +74,17 @@ impl EventSubscription { pub async fn next(&mut self) -> Option> { loop { if let Some(event) = self.events.pop_front() { - return Some(Ok(event)) + return Some(Ok(event)); } if self.finished { - return None + return None; } let change_set = self.subscription.next().await; if let Some(hash) = self.block.as_ref() { if &change_set.block == hash { self.finished = true; } else { - continue + continue; } } for (_key, data) in change_set.changes { @@ -104,7 +97,7 @@ impl EventSubscription { if let Phase::ApplyExtrinsic(i) = phase { if let Some(ext_index) = self.extrinsic { if i as usize != ext_index { - continue + continue; } } let event = match raw { @@ -113,7 +106,7 @@ impl EventSubscription { }; if let Some((module, variant)) = self.event { if event.module != module || event.variant != variant { - continue + continue; } } self.events.push_back(event); diff --git a/test-node/build.rs b/test-node/build.rs index ca699c6c738..804440eec68 100644 --- a/test-node/build.rs +++ b/test-node/build.rs @@ -14,10 +14,7 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use substrate_build_script_utils::{ - generate_cargo_keys, - rerun_if_git_head_changed, -}; +use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; fn main() { generate_cargo_keys(); diff --git a/test-node/runtime/src/lib.rs b/test-node/runtime/src/lib.rs index 85abd73d32c..61c0dd60c9d 100644 --- a/test-node/runtime/src/lib.rs +++ b/test-node/runtime/src/lib.rs @@ -26,35 +26,19 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use pallet_grandpa::{ - fg_primitives, - AuthorityId as GrandpaId, - AuthorityList as GrandpaAuthorityList, + fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList, }; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{ - crypto::KeyTypeId, - OpaqueMetadata, -}; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, - generic, - impl_opaque_keys, + create_runtime_str, generic, impl_opaque_keys, traits::{ - BlakeTwo256, - Block as BlockT, - IdentifyAccount, - IdentityLookup, - NumberFor, - Saturating, - Verify, - }, - transaction_validity::{ - TransactionSource, - TransactionValidity, + BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, + Saturating, Verify, }, - ApplyExtrinsicResult, - MultiSignature, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, MultiSignature, }; use sp_std::prelude::*; #[cfg(feature = "std")] @@ -63,21 +47,13 @@ use sp_version::RuntimeVersion; // A few exports that help ease life for downstream crates. pub use frame_support::{ - construct_runtime, - parameter_types, - traits::{ - KeyOwnerProofSystem, - Randomness, - }, + construct_runtime, parameter_types, + traits::{KeyOwnerProofSystem, Randomness}, weights::{ constants::{ - BlockExecutionWeight, - ExtrinsicBaseWeight, - RocksDbWeight, - WEIGHT_PER_SECOND, + BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND, }, - IdentityFee, - Weight, + IdentityFee, Weight, }, StorageValue, }; @@ -85,10 +61,7 @@ pub use pallet_balances::Call as BalancesCall; pub use pallet_timestamp::Call as TimestampCall; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; -pub use sp_runtime::{ - Perbill, - Permill, -}; +pub use sp_runtime::{Perbill, Permill}; /// An index to a block. pub type BlockNumber = u32; diff --git a/test-node/src/chain_spec.rs b/test-node/src/chain_spec.rs index a9cc64e42d2..f851b548101 100644 --- a/test-node/src/chain_spec.rs +++ b/test-node/src/chain_spec.rs @@ -16,26 +16,12 @@ use sc_service::ChainType; use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{ - sr25519, - Pair, - Public, -}; +use sp_core::{sr25519, Pair, Public}; use sp_finality_grandpa::AuthorityId as GrandpaId; -use sp_runtime::traits::{ - IdentifyAccount, - Verify, -}; +use sp_runtime::traits::{IdentifyAccount, Verify}; use test_node_runtime::{ - AccountId, - AuraConfig, - BalancesConfig, - GenesisConfig, - GrandpaConfig, - Signature, - SudoConfig, - SystemConfig, - WASM_BINARY, + AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, + SudoConfig, SystemConfig, WASM_BINARY, }; // The URL for the telemetry server. diff --git a/test-node/src/cli.rs b/test-node/src/cli.rs index b94a06ad742..57fe7db8bfc 100644 --- a/test-node/src/cli.rs +++ b/test-node/src/cli.rs @@ -14,10 +14,7 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use sc_cli::{ - RunCmd, - Subcommand, -}; +use sc_cli::{RunCmd, Subcommand}; use structopt::StructOpt; #[derive(Debug, StructOpt)] diff --git a/test-node/src/command.rs b/test-node/src/command.rs index f4d7e82fd9a..1ebf9fbcbcf 100644 --- a/test-node/src/command.rs +++ b/test-node/src/command.rs @@ -14,17 +14,8 @@ // You should have received a copy of the GNU General Public License // along with substrate-subxt. If not, see . -use crate::{ - chain_spec, - cli::Cli, - service, -}; -use sc_cli::{ - ChainSpec, - Role, - RuntimeVersion, - SubstrateCli, -}; +use crate::{chain_spec, cli::Cli, service}; +use sc_cli::{ChainSpec, Role, RuntimeVersion, SubstrateCli}; use sc_service::PartialComponents; impl SubstrateCli for Cli { @@ -56,11 +47,9 @@ impl SubstrateCli for Cli { Ok(match id { "dev" => Box::new(chain_spec::development_config()?), "" | "local" => Box::new(chain_spec::local_testnet_config()?), - path => { - Box::new(chain_spec::ChainSpec::from_json_file( - std::path::PathBuf::from(path), - )?) - } + path => Box::new(chain_spec::ChainSpec::from_json_file( + std::path::PathBuf::from(path), + )?), }) } diff --git a/test-node/src/service.rs b/test-node/src/service.rs index 454f7f41a9a..f4d1d65fc8b 100644 --- a/test-node/src/service.rs +++ b/test-node/src/service.rs @@ -17,34 +17,20 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. #![allow(clippy::type_complexity)] -use sc_client_api::{ - ExecutorProvider, - RemoteBackend, -}; +use sc_client_api::{ExecutorProvider, RemoteBackend}; use sc_executor::native_executor_instance; pub use sc_executor::NativeExecutor; use sc_finality_grandpa::{ - FinalityProofProvider as GrandpaFinalityProofProvider, - SharedVoterState, + FinalityProofProvider as GrandpaFinalityProofProvider, SharedVoterState, }; use sc_service::{ - error::Error as ServiceError, - Configuration, - PartialComponents, - RpcHandlers, + error::Error as ServiceError, Configuration, PartialComponents, RpcHandlers, TaskManager, }; use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; use sp_inherents::InherentDataProviders; -use std::{ - sync::Arc, - time::Duration, -}; -use test_node_runtime::{ - self, - opaque::Block, - RuntimeApi, -}; +use std::{sync::Arc, time::Duration}; +use test_node_runtime::{self, opaque::Block, RuntimeApi}; // Our native executor instance. native_executor_instance!(