From 62fdcb1853c5b55bb95d063b1ee679ad57839c0b Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Tue, 14 Apr 2020 12:31:14 +0100 Subject: [PATCH 1/2] Add fetch example and wrap BlockNumber impl --- examples/fetch_remote.rs | 42 ++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 9 ++++----- src/rpc.rs | 26 ++++++++++++++++++++++++- 3 files changed, 71 insertions(+), 6 deletions(-) create mode 100644 examples/fetch_remote.rs diff --git a/examples/fetch_remote.rs b/examples/fetch_remote.rs new file mode 100644 index 0000000000..061e22fb8b --- /dev/null +++ b/examples/fetch_remote.rs @@ -0,0 +1,42 @@ +// Copyright 2020 Parity Technologies (UK) Ltd. +// This file is part of substrate-subxt. +// +// subxt is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// subxt is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with substrate-subxt. If not, see . + +use substrate_subxt::{ + Error, + KusamaRuntime, + system::System, +}; + +fn main() { + async_std::task::block_on(async move { + env_logger::init(); + + let block_hash = fetch_block_hash(1).await; + match block_hash { + Ok(Some(hash)) => println!("Block hash for block number 1: {}", hash), + Ok(None) => println!("Block number 1 not found."), + Err(_) => eprintln!("Failed to fetch block hash"), + } + }); +} + +async fn fetch_block_hash(block_number: u32) -> Result::Hash>, Error> { + substrate_subxt::ClientBuilder::::new() + .set_url("wss://kusama-rpc.polkadot.io") + .build().await? + .block_hash(Some(block_number.into())) + .await +} diff --git a/src/lib.rs b/src/lib.rs index 91e2def0e8..2a7b7fd2f0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,7 +83,7 @@ pub use self::{ error::Error, events::RawEvent, frame::*, - rpc::ExtrinsicSuccess, + rpc::{BlockNumber, ExtrinsicSuccess}, runtimes::*, }; use self::{ @@ -106,7 +106,6 @@ use self::{ }, metadata::Metadata, rpc::{ - BlockNumber, ChainBlock, Rpc, }, @@ -616,7 +615,7 @@ mod tests { #[test] #[ignore] // requires locally running substrate node fn test_create_raw_payload() { - + let result: Result<_, Error> = async_std::task::block_on(async move { let signer_pair = Ed25519Keyring::Alice.pair(); let signer_account_id = Ed25519Keyring::Alice.to_account_id(); @@ -624,7 +623,7 @@ mod tests { let client = test_client().await; - // create raw payload with AccoundId and sign it + // create raw payload with AccoundId and sign it let raw_payload = client.create_raw_payload(signer_account_id, balances::transfer::(dest.clone().into(), 10_000)).await?; let raw_signature = signer_pair.sign(raw_payload.encode().split_off(2).as_slice()); let raw_multisig = MultiSignature::from(raw_signature); @@ -637,7 +636,7 @@ mod tests { assert_eq!(raw_multisig, xt_multi_sig); Ok(()) - + }); assert!(result.is_ok()) diff --git a/src/rpc.rs b/src/rpc.rs index d4d91853a0..f1e1893b5c 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -38,6 +38,7 @@ use jsonrpsee::{ use num_traits::bounds::Bounded; use frame_metadata::RuntimeMetadataPrefixed; +use serde::Serialize; use sp_core::{ storage::{ StorageChangeSet, @@ -82,7 +83,30 @@ use crate::{ pub type ChainBlock = SignedBlock::Header, ::Extrinsic>>; -pub type BlockNumber = NumberOrHex<::BlockNumber>; + +/// Wrapper for NumberOrHex to allow custom From impls +#[derive(Serialize)] +#[serde(bound = "::BlockNumber: Serialize")] +pub struct BlockNumber (NumberOrHex<::BlockNumber>); + +impl From::BlockNumber>> for BlockNumber +where + T: System +{ + fn from(x: NumberOrHex<::BlockNumber>) -> Self { + BlockNumber(x) + } +} + +impl From for BlockNumber +where + T: System, + ::BlockNumber: From, +{ + fn from(x: u32) -> Self { + NumberOrHex::Number(x.into()).into() + } +} /// Client for substrate rpc interfaces #[derive(Clone)] From f200992bc0f9894be11f14b214119f506c8c441f Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Tue, 14 Apr 2020 12:32:12 +0100 Subject: [PATCH 2/2] Fmt --- examples/fetch_remote.rs | 39 ++++++++++++++++------------- examples/kusama_balance_transfer.rs | 11 +++++--- examples/submit_and_watch.rs | 5 ++-- src/lib.rs | 39 ++++++++++++++++++++--------- src/rpc.rs | 4 +-- 5 files changed, 60 insertions(+), 38 deletions(-) diff --git a/examples/fetch_remote.rs b/examples/fetch_remote.rs index 061e22fb8b..8454daf3cc 100644 --- a/examples/fetch_remote.rs +++ b/examples/fetch_remote.rs @@ -15,28 +15,31 @@ // along with substrate-subxt. If not, see . use substrate_subxt::{ - Error, - KusamaRuntime, - system::System, + system::System, + Error, + KusamaRuntime, }; fn main() { - async_std::task::block_on(async move { - env_logger::init(); + async_std::task::block_on(async move { + env_logger::init(); - let block_hash = fetch_block_hash(1).await; - match block_hash { - Ok(Some(hash)) => println!("Block hash for block number 1: {}", hash), - Ok(None) => println!("Block number 1 not found."), - Err(_) => eprintln!("Failed to fetch block hash"), - } - }); + let block_hash = fetch_block_hash(1).await; + match block_hash { + Ok(Some(hash)) => println!("Block hash for block number 1: {}", hash), + Ok(None) => println!("Block number 1 not found."), + Err(_) => eprintln!("Failed to fetch block hash"), + } + }); } -async fn fetch_block_hash(block_number: u32) -> Result::Hash>, Error> { - substrate_subxt::ClientBuilder::::new() - .set_url("wss://kusama-rpc.polkadot.io") - .build().await? - .block_hash(Some(block_number.into())) - .await +async fn fetch_block_hash( + block_number: u32, +) -> Result::Hash>, Error> { + substrate_subxt::ClientBuilder::::new() + .set_url("wss://kusama-rpc.polkadot.io") + .build() + .await? + .block_hash(Some(block_number.into())) + .await } diff --git a/examples/kusama_balance_transfer.rs b/examples/kusama_balance_transfer.rs index bb7e1ff1c5..5255244365 100644 --- a/examples/kusama_balance_transfer.rs +++ b/examples/kusama_balance_transfer.rs @@ -39,8 +39,13 @@ async fn transfer_balance() -> Result { // note use of `KusamaRuntime` substrate_subxt::ClientBuilder::::new() - .build().await? - .xt(signer, None).await? - .submit(balances::transfer::(dest.clone().into(), 10_000)) + .build() + .await? + .xt(signer, None) + .await? + .submit(balances::transfer::( + dest.clone().into(), + 10_000, + )) .await } diff --git a/examples/submit_and_watch.rs b/examples/submit_and_watch.rs index c40553c50b..09d3a77d81 100644 --- a/examples/submit_and_watch.rs +++ b/examples/submit_and_watch.rs @@ -51,9 +51,8 @@ fn main() { match result { Ok(extrinsic_success) => { match extrinsic_success - .find_event::<(AccountId, AccountId, Balance)>( - "Balances", "Transfer", - ) { + .find_event::<(AccountId, AccountId, Balance)>("Balances", "Transfer") + { Some(Ok((_from, _to, value))) => { println!("Balance transfer success: value: {:?}", value) } diff --git a/src/lib.rs b/src/lib.rs index 2a7b7fd2f0..9e4fbf115f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,7 +83,10 @@ pub use self::{ error::Error, events::RawEvent, frame::*, - rpc::{BlockNumber, ExtrinsicSuccess}, + rpc::{ + BlockNumber, + ExtrinsicSuccess, + }, runtimes::*, }; use self::{ @@ -303,10 +306,7 @@ impl Client { &self, account_id: ::AccountId, call: Call, - ) -> Result< - Vec, - Error, - > + ) -> Result, Error> where C: codec::Encode, { @@ -317,7 +317,8 @@ impl Client { .metadata() .module_with_calls(&call.module) .and_then(|module| module.call(&call.function, call.args))?; - let extra: extrinsic::DefaultExtra = extrinsic::DefaultExtra::new(version, account_nonce, genesis_hash); + let extra: extrinsic::DefaultExtra = + extrinsic::DefaultExtra::new(version, account_nonce, genesis_hash); let raw_payload = SignedPayload::new(call, extra.extra())?; Ok(raw_payload.encode()) } @@ -510,7 +511,10 @@ impl codec::Encode for Encoded { #[cfg(test)] mod tests { - use sp_keyring::{ AccountKeyring, Ed25519Keyring }; + use sp_keyring::{ + AccountKeyring, + Ed25519Keyring, + }; use super::*; use crate::{ @@ -615,7 +619,6 @@ mod tests { #[test] #[ignore] // requires locally running substrate node fn test_create_raw_payload() { - let result: Result<_, Error> = async_std::task::block_on(async move { let signer_pair = Ed25519Keyring::Alice.pair(); let signer_account_id = Ed25519Keyring::Alice.to_account_id(); @@ -624,19 +627,31 @@ mod tests { let client = test_client().await; // create raw payload with AccoundId and sign it - let raw_payload = client.create_raw_payload(signer_account_id, balances::transfer::(dest.clone().into(), 10_000)).await?; - let raw_signature = signer_pair.sign(raw_payload.encode().split_off(2).as_slice()); + let raw_payload = client + .create_raw_payload( + signer_account_id, + balances::transfer::(dest.clone().into(), 10_000), + ) + .await?; + let raw_signature = + signer_pair.sign(raw_payload.encode().split_off(2).as_slice()); let raw_multisig = MultiSignature::from(raw_signature); // create signature with Xtbuilder let xt = client.xt(signer_pair.clone(), None).await?; - let xt_multi_sig = xt.create_and_sign(balances::transfer::(dest.clone().into(), 10_000))?.signature.unwrap().1; + let xt_multi_sig = xt + .create_and_sign(balances::transfer::( + dest.clone().into(), + 10_000, + ))? + .signature + .unwrap() + .1; // compare signatures assert_eq!(raw_multisig, xt_multi_sig); Ok(()) - }); assert!(result.is_ok()) diff --git a/src/rpc.rs b/src/rpc.rs index f1e1893b5c..04acb4669a 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -87,11 +87,11 @@ pub type ChainBlock = /// Wrapper for NumberOrHex to allow custom From impls #[derive(Serialize)] #[serde(bound = "::BlockNumber: Serialize")] -pub struct BlockNumber (NumberOrHex<::BlockNumber>); +pub struct BlockNumber(NumberOrHex<::BlockNumber>); impl From::BlockNumber>> for BlockNumber where - T: System + T: System, { fn from(x: NumberOrHex<::BlockNumber>) -> Self { BlockNumber(x)