Refactors the api (#113)

* Refactor api.

* Try fix ci.

* Fix test.

* Address review comments.
This commit is contained in:
David Craven
2020-05-26 11:04:44 +02:00
committed by GitHub
parent 6e6a8bbd28
commit 67f3ce529e
10 changed files with 335 additions and 403 deletions
+1 -2
View File
@@ -16,8 +16,7 @@ jobs:
- name: setup
run: |
rustup install nightly
rustup component add rustfmt --toolchain nightly
rustup install nightly --profile default
- name: fmt
run: cargo +nightly fmt --all -- --check
+3 -7
View File
@@ -19,22 +19,18 @@ use substrate_subxt::{
balances::*,
ClientBuilder,
KusamaRuntime,
PairSigner,
};
#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
let signer = AccountKeyring::Alice.pair();
let signer = PairSigner::new(AccountKeyring::Alice.pair());
let dest = AccountKeyring::Bob.to_account_id().into();
let client = ClientBuilder::<KusamaRuntime>::new().build().await?;
let hash = client
.xt(signer, None)
.await?
.transfer(&dest, 10_000)
.await?;
let hash = client.transfer(&signer, &dest, 10_000).await?;
println!("Balance transfer extrinsic submitted: {}", hash);
+3 -7
View File
@@ -19,22 +19,18 @@ use substrate_subxt::{
balances::*,
ClientBuilder,
DefaultNodeRuntime,
PairSigner,
};
#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
let signer = AccountKeyring::Alice.pair();
let signer = PairSigner::new(AccountKeyring::Alice.pair());
let dest = AccountKeyring::Bob.to_account_id().into();
let client = ClientBuilder::<DefaultNodeRuntime>::new().build().await?;
let result = client
.xt(signer, None)
.await?
.watch()
.transfer(&dest, 10_000)
.await?;
let result = client.transfer_and_watch(&signer, &dest, 10_000).await?;
if let Some(event) = result.transfer()? {
println!("Balance transfer success: value: {:?}", event.amount);
+54 -91
View File
@@ -28,6 +28,7 @@ use synstructure::Structure;
pub fn call(s: Structure) -> TokenStream {
let subxt = utils::use_crate("substrate-subxt");
let codec = utils::use_crate("parity-scale-codec");
let ident = &s.ast().ident;
let generics = &s.ast().generics;
let params = utils::type_params(generics);
@@ -43,26 +44,9 @@ pub fn call(s: Structure) -> TokenStream {
let filtered_fields = utils::filter_fields(&fields, &marker);
let args = utils::fields_to_args(&filtered_fields);
let build_struct = utils::build_struct(ident, &fields);
let xt_builder = generate_trait(
&module,
&call_name,
"XtBuilder",
quote!(&'a self),
quote!(T::Hash),
&args,
&build_struct,
&marker,
);
let events_subscriber = generate_trait(
&module,
&call_name,
"EventsSubscriber",
quote!(self),
quote!(#subxt::ExtrinsicSuccess<T>),
&args,
&build_struct,
&marker,
);
let call_trait = format_ident!("{}CallExt", call_name.to_camel_case());
let call = format_ident!("{}", call_name);
let call_and_watch = format_ident!("{}_and_watch", call_name);
quote! {
impl#generics #subxt::Call<T> for #ident<#(#params),*> {
@@ -76,52 +60,45 @@ pub fn call(s: Structure) -> TokenStream {
}
}
#xt_builder
#events_subscriber
}
}
pub fn generate_trait(
module: &syn::Path,
call: &str,
ty: &str,
me: TokenStream,
ret: TokenStream,
args: &TokenStream,
build_struct: &TokenStream,
marker: &syn::Ident,
) -> TokenStream {
let subxt = utils::use_crate("substrate-subxt");
let codec = utils::use_crate("parity-scale-codec");
let call_trait = format_ident!("{}Call{}", call.to_camel_case(), ty);
let call = format_ident!("{}", call);
let ty = format_ident!("{}", ty);
quote! {
/// Call extension trait.
pub trait #call_trait<T: #module> {
/// Create and submit the extrinsic.
pub trait #call_trait<T: #module, S: #codec::Encode, E: #subxt::SignedExtra<T>> {
/// Create and submit an extrinsic.
fn #call<'a>(
#me,
&'a self,
signer: &'a (dyn #subxt::Signer<T, S, E> + Send + Sync),
#args
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<#ret, #subxt::Error>> + Send + 'a>>;
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<T::Hash, #subxt::Error>> + Send + 'a>>;
/// Create, submit and watch an extrinsic.
fn #call_and_watch<'a>(
&'a self,
signer: &'a (dyn #subxt::Signer<T, S, E> + Send + Sync),
#args
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<#subxt::ExtrinsicSuccess<T>, #subxt::Error>> + Send + 'a>>;
}
impl<T, P, S, E> #call_trait<T> for #subxt::#ty<T, P, S, E>
impl<T, S, E> #call_trait<T, S, E> for #subxt::Client<T, S, E>
where
T: #module + #subxt::system::System + Send + Sync + 'static,
P: #subxt::sp_core::Pair,
S: #subxt::sp_runtime::traits::Verify + #codec::Codec + From<P::Signature> + Send + 'static,
S::Signer: From<P::Public> + #subxt::sp_runtime::traits::IdentifyAccount<AccountId = T::AccountId>,
T::Address: From<T::AccountId>,
E: #subxt::SignedExtra<T> + #subxt::sp_runtime::traits::SignedExtension + 'static,
S: #codec::Encode + Send + Sync + 'static,
E: #subxt::SignedExtra<T> + #subxt::sp_runtime::traits::SignedExtension + Send + Sync + 'static,
{
fn #call<'a>(
#me,
&'a self,
signer: &'a (dyn #subxt::Signer<T, S, E> + Send + Sync),
#args
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<#ret, #subxt::Error>> + Send + 'a>> {
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<T::Hash, #subxt::Error>> + Send + 'a>> {
let #marker = core::marker::PhantomData::<T>;
Box::pin(self.submit(#build_struct))
Box::pin(self.submit(#build_struct, signer))
}
fn #call_and_watch<'a>(
&'a self,
signer: &'a (dyn #subxt::Signer<T, S, E> + Send + Sync),
#args
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<#subxt::ExtrinsicSuccess<T>, #subxt::Error>> + Send + 'a>> {
let #marker = core::marker::PhantomData::<T>;
Box::pin(self.watch(#build_struct, signer))
}
}
}
@@ -154,62 +131,48 @@ mod tests {
}
/// Call extension trait.
pub trait TransferCallXtBuilder<T: Balances> {
/// Create and submit the extrinsic.
pub trait TransferCallExt<T: Balances, S: codec::Encode, E: substrate_subxt::SignedExtra<T>> {
/// Create and submit an extrinsic.
fn transfer<'a>(
&'a self,
signer: &'a (dyn substrate_subxt::Signer<T, S, E> + Send + Sync),
to: &'a <T as System>::Address,
amount: T::Balance,
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<T::Hash, substrate_subxt::Error>> + Send + 'a>>;
}
impl<T, P, S, E> TransferCallXtBuilder<T> for substrate_subxt::XtBuilder<T, P, S, E>
where
T: Balances + substrate_subxt::system::System + Send + Sync + 'static,
P: substrate_subxt::sp_core::Pair,
S: substrate_subxt::sp_runtime::traits::Verify + codec::Codec + From<P::Signature> + Send + 'static,
S::Signer: From<P::Public> + substrate_subxt::sp_runtime::traits::IdentifyAccount<
AccountId = T::AccountId>,
T::Address: From<T::AccountId>,
E: substrate_subxt::SignedExtra<T> + substrate_subxt::sp_runtime::traits::SignedExtension + 'static,
{
fn transfer<'a>(
/// Create, submit and watch an extrinsic.
fn transfer_and_watch<'a>(
&'a self,
to: &'a <T as System>::Address,
amount: T::Balance,
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<T::Hash, substrate_subxt::Error>> + Send + 'a>> {
let _ = core::marker::PhantomData::<T>;
Box::pin(self.submit(TransferCall { to, amount, }))
}
}
/// Call extension trait.
pub trait TransferCallEventsSubscriber<T: Balances> {
/// Create and submit the extrinsic.
fn transfer<'a>(
self,
signer: &'a (dyn substrate_subxt::Signer<T, S, E> + Send + Sync),
to: &'a <T as System>::Address,
amount: T::Balance,
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<substrate_subxt::ExtrinsicSuccess<T>, substrate_subxt::Error>> + Send + 'a>>;
}
impl<T, P, S, E> TransferCallEventsSubscriber<T> for substrate_subxt::EventsSubscriber<T, P, S, E>
impl<T, S, E> TransferCallExt<T, S, E> for substrate_subxt::Client<T, S, E>
where
T: Balances + substrate_subxt::system::System + Send + Sync + 'static,
P: substrate_subxt::sp_core::Pair,
S: substrate_subxt::sp_runtime::traits::Verify + codec::Codec + From<P::Signature> + Send + 'static,
S::Signer: From<P::Public> + substrate_subxt::sp_runtime::traits::IdentifyAccount<
AccountId = T::AccountId>,
T::Address: From<T::AccountId>,
E: substrate_subxt::SignedExtra<T> + substrate_subxt::sp_runtime::traits::SignedExtension + 'static,
S: codec::Encode + Send + Sync + 'static,
E: substrate_subxt::SignedExtra<T> + substrate_subxt::sp_runtime::traits::SignedExtension + Send + Sync + 'static,
{
fn transfer<'a>(
self,
&'a self,
signer: &'a (dyn substrate_subxt::Signer<T, S, E> + Send + Sync),
to: &'a <T as System>::Address,
amount: T::Balance,
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<T::Hash, substrate_subxt::Error>> + Send + 'a>> {
let _ = core::marker::PhantomData::<T>;
Box::pin(self.submit(TransferCall { to, amount, }, signer))
}
fn transfer_and_watch<'a>(
&'a self,
signer: &'a (dyn substrate_subxt::Signer<T, S, E> + Send + Sync),
to: &'a <T as System>::Address,
amount: T::Balance,
) -> core::pin::Pin<Box<dyn core::future::Future<Output = Result<substrate_subxt::ExtrinsicSuccess<T>, substrate_subxt::Error>> + Send + 'a>> {
let _ = core::marker::PhantomData::<T>;
Box::pin(self.submit(TransferCall { to, amount, }))
Box::pin(self.watch(TransferCall { to, amount, }, signer))
}
}
};
+10 -18
View File
@@ -228,7 +228,7 @@ impl Test {
let prelude = prelude.map(|block| block.stmts).unwrap_or_default();
let step = steps
.into_iter()
.map(|step| step.into_tokens(&account, state.as_ref()));
.map(|step| step.into_tokens(state.as_ref()));
quote! {
#[async_std::test]
#[ignore]
@@ -236,6 +236,8 @@ impl Test {
#env_logger
let client = #subxt::ClientBuilder::<#runtime, #signature, #extra>::new()
.build().await.unwrap();
let signer = #subxt::PairSigner::new(#sp_keyring::AccountKeyring::#account.pair());
#[allow(unused)]
let alice = #sp_keyring::AccountKeyring::Alice.to_account_id();
#[allow(unused)]
@@ -304,12 +306,7 @@ impl From<ItemStep> for Step {
}
impl Step {
fn into_tokens(
self,
account: &syn::Ident,
test_state: Option<&State>,
) -> TokenStream {
let sp_keyring = utils::use_crate("sp-keyring");
fn into_tokens(self, test_state: Option<&State>) -> TokenStream {
let Step {
state,
call,
@@ -359,14 +356,11 @@ impl Step {
});
let assert = assert.map(|block| block.stmts).unwrap_or_default();
quote! {
let xt = client.xt(#sp_keyring::AccountKeyring::#account.pair(), None).await.unwrap();
#pre
#[allow(unused)]
let result = xt
.watch()
.submit(#call)
let result = client
.watch(#call, &signer)
.await
.unwrap();
@@ -461,6 +455,7 @@ mod tests {
substrate_subxt::sp_runtime::MultiSignature,
substrate_subxt::DefaultExtra<KusamaRuntime>
>::new().build().await.unwrap();
let signer = substrate_subxt::PairSigner::new(sp_keyring::AccountKeyring::Alice.pair());
#[allow(unused)]
let alice = sp_keyring::AccountKeyring::Alice.to_account_id();
#[allow(unused)]
@@ -475,8 +470,6 @@ mod tests {
let ferdie = sp_keyring::AccountKeyring::Ferdie.to_account_id();
{
let xt = client.xt(sp_keyring::AccountKeyring::Alice.pair(), None).await.unwrap();
struct State<A, B> {
alice: A,
bob: B,
@@ -495,12 +488,11 @@ mod tests {
};
#[allow(unused)]
let result = xt
.watch()
.submit(TransferCall {
let result = client
.watch(TransferCall {
to: &bob,
amount: 10_000,
})
}, &signer)
.await
.unwrap();
+7 -6
View File
@@ -36,6 +36,7 @@ use substrate_subxt::{
},
ClientBuilder,
KusamaRuntime,
PairSigner,
};
#[module]
@@ -112,6 +113,7 @@ subxt_test!({
async fn transfer_balance_example() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
let client = ClientBuilder::<KusamaRuntime>::new().build().await?;
let signer = PairSigner::new(AccountKeyring::Alice.pair());
let alice = AccountKeyring::Alice.to_account_id();
let bob = AccountKeyring::Bob.to_account_id();
@@ -119,13 +121,12 @@ async fn transfer_balance_example() -> Result<(), Box<dyn std::error::Error>> {
let bob_account = client.account(&bob).await?;
let pre = (alice_account, bob_account);
let builder = client.xt(AccountKeyring::Alice.pair(), None).await?;
let _hash = client
.transfer(&signer, &bob.clone().into(), 10_000)
.await?;
let _hash = builder.transfer(&bob.clone().into(), 10_000).await?;
let result = builder
.watch()
.transfer(&bob.clone().into(), 10_000)
let result = client
.transfer_and_watch(&signer, &bob.clone().into(), 10_000)
.await?;
assert_eq!(
+2 -41
View File
@@ -15,7 +15,6 @@
// along with substrate-subxt. If not, see <http://www.gnu.org/licenses/>.
use codec::{
Codec,
Decode,
Encode,
};
@@ -23,18 +22,9 @@ use core::{
fmt::Debug,
marker::PhantomData,
};
use sp_core::Pair;
use sp_runtime::{
generic::{
Era,
SignedPayload,
UncheckedExtrinsic,
},
traits::{
IdentifyAccount,
SignedExtension,
Verify,
},
generic::Era,
traits::SignedExtension,
transaction_validity::TransactionValidityError,
};
@@ -289,32 +279,3 @@ impl<T: System + Balances + Clone + Debug + Eq + Send + Sync> SignedExtension
self.extra().additional_signed()
}
}
pub(crate) fn create_and_sign<T: System + Send + Sync, C, P, S, E>(
signer: P,
call: C,
extra: E,
) -> Result<
UncheckedExtrinsic<T::Address, C, S, <E as SignedExtra<T>>::Extra>,
TransactionValidityError,
>
where
P: Pair,
S: Verify + Codec + From<P::Signature>,
S::Signer: From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
C: Encode,
E: SignedExtra<T> + SignedExtension,
T::Address: From<T::AccountId>,
{
let raw_payload = SignedPayload::new(call, extra.extra())?;
let signature = raw_payload.using_encoded(|payload| signer.sign(payload));
let (call, extra, _) = raw_payload.deconstruct();
let account_id = S::Signer::from(signer.public()).into_account();
Ok(UncheckedExtrinsic::new_signed(
call,
account_id.into(),
signature.into(),
extra,
))
}
+132 -230
View File
@@ -45,46 +45,36 @@ extern crate substrate_subxt_proc_macro;
pub use sp_core;
pub use sp_runtime;
use std::{
convert::TryFrom,
marker::PhantomData,
};
use codec::{
Codec,
Encode,
};
use codec::Encode;
use futures::future;
use jsonrpsee::client::Subscription;
use sc_rpc_api::state::ReadProof;
use sp_core::{
storage::{
StorageChangeSet,
StorageKey,
},
Pair,
use sp_core::storage::{
StorageChangeSet,
StorageKey,
};
use sp_runtime::{
generic::{
SignedPayload,
UncheckedExtrinsic,
},
traits::{
IdentifyAccount,
SignedExtension,
Verify,
},
traits::SignedExtension,
MultiSignature,
};
use sp_version::RuntimeVersion;
use std::{
convert::TryFrom,
marker::PhantomData,
};
mod error;
mod events;
mod extrinsic;
mod extra;
mod frame;
mod metadata;
mod rpc;
mod runtimes;
mod signer;
pub use crate::{
error::Error,
@@ -93,7 +83,7 @@ pub use crate::{
EventsError,
RawEvent,
},
extrinsic::*,
extra::*,
frame::*,
metadata::{
Metadata,
@@ -104,17 +94,15 @@ pub use crate::{
ExtrinsicSuccess,
},
runtimes::*,
signer::*,
substrate_subxt_proc_macro::*,
};
use crate::{
frame::{
balances::Balances,
system::{
AccountStoreExt,
Phase,
System,
SystemEvent,
},
frame::system::{
AccountStoreExt,
Phase,
System,
SystemEvent,
},
rpc::{
ChainBlock,
@@ -283,28 +271,6 @@ impl<T: System, S, E> Client<T, S, E> {
Ok(proof)
}
/// Create and submit an extrinsic and return corresponding Hash if successful
pub async fn submit_extrinsic<X: Encode>(
&self,
extrinsic: X,
) -> Result<T::Hash, Error> {
let xt_hash = self.rpc.submit_extrinsic(extrinsic).await?;
Ok(xt_hash)
}
/// Create and submit an extrinsic and return corresponding Event if successful
pub async fn submit_and_watch_extrinsic<X: Encode + 'static>(
self,
extrinsic: X,
decoder: EventsDecoder<T>,
) -> Result<ExtrinsicSuccess<T>, Error> {
let success = self
.rpc
.submit_and_watch_extrinsic(extrinsic, decoder)
.await?;
Ok(success)
}
/// Subscribe to events.
pub async fn subscribe_events(
&self,
@@ -330,17 +296,24 @@ impl<T: System, S, E> Client<T, S, E> {
impl<T, S, E> Client<T, S, E>
where
T: System + Balances + Send + Sync + 'static,
S: 'static,
E: SignedExtra<T> + SignedExtension + 'static,
T: System + Send + Sync + 'static,
S: Encode + Send + Sync + 'static,
E: SignedExtra<T> + SignedExtension + Send + Sync + 'static,
{
/// Creates raw payload to be signed for the supplied `Call` without private key
pub async fn create_raw_payload<C: Call<T>>(
/// Creates an unsigned extrinsic.
///
/// If `nonce` is `None` the nonce will be fetched from the chain.
pub async fn create_unsigned<C: Call<T>>(
&self,
account_id: &<T as System>::AccountId,
call: C,
account_id: &<T as System>::AccountId,
nonce: Option<T::Index>,
) -> Result<SignedPayload<Encoded, <E as SignedExtra<T>>::Extra>, Error> {
let account_nonce = self.account(account_id).await?.nonce;
let account_nonce = if let Some(nonce) = nonce {
nonce
} else {
self.account(account_id).await?.nonce
};
let version = self.runtime_version.spec_version;
let genesis_hash = self.genesis_hash;
let call = self
@@ -352,168 +325,77 @@ where
Ok(raw_payload)
}
/// Create a transaction builder for a private key.
pub async fn xt<P>(
&self,
signer: P,
nonce: Option<T::Index>,
) -> Result<XtBuilder<T, P, S, E>, Error>
where
P: Pair,
P::Signature: Codec,
S: Verify,
S::Signer: From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
{
let account_id = S::Signer::from(signer.public()).into_account();
let nonce = match nonce {
Some(nonce) => nonce,
None => self.account(&account_id).await?.nonce,
};
let genesis_hash = self.genesis_hash;
let runtime_version = self.runtime_version.clone();
Ok(XtBuilder {
client: self.clone(),
nonce,
runtime_version,
genesis_hash,
signer,
})
}
}
/// Transaction builder.
#[derive(Clone)]
pub struct XtBuilder<T: System, P, S, E> {
client: Client<T, S, E>,
nonce: T::Index,
runtime_version: RuntimeVersion,
genesis_hash: T::Hash,
signer: P,
}
impl<T: System, P, S, E> XtBuilder<T, P, S, E> {
/// Returns the chain metadata.
pub fn metadata(&self) -> &Metadata {
self.client.metadata()
}
/// Returns the nonce.
pub fn nonce(&self) -> T::Index {
self.nonce
}
/// Sets the nonce to a new value.
pub fn set_nonce(&mut self, nonce: T::Index) -> &mut XtBuilder<T, P, S, E> {
self.nonce = nonce;
self
}
/// Increment the nonce
pub fn increment_nonce(&mut self) -> &mut XtBuilder<T, P, S, E> {
self.set_nonce(self.nonce() + 1.into());
self
}
}
impl<T: System + Send + Sync + 'static, P, S: 'static, E> XtBuilder<T, P, S, E>
where
P: Pair,
S: Verify + Codec + From<P::Signature>,
S::Signer: From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
T::Address: From<T::AccountId>,
E: SignedExtra<T> + SignedExtension + 'static,
{
/// Creates and signs an Extrinsic for the supplied `Call`
pub fn create_and_sign<C: Call<T>>(
/// Creates a signed extrinsic.
pub async fn create_signed<C: Call<T>>(
&self,
call: C,
signer: &(dyn Signer<T, S, E> + Send + Sync),
) -> Result<
UncheckedExtrinsic<T::Address, Encoded, S, <E as SignedExtra<T>>::Extra>,
Error,
> {
let signer = self.signer.clone();
let account_nonce = self.nonce;
let version = self.runtime_version.spec_version;
let genesis_hash = self.genesis_hash;
let call = self
.metadata()
.module_with_calls(C::MODULE)
.and_then(|module| module.call(C::FUNCTION, call))?;
let unsigned = self
.create_unsigned(call, signer.account_id(), signer.nonce())
.await?;
Ok(signer.sign(unsigned))
}
log::info!(
"Creating Extrinsic with genesis hash {:?} and account nonce {:?}",
genesis_hash,
account_nonce
);
/// Returns an events decoder for a call.
pub fn events_decoder<C: Call<T>>(&self) -> Result<EventsDecoder<T>, Error> {
let metadata = self.metadata().clone();
let mut decoder = EventsDecoder::try_from(metadata)?;
C::events_decoder(&mut decoder)?;
Ok(decoder)
}
let extra = E::new(version, account_nonce, genesis_hash);
let xt = extrinsic::create_and_sign::<_, _, _, S, _>(signer, call, extra)?;
Ok(xt)
/// Create and submit an extrinsic and return corresponding Hash if successful
pub async fn submit_extrinsic(
&self,
extrinsic: UncheckedExtrinsic<
T::Address,
Encoded,
S,
<E as SignedExtra<T>>::Extra,
>,
) -> Result<T::Hash, Error> {
self.rpc.submit_extrinsic(extrinsic).await
}
/// Create and submit an extrinsic and return corresponding Event if successful
pub async fn submit_and_watch_extrinsic(
&self,
extrinsic: UncheckedExtrinsic<
T::Address,
Encoded,
S,
<E as SignedExtra<T>>::Extra,
>,
decoder: EventsDecoder<T>,
) -> Result<ExtrinsicSuccess<T>, Error> {
self.rpc
.submit_and_watch_extrinsic(extrinsic, decoder)
.await
}
/// Submits a transaction to the chain.
pub async fn submit<C: Call<T>>(&self, call: C) -> Result<T::Hash, Error> {
let extrinsic = self.create_and_sign(call)?;
let xt_hash = self.client.submit_extrinsic(extrinsic).await?;
Ok(xt_hash)
pub async fn submit<C: Call<T>>(
&self,
call: C,
signer: &(dyn Signer<T, S, E> + Send + Sync),
) -> Result<T::Hash, Error> {
let extrinsic = self.create_signed(call, signer).await?;
self.submit_extrinsic(extrinsic).await
}
/// Submits transaction to the chain and watch for events.
pub fn watch(self) -> EventsSubscriber<T, P, S, E> {
let metadata = self.client.metadata().clone();
let decoder = EventsDecoder::try_from(metadata).map_err(Into::into);
EventsSubscriber {
client: self.client.clone(),
builder: self,
decoder,
}
}
}
/// Submits an extrinsic and subscribes to the triggered events
pub struct EventsSubscriber<T: System, P, S, E> {
client: Client<T, S, E>,
builder: XtBuilder<T, P, S, E>,
decoder: Result<EventsDecoder<T>, EventsError>,
}
impl<T: System, P, S, E> EventsSubscriber<T, P, S, E> {
/// Access the events decoder for registering custom type sizes
pub fn events_decoder<
F: FnOnce(&mut EventsDecoder<T>) -> Result<usize, EventsError>,
>(
self,
f: F,
) -> Self {
let mut this = self;
if let Ok(ref mut decoder) = this.decoder {
if let Err(err) = f(decoder) {
this.decoder = Err(err)
}
}
this
}
}
impl<T: System + Send + Sync + 'static, P, S: 'static, E> EventsSubscriber<T, P, S, E>
where
P: Pair,
S: Verify + Codec + From<P::Signature>,
S::Signer: From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
T::Address: From<T::AccountId>,
E: SignedExtra<T> + SignedExtension + 'static,
{
/// Submits transaction to the chain and watch for events.
pub async fn submit<C: Call<T>>(self, call: C) -> Result<ExtrinsicSuccess<T>, Error> {
let mut decoder = self.decoder?;
C::events_decoder(&mut decoder)?;
let extrinsic = self.builder.create_and_sign(call)?;
let xt_success = self
.client
.submit_and_watch_extrinsic(extrinsic, decoder)
.await?;
Ok(xt_success)
pub async fn watch<C: Call<T>>(
&self,
call: C,
signer: &(dyn Signer<T, S, E> + Send + Sync),
) -> Result<ExtrinsicSuccess<T>, Error> {
let extrinsic = self.create_signed(call, signer).await?;
let decoder = self.events_decoder::<C>()?;
self.submit_and_watch_extrinsic(extrinsic, decoder).await
}
}
@@ -530,9 +412,12 @@ impl codec::Encode for Encoded {
#[cfg(test)]
mod tests {
use sp_core::storage::{
well_known_keys,
StorageKey,
use sp_core::{
storage::{
well_known_keys,
StorageKey,
},
Pair,
};
use sp_keyring::{
AccountKeyring,
@@ -552,25 +437,37 @@ mod tests {
#[ignore] // requires locally running substrate node
async fn test_tx_transfer_balance() {
env_logger::try_init().ok();
let signer = AccountKeyring::Alice.pair();
let mut signer = PairSigner::new(AccountKeyring::Alice.pair());
let dest = AccountKeyring::Bob.to_account_id().into();
let client = test_client().await;
let mut xt = client.xt(signer, None).await.unwrap();
let _ = xt
.submit(balances::TransferCall {
to: &dest,
amount: 10_000,
})
let nonce = client
.account(&AccountKeyring::Alice.to_account_id())
.await
.unwrap()
.nonce;
signer.set_nonce(nonce);
client
.submit(
balances::TransferCall {
to: &dest,
amount: 10_000,
},
&signer,
)
.await
.unwrap();
// check that nonce is handled correctly
xt.increment_nonce()
.submit(balances::TransferCall {
to: &dest,
amount: 10_000,
})
signer.increment_nonce();
client
.submit(
balances::TransferCall {
to: &dest,
amount: 10_000,
},
&signer,
)
.await
.unwrap();
}
@@ -634,12 +531,13 @@ mod tests {
// create raw payload with AccoundId and sign it
let raw_payload = client
.create_raw_payload(
&signer_account_id,
.create_unsigned(
balances::TransferCall {
to: &dest,
amount: 10_000,
},
&signer_account_id,
None,
)
.await
.unwrap();
@@ -647,12 +545,16 @@ mod tests {
let raw_multisig = MultiSignature::from(raw_signature);
// create signature with Xtbuilder
let xt = client.xt(signer_pair.clone(), None).await.unwrap();
let xt_multi_sig = xt
.create_and_sign(balances::TransferCall {
to: &dest,
amount: 10_000,
})
let signer = PairSigner::new(Ed25519Keyring::Alice.pair());
let xt_multi_sig = client
.create_signed(
balances::TransferCall {
to: &dest,
amount: 10_000,
},
&signer,
)
.await
.unwrap()
.signature
.unwrap()
+1 -1
View File
@@ -342,7 +342,7 @@ impl<T: System> Rpc<T> {
/// Create and submit an extrinsic and return corresponding Event if successful
pub async fn submit_and_watch_extrinsic<E: Encode + 'static>(
self,
&self,
extrinsic: E,
decoder: EventsDecoder<T>,
) -> Result<ExtrinsicSuccess<T>, Error> {
+122
View File
@@ -0,0 +1,122 @@
// Copyright 2019-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 <http://www.gnu.org/licenses/>.
//! A library to **sub**mit e**xt**rinsics to a
//! [substrate](https://github.com/paritytech/substrate) node via RPC.
use crate::{
extra::SignedExtra,
frame::system::System,
Encoded,
};
use codec::Encode;
use sp_core::Pair;
use sp_runtime::{
generic::{
SignedPayload,
UncheckedExtrinsic,
},
traits::{
IdentifyAccount,
Verify,
},
};
use std::marker::PhantomData;
/// Extrinsic signer.
pub trait Signer<T: System, S: Encode, E: SignedExtra<T>> {
/// Returns the account id.
fn account_id(&self) -> &T::AccountId;
/// Optionally returns a nonce.
fn nonce(&self) -> Option<T::Index>;
/// Takes an unsigned extrinsic and returns a signed extrinsic.
fn sign(
&self,
extrinsic: SignedPayload<Encoded, E::Extra>,
) -> UncheckedExtrinsic<T::Address, Encoded, S, E::Extra>;
}
/// Extrinsic signer using a private key.
pub struct PairSigner<T: System, S: Encode, E: SignedExtra<T>, P: Pair> {
_marker: PhantomData<(S, E)>,
account_id: T::AccountId,
nonce: Option<T::Index>,
signer: P,
}
impl<T, S, E, P> PairSigner<T, S, E, P>
where
T: System,
S: Encode + Verify + From<P::Signature>,
S::Signer: From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
E: SignedExtra<T>,
P: Pair,
{
/// Creates a new `Signer` from a `Pair`.
pub fn new(signer: P) -> Self {
let account_id = S::Signer::from(signer.public()).into_account();
Self {
_marker: PhantomData,
account_id,
nonce: None,
signer,
}
}
/// Sets the nonce to a new value.
pub fn set_nonce(&mut self, nonce: T::Index) {
self.nonce = Some(nonce);
}
/// Increment the nonce
pub fn increment_nonce(&mut self) {
self.nonce = self.nonce.map(|nonce| nonce + 1.into());
}
}
impl<T, S, E, P> Signer<T, S, E> for PairSigner<T, S, E, P>
where
T: System,
T::AccountId: Into<T::Address>,
S: Encode,
E: SignedExtra<T>,
P: Pair,
P::Signature: Into<S>,
{
fn account_id(&self) -> &T::AccountId {
&self.account_id
}
fn nonce(&self) -> Option<T::Index> {
self.nonce
}
fn sign(
&self,
extrinsic: SignedPayload<Encoded, E::Extra>,
) -> UncheckedExtrinsic<T::Address, Encoded, S, E::Extra> {
let signature = extrinsic.using_encoded(|payload| self.signer.sign(payload));
let (call, extra, _) = extrinsic.deconstruct();
UncheckedExtrinsic::new_signed(
call,
self.account_id.clone().into(),
signature.into(),
extra,
)
}
}