mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-14 01:41:09 +00:00
Merge branch 'master' into staking
This commit is contained in:
+52
-8
@@ -19,15 +19,19 @@ use jsonrpsee::{
|
||||
transport::ws::WsNewDnsError,
|
||||
};
|
||||
use sp_core::crypto::SecretStringError;
|
||||
use sp_runtime::transaction_validity::TransactionValidityError;
|
||||
use sp_runtime::{
|
||||
transaction_validity::TransactionValidityError,
|
||||
DispatchError,
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
events::EventsError,
|
||||
metadata::MetadataError,
|
||||
use crate::metadata::{
|
||||
Metadata,
|
||||
MetadataError,
|
||||
};
|
||||
|
||||
/// Error enum.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
/// Io error.
|
||||
#[error("Io error: {0}")]
|
||||
@@ -50,12 +54,21 @@ pub enum Error {
|
||||
/// Extrinsic validity error
|
||||
#[error("Transaction Validity Error: {0:?}")]
|
||||
Invalid(TransactionValidityError),
|
||||
/// Events error.
|
||||
#[error("Event error: {0}")]
|
||||
Events(#[from] EventsError),
|
||||
/// Metadata error.
|
||||
#[error("Metadata error: {0}")]
|
||||
Metadata(#[from] MetadataError),
|
||||
/// Type size unavailable.
|
||||
#[error("Type size unavailable while decoding event: {0:?}")]
|
||||
TypeSizeUnavailable(String),
|
||||
/// Runtime error.
|
||||
#[error("Runtime error: {0}")]
|
||||
Runtime(RuntimeError),
|
||||
/// Bad origin.
|
||||
#[error("Bad origin: throw by ensure_signed, ensure_root or ensure_none.")]
|
||||
BadOrigin,
|
||||
/// Cannot lookup.
|
||||
#[error("Cannot lookup some information required to validate the transaction.")]
|
||||
CannotLookup,
|
||||
/// Other error.
|
||||
#[error("Other error: {0}")]
|
||||
Other(String),
|
||||
@@ -84,3 +97,34 @@ impl From<String> for Error {
|
||||
Error::Other(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Converts a `DispatchError` into a subxt error.
|
||||
pub fn from_dispatch(metadata: &Metadata, error: DispatchError) -> Result<(), Self> {
|
||||
match error {
|
||||
DispatchError::Module {
|
||||
index,
|
||||
error,
|
||||
message: _,
|
||||
} => {
|
||||
let module = metadata.module_with_errors(index)?;
|
||||
let error = module.error(error)?;
|
||||
Err(Error::Runtime(RuntimeError {
|
||||
module: module.name().to_string(),
|
||||
error: error.to_string(),
|
||||
}))
|
||||
}
|
||||
DispatchError::BadOrigin => Err(Error::BadOrigin),
|
||||
DispatchError::CannotLookup => Err(Error::CannotLookup),
|
||||
DispatchError::Other(msg) => Err(Error::Other(msg.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime errors.
|
||||
#[derive(Clone, Debug, Eq, Error, PartialEq)]
|
||||
#[error("{error} from {module}")]
|
||||
pub struct RuntimeError {
|
||||
pub module: String,
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
+41
-64
@@ -19,10 +19,14 @@ use codec::{
|
||||
Compact,
|
||||
Decode,
|
||||
Encode,
|
||||
Error as CodecError,
|
||||
Input,
|
||||
Output,
|
||||
};
|
||||
use frame_support::dispatch::DispatchInfo;
|
||||
use sp_runtime::{
|
||||
DispatchError,
|
||||
DispatchResult,
|
||||
};
|
||||
use std::{
|
||||
collections::{
|
||||
HashMap,
|
||||
@@ -33,26 +37,17 @@ use std::{
|
||||
Send,
|
||||
},
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
error::Error,
|
||||
metadata::{
|
||||
EventArg,
|
||||
Metadata,
|
||||
MetadataError,
|
||||
},
|
||||
Phase,
|
||||
System,
|
||||
SystemEvent,
|
||||
};
|
||||
|
||||
/// Top level Event that can be produced by a substrate runtime
|
||||
#[derive(Debug)]
|
||||
pub enum RuntimeEvent<T: System> {
|
||||
System(SystemEvent<T>),
|
||||
Raw(RawEvent),
|
||||
}
|
||||
|
||||
/// Raw bytes for an Event
|
||||
#[derive(Debug)]
|
||||
pub struct RawEvent {
|
||||
@@ -64,20 +59,6 @@ pub struct RawEvent {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Events error.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum EventsError {
|
||||
/// Codec error.
|
||||
#[error("Scale codec error: {0:?}")]
|
||||
CodecError(#[from] CodecError),
|
||||
/// Metadata error.
|
||||
#[error("Metadata error: {0:?}")]
|
||||
Metadata(#[from] MetadataError),
|
||||
/// Type size unavailable.
|
||||
#[error("Type Sizes Unavailable: {0:?}")]
|
||||
TypeSizeUnavailable(String),
|
||||
}
|
||||
|
||||
/// Event decoder.
|
||||
#[derive(Debug)]
|
||||
pub struct EventsDecoder<T> {
|
||||
@@ -95,6 +76,8 @@ impl<T: System> EventsDecoder<T> {
|
||||
marker: PhantomData,
|
||||
};
|
||||
// register default event arg type sizes for dynamic decoding of events
|
||||
decoder.register_type_size::<()>("PhantomData");
|
||||
decoder.register_type_size::<DispatchInfo>("DispatchInfo");
|
||||
decoder.register_type_size::<bool>("bool");
|
||||
decoder.register_type_size::<u32>("ReferendumIndex");
|
||||
decoder.register_type_size::<[u8; 16]>("Kind");
|
||||
@@ -132,10 +115,7 @@ impl<T: System> EventsDecoder<T> {
|
||||
for event in module.events() {
|
||||
for arg in event.arguments() {
|
||||
for primitive in arg.primitives() {
|
||||
if module.name() != "System"
|
||||
&& !self.type_sizes.contains_key(&primitive)
|
||||
&& !primitive.contains("PhantomData")
|
||||
{
|
||||
if !self.type_sizes.contains_key(&primitive) {
|
||||
missing.insert(format!(
|
||||
"{}::{}::{}",
|
||||
module.name(),
|
||||
@@ -161,7 +141,7 @@ impl<T: System> EventsDecoder<T> {
|
||||
args: &[EventArg],
|
||||
input: &mut I,
|
||||
output: &mut W,
|
||||
) -> Result<(), EventsError> {
|
||||
) -> Result<(), Error> {
|
||||
for arg in args {
|
||||
match arg {
|
||||
EventArg::Vec(arg) => {
|
||||
@@ -173,16 +153,22 @@ impl<T: System> EventsDecoder<T> {
|
||||
}
|
||||
EventArg::Tuple(args) => self.decode_raw_bytes(args, input, output)?,
|
||||
EventArg::Primitive(name) => {
|
||||
if name.contains("PhantomData") {
|
||||
// PhantomData is size 0
|
||||
return Ok(())
|
||||
}
|
||||
if let Some(size) = self.type_sizes.get(name) {
|
||||
let mut buf = vec![0; *size];
|
||||
input.read(&mut buf)?;
|
||||
output.write(&buf);
|
||||
} else {
|
||||
return Err(EventsError::TypeSizeUnavailable(name.to_owned()))
|
||||
let result = match name.as_str() {
|
||||
"DispatchResult" => DispatchResult::decode(input)?,
|
||||
"DispatchError" => Err(DispatchError::decode(input)?),
|
||||
_ => {
|
||||
if let Some(size) = self.type_sizes.get(name) {
|
||||
let mut buf = vec![0; *size];
|
||||
input.read(&mut buf)?;
|
||||
output.write(&buf);
|
||||
Ok(())
|
||||
} else {
|
||||
return Err(Error::TypeSizeUnavailable(name.to_owned()))
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Err(error) = result {
|
||||
Error::from_dispatch(&self.metadata, error)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -194,7 +180,7 @@ impl<T: System> EventsDecoder<T> {
|
||||
pub fn decode_events(
|
||||
&self,
|
||||
input: &mut &[u8],
|
||||
) -> Result<Vec<(Phase, RuntimeEvent<T>)>, EventsError> {
|
||||
) -> Result<Vec<(Phase, RawEvent)>, Error> {
|
||||
let compact_len = <Compact<u32>>::decode(input)?;
|
||||
let len = compact_len.0 as usize;
|
||||
|
||||
@@ -205,33 +191,24 @@ impl<T: System> EventsDecoder<T> {
|
||||
let module_variant = input.read_byte()?;
|
||||
|
||||
let module = self.metadata.module_with_events(module_variant)?;
|
||||
let event = if module.name() == "System" {
|
||||
let system_event = SystemEvent::decode(input)?;
|
||||
RuntimeEvent::System(system_event)
|
||||
} else {
|
||||
let event_variant = input.read_byte()?;
|
||||
let event_metadata = module.event(event_variant)?;
|
||||
let event_variant = input.read_byte()?;
|
||||
let event_metadata = module.event(event_variant)?;
|
||||
|
||||
log::debug!(
|
||||
"received event '{}::{}'",
|
||||
module.name(),
|
||||
event_metadata.name
|
||||
);
|
||||
log::debug!(
|
||||
"received event '{}::{}'",
|
||||
module.name(),
|
||||
event_metadata.name
|
||||
);
|
||||
|
||||
let mut event_data = Vec::<u8>::new();
|
||||
self.decode_raw_bytes(
|
||||
&event_metadata.arguments(),
|
||||
input,
|
||||
&mut event_data,
|
||||
)?;
|
||||
let mut event_data = Vec::<u8>::new();
|
||||
self.decode_raw_bytes(&event_metadata.arguments(), input, &mut event_data)?;
|
||||
|
||||
log::debug!("raw bytes: {}", hex::encode(&event_data),);
|
||||
log::debug!("raw bytes: {}", hex::encode(&event_data),);
|
||||
|
||||
RuntimeEvent::Raw(RawEvent {
|
||||
module: module.name().to_string(),
|
||||
variant: event_metadata.name.clone(),
|
||||
data: event_data,
|
||||
})
|
||||
let event = RawEvent {
|
||||
module: module.name().to_string(),
|
||||
variant: event_metadata.name.clone(),
|
||||
data: event_data,
|
||||
};
|
||||
|
||||
// topics come after the event data in EventRecord
|
||||
|
||||
+2
-2
@@ -222,9 +222,9 @@ where
|
||||
}
|
||||
|
||||
/// Trait for implementing transaction extras for a runtime.
|
||||
pub trait SignedExtra<T: System> {
|
||||
pub trait SignedExtra<T: System>: SignedExtension {
|
||||
/// The type the extras.
|
||||
type Extra: SignedExtension;
|
||||
type Extra: SignedExtension + Send + Sync;
|
||||
|
||||
/// Creates a new `SignedExtra`.
|
||||
fn new(
|
||||
|
||||
+96
-26
@@ -110,36 +110,58 @@ pub struct TransferEvent<T: Balances> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
system::{
|
||||
AccountStore,
|
||||
AccountStoreExt,
|
||||
error::{
|
||||
Error,
|
||||
RuntimeError,
|
||||
},
|
||||
tests::test_client,
|
||||
events::EventsDecoder,
|
||||
signer::{
|
||||
PairSigner,
|
||||
Signer,
|
||||
},
|
||||
subscription::EventSubscription,
|
||||
system::AccountStoreExt,
|
||||
tests::{
|
||||
test_client,
|
||||
TestRuntime,
|
||||
},
|
||||
};
|
||||
use sp_core::{
|
||||
sr25519::Pair,
|
||||
Pair as _,
|
||||
};
|
||||
use sp_keyring::AccountKeyring;
|
||||
|
||||
subxt_test!({
|
||||
name: test_transfer,
|
||||
step: {
|
||||
state: {
|
||||
alice: AccountStore { account_id: &alice },
|
||||
bob: AccountStore { account_id: &bob },
|
||||
},
|
||||
call: TransferCall {
|
||||
to: &bob.clone().into(),
|
||||
amount: 10_000,
|
||||
},
|
||||
event: TransferEvent {
|
||||
from: alice.clone(),
|
||||
to: bob.clone(),
|
||||
amount: 10_000,
|
||||
},
|
||||
assert: {
|
||||
assert!(pre.alice.data.free - 10_000 >= post.alice.data.free);
|
||||
assert_eq!(pre.bob.data.free + 10_000, post.bob.data.free);
|
||||
},
|
||||
},
|
||||
});
|
||||
#[async_std::test]
|
||||
async fn test_transfer() {
|
||||
env_logger::try_init().ok();
|
||||
let alice = PairSigner::<TestRuntime, _>::new(AccountKeyring::Alice.pair());
|
||||
let bob = PairSigner::<TestRuntime, _>::new(AccountKeyring::Bob.pair());
|
||||
let (client, _) = test_client().await;
|
||||
|
||||
let alice_pre = client.account(alice.account_id(), None).await.unwrap();
|
||||
let bob_pre = client.account(bob.account_id(), None).await.unwrap();
|
||||
|
||||
let event = client
|
||||
.transfer_and_watch(&alice, &bob.account_id(), 10_000)
|
||||
.await
|
||||
.unwrap()
|
||||
.transfer()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let expected_event = TransferEvent {
|
||||
from: alice.account_id().clone(),
|
||||
to: bob.account_id().clone(),
|
||||
amount: 10_000,
|
||||
};
|
||||
assert_eq!(event, expected_event);
|
||||
|
||||
let alice_post = client.account(alice.account_id(), None).await.unwrap();
|
||||
let bob_post = client.account(bob.account_id(), None).await.unwrap();
|
||||
|
||||
assert!(alice_pre.data.free - 10_000 >= alice_post.data.free);
|
||||
assert_eq!(bob_pre.data.free + 10_000, bob_post.data.free);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn test_state_total_issuance() {
|
||||
@@ -157,4 +179,52 @@ mod tests {
|
||||
let info = client.account(&account, None).await.unwrap();
|
||||
assert_ne!(info.data.free, 0);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn test_transfer_error() {
|
||||
env_logger::try_init().ok();
|
||||
let alice = PairSigner::new(AccountKeyring::Alice.pair());
|
||||
let hans = PairSigner::new(Pair::generate().0);
|
||||
let (client, _) = test_client().await;
|
||||
client
|
||||
.transfer_and_watch(&alice, hans.account_id(), 100_000_000_000)
|
||||
.await
|
||||
.unwrap();
|
||||
let res = client
|
||||
.transfer_and_watch(&hans, alice.account_id(), 100_000_000_000)
|
||||
.await;
|
||||
if let Err(Error::Runtime(error)) = res {
|
||||
let error2 = RuntimeError {
|
||||
module: "Balances".into(),
|
||||
error: "InsufficientBalance".into(),
|
||||
};
|
||||
assert_eq!(error, error2);
|
||||
} else {
|
||||
panic!("expected an error");
|
||||
}
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn test_transfer_subscription() {
|
||||
env_logger::try_init().ok();
|
||||
let alice = PairSigner::new(AccountKeyring::Alice.pair());
|
||||
let bob = AccountKeyring::Bob.to_account_id();
|
||||
let (client, _) = test_client().await;
|
||||
let sub = client.subscribe_events().await.unwrap();
|
||||
let mut decoder = EventsDecoder::<TestRuntime>::new(client.metadata().clone());
|
||||
decoder.with_balances();
|
||||
let mut sub = EventSubscription::<TestRuntime>::new(sub, decoder);
|
||||
sub.filter_event::<TransferEvent<_>>();
|
||||
client.transfer(&alice, &bob, 10_000).await.unwrap();
|
||||
let raw = sub.next().await.unwrap().unwrap();
|
||||
let event = TransferEvent::<TestRuntime>::decode(&mut &raw.data[..]).unwrap();
|
||||
assert_eq!(
|
||||
event,
|
||||
TransferEvent {
|
||||
from: alice.account_id().clone(),
|
||||
to: bob.clone(),
|
||||
amount: 10_000,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ pub mod balances;
|
||||
pub mod contracts;
|
||||
pub mod session;
|
||||
pub mod staking;
|
||||
pub mod sudo;
|
||||
pub mod system;
|
||||
|
||||
/// Store trait.
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// 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/>.
|
||||
|
||||
//! Implements support for the frame_sudo module.
|
||||
|
||||
use crate::{
|
||||
frame::system::{
|
||||
System,
|
||||
SystemEventsDecoder,
|
||||
},
|
||||
Encoded,
|
||||
};
|
||||
use codec::Encode;
|
||||
use core::marker::PhantomData;
|
||||
|
||||
/// The subset of the `frame_sudo::Trait` that a client must implement.
|
||||
#[module]
|
||||
pub trait Sudo: System {}
|
||||
|
||||
/// Execute a transaction with sudo permissions.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Call, Encode)]
|
||||
pub struct SudoCall<'a, T: Sudo> {
|
||||
/// Runtime marker.
|
||||
pub _runtime: PhantomData<T>,
|
||||
/// Encoded transaction.
|
||||
pub call: &'a Encoded,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
error::Error,
|
||||
frame::balances::TransferCall,
|
||||
signer::PairSigner,
|
||||
tests::{
|
||||
test_client,
|
||||
TestRuntime,
|
||||
},
|
||||
};
|
||||
use sp_keyring::AccountKeyring;
|
||||
|
||||
#[async_std::test]
|
||||
async fn test_sudo() {
|
||||
env_logger::try_init().ok();
|
||||
let alice = PairSigner::<TestRuntime, _>::new(AccountKeyring::Alice.pair());
|
||||
let (client, _) = test_client().await;
|
||||
|
||||
let call = client
|
||||
.encode(TransferCall {
|
||||
to: &AccountKeyring::Bob.to_account_id(),
|
||||
amount: 10_000,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let res = client.sudo_and_watch(&alice, &call).await;
|
||||
assert!(
|
||||
if let Err(Error::BadOrigin) = res {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+41
-15
@@ -157,21 +157,6 @@ pub struct SetCodeCall<'a, T: System> {
|
||||
pub code: &'a [u8],
|
||||
}
|
||||
|
||||
/// Event for the System module.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Decode)]
|
||||
pub enum SystemEvent<T: System> {
|
||||
/// An extrinsic completed successfully.
|
||||
ExtrinsicSuccess(DispatchInfo),
|
||||
/// An extrinsic failed.
|
||||
ExtrinsicFailed(DispatchError, DispatchInfo),
|
||||
/// `:code` was updated.
|
||||
CodeUpdated,
|
||||
/// A new account was created.
|
||||
NewAccount(T::AccountId),
|
||||
/// An account was reaped.
|
||||
KilledAccount(T::AccountId),
|
||||
}
|
||||
|
||||
/// A phase of a block's execution.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Decode)]
|
||||
pub enum Phase {
|
||||
@@ -180,3 +165,44 @@ pub enum Phase {
|
||||
/// The end.
|
||||
Finalization,
|
||||
}
|
||||
|
||||
/// An extrinsic completed successfully.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Event, Decode)]
|
||||
pub struct ExtrinsicSuccessEvent<T: System> {
|
||||
/// Runtime marker.
|
||||
pub _runtime: PhantomData<T>,
|
||||
/// The dispatch info.
|
||||
pub info: DispatchInfo,
|
||||
}
|
||||
|
||||
/// An extrinsic failed.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Event, Decode)]
|
||||
pub struct ExtrinsicFailedEvent<T: System> {
|
||||
/// Runtime marker.
|
||||
pub _runtime: PhantomData<T>,
|
||||
/// The dispatch error.
|
||||
pub error: DispatchError,
|
||||
/// The dispatch info.
|
||||
pub info: DispatchInfo,
|
||||
}
|
||||
|
||||
/// `:code` was updated.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Event, Decode)]
|
||||
pub struct CodeUpdatedEvent<T: System> {
|
||||
/// Runtime marker.
|
||||
pub _runtime: PhantomData<T>,
|
||||
}
|
||||
|
||||
/// A new account was created.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Event, Decode)]
|
||||
pub struct NewAccountEvent<T: System> {
|
||||
/// Created account id.
|
||||
pub account: T::AccountId,
|
||||
}
|
||||
|
||||
/// An account was reaped.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Event, Decode)]
|
||||
pub struct KilledAccountEvent<T: System> {
|
||||
/// Killed account id.
|
||||
pub account: T::AccountId,
|
||||
}
|
||||
|
||||
+51
-63
@@ -21,6 +21,7 @@
|
||||
bad_style,
|
||||
const_err,
|
||||
improper_ctypes,
|
||||
missing_docs,
|
||||
non_shorthand_field_patterns,
|
||||
no_mangle_generic_items,
|
||||
overflowing_literals,
|
||||
@@ -49,10 +50,7 @@ pub use substrate_subxt_client as client;
|
||||
pub use sp_core;
|
||||
pub use sp_runtime;
|
||||
|
||||
use codec::{
|
||||
Decode,
|
||||
Encode,
|
||||
};
|
||||
use codec::Decode;
|
||||
use futures::future;
|
||||
use jsonrpsee::client::Subscription;
|
||||
use sc_rpc_api::state::ReadProof;
|
||||
@@ -60,14 +58,7 @@ use sp_core::storage::{
|
||||
StorageChangeSet,
|
||||
StorageKey,
|
||||
};
|
||||
use sp_runtime::{
|
||||
generic::{
|
||||
SignedPayload,
|
||||
UncheckedExtrinsic,
|
||||
},
|
||||
traits::SignedExtension,
|
||||
MultiSignature,
|
||||
};
|
||||
pub use sp_runtime::traits::SignedExtension;
|
||||
use sp_version::RuntimeVersion;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -79,12 +70,12 @@ mod metadata;
|
||||
mod rpc;
|
||||
mod runtimes;
|
||||
mod signer;
|
||||
mod subscription;
|
||||
|
||||
pub use crate::{
|
||||
error::Error,
|
||||
events::{
|
||||
EventsDecoder,
|
||||
EventsError,
|
||||
RawEvent,
|
||||
},
|
||||
extra::*,
|
||||
@@ -99,6 +90,7 @@ pub use crate::{
|
||||
},
|
||||
runtimes::*,
|
||||
signer::*,
|
||||
subscription::*,
|
||||
substrate_subxt_proc_macro::*,
|
||||
};
|
||||
use crate::{
|
||||
@@ -106,7 +98,6 @@ use crate::{
|
||||
AccountStoreExt,
|
||||
Phase,
|
||||
System,
|
||||
SystemEvent,
|
||||
},
|
||||
rpc::{
|
||||
ChainBlock,
|
||||
@@ -117,13 +108,13 @@ use crate::{
|
||||
/// ClientBuilder for constructing a Client.
|
||||
#[derive(Default)]
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct ClientBuilder<T: System, S = MultiSignature, E = DefaultExtra<T>> {
|
||||
_marker: std::marker::PhantomData<(T, S, E)>,
|
||||
pub struct ClientBuilder<T: Runtime> {
|
||||
_marker: std::marker::PhantomData<T>,
|
||||
url: Option<String>,
|
||||
client: Option<jsonrpsee::Client>,
|
||||
}
|
||||
|
||||
impl<T: System + Send + Sync, S, E> ClientBuilder<T, S, E> {
|
||||
impl<T: Runtime> ClientBuilder<T> {
|
||||
/// Creates a new ClientBuilder.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
@@ -146,7 +137,7 @@ impl<T: System + Send + Sync, S, E> ClientBuilder<T, S, E> {
|
||||
}
|
||||
|
||||
/// Creates a new Client.
|
||||
pub async fn build(self) -> Result<Client<T, S, E>, Error> {
|
||||
pub async fn build(self) -> Result<Client<T>, Error> {
|
||||
let client = if let Some(client) = self.client {
|
||||
client
|
||||
} else {
|
||||
@@ -176,15 +167,15 @@ impl<T: System + Send + Sync, S, E> ClientBuilder<T, S, E> {
|
||||
|
||||
/// Client to interface with a substrate node.
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct Client<T: System, S = MultiSignature, E = DefaultExtra<T>> {
|
||||
pub struct Client<T: Runtime> {
|
||||
rpc: Rpc<T>,
|
||||
genesis_hash: T::Hash,
|
||||
metadata: Metadata,
|
||||
runtime_version: RuntimeVersion,
|
||||
_marker: PhantomData<(fn() -> S, E)>,
|
||||
_marker: PhantomData<(fn() -> T::Signature, T::Extra)>,
|
||||
}
|
||||
|
||||
impl<T: System, S, E> Clone for Client<T, S, E> {
|
||||
impl<T: Runtime> Clone for Client<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
rpc: self.rpc.clone(),
|
||||
@@ -196,7 +187,7 @@ impl<T: System, S, E> Clone for Client<T, S, E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: System, S, E> Client<T, S, E> {
|
||||
impl<T: Runtime> Client<T> {
|
||||
/// Returns the genesis hash.
|
||||
pub fn genesis(&self) -> &T::Hash {
|
||||
&self.genesis_hash
|
||||
@@ -312,14 +303,15 @@ impl<T: System, S, E> Client<T, S, E> {
|
||||
let headers = self.rpc.subscribe_finalized_blocks().await?;
|
||||
Ok(headers)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, E> Client<T, S, E>
|
||||
where
|
||||
T: System + Send + Sync + 'static,
|
||||
S: Encode + Send + Sync + 'static,
|
||||
E: SignedExtra<T> + SignedExtension + Send + Sync + 'static,
|
||||
{
|
||||
/// Encodes a call.
|
||||
pub fn encode<C: Call<T>>(&self, call: C) -> Result<Encoded, Error> {
|
||||
Ok(self
|
||||
.metadata()
|
||||
.module_with_calls(C::MODULE)
|
||||
.and_then(|module| module.call(C::FUNCTION, call))?)
|
||||
}
|
||||
|
||||
/// Creates an unsigned extrinsic.
|
||||
///
|
||||
/// If `nonce` is `None` the nonce will be fetched from the chain.
|
||||
@@ -328,7 +320,11 @@ where
|
||||
call: C,
|
||||
account_id: &<T as System>::AccountId,
|
||||
nonce: Option<T::Index>,
|
||||
) -> Result<SignedPayload<Encoded, <E as SignedExtra<T>>::Extra>, Error> {
|
||||
) -> Result<SignedPayload<T>, Error>
|
||||
where
|
||||
<<T::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
|
||||
Send + Sync,
|
||||
{
|
||||
let account_nonce = if let Some(nonce) = nonce {
|
||||
nonce
|
||||
} else {
|
||||
@@ -337,12 +333,10 @@ where
|
||||
let spec_version = self.runtime_version.spec_version;
|
||||
let tx_version = self.runtime_version.transaction_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 extra: E = E::new(spec_version, tx_version, account_nonce, genesis_hash);
|
||||
let raw_payload = SignedPayload::new(call, extra.extra())?;
|
||||
let call = self.encode(call)?;
|
||||
let extra: T::Extra =
|
||||
T::Extra::new(spec_version, tx_version, account_nonce, genesis_hash);
|
||||
let raw_payload = SignedPayload::<T>::new(call, extra.extra())?;
|
||||
Ok(raw_payload)
|
||||
}
|
||||
|
||||
@@ -350,13 +344,11 @@ where
|
||||
pub async fn create_signed<C: Call<T> + Send + Sync>(
|
||||
&self,
|
||||
call: C,
|
||||
signer: &(dyn Signer<T, S, E> + Send + Sync),
|
||||
) -> Result<
|
||||
UncheckedExtrinsic<T::Address, Encoded, S, <E as SignedExtra<T>>::Extra>,
|
||||
Error,
|
||||
>
|
||||
signer: &(dyn Signer<T> + Send + Sync),
|
||||
) -> Result<UncheckedExtrinsic<T>, Error>
|
||||
where
|
||||
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync,
|
||||
<<T::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
|
||||
Send + Sync,
|
||||
{
|
||||
let unsigned = self
|
||||
.create_unsigned(call, signer.account_id(), signer.nonce())
|
||||
@@ -376,12 +368,7 @@ where
|
||||
/// 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,
|
||||
>,
|
||||
extrinsic: UncheckedExtrinsic<T>,
|
||||
) -> Result<T::Hash, Error> {
|
||||
self.rpc.submit_extrinsic(extrinsic).await
|
||||
}
|
||||
@@ -389,12 +376,7 @@ where
|
||||
/// 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,
|
||||
>,
|
||||
extrinsic: UncheckedExtrinsic<T>,
|
||||
decoder: EventsDecoder<T>,
|
||||
) -> Result<ExtrinsicSuccess<T>, Error> {
|
||||
self.rpc
|
||||
@@ -406,10 +388,11 @@ where
|
||||
pub async fn submit<C: Call<T> + Send + Sync>(
|
||||
&self,
|
||||
call: C,
|
||||
signer: &(dyn Signer<T, S, E> + Send + Sync),
|
||||
signer: &(dyn Signer<T> + Send + Sync),
|
||||
) -> Result<T::Hash, Error>
|
||||
where
|
||||
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync,
|
||||
<<T::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
|
||||
Send + Sync,
|
||||
{
|
||||
let extrinsic = self.create_signed(call, signer).await?;
|
||||
self.submit_extrinsic(extrinsic).await
|
||||
@@ -419,10 +402,11 @@ where
|
||||
pub async fn watch<C: Call<T> + Send + Sync>(
|
||||
&self,
|
||||
call: C,
|
||||
signer: &(dyn Signer<T, S, E> + Send + Sync),
|
||||
signer: &(dyn Signer<T> + Send + Sync),
|
||||
) -> Result<ExtrinsicSuccess<T>, Error>
|
||||
where
|
||||
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync,
|
||||
<<T::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
|
||||
Send + Sync,
|
||||
{
|
||||
let extrinsic = self.create_signed(call, signer).await?;
|
||||
let decoder = self.events_decoder::<C>();
|
||||
@@ -432,7 +416,7 @@ where
|
||||
|
||||
/// Wraps an already encoded byte vector, prevents being encoded as a raw byte vector as part of
|
||||
/// the transaction payload
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Encoded(pub Vec<u8>);
|
||||
|
||||
impl codec::Encode for Encoded {
|
||||
@@ -444,6 +428,7 @@ impl codec::Encode for Encoded {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codec::Encode;
|
||||
use sp_core::{
|
||||
storage::{
|
||||
well_known_keys,
|
||||
@@ -455,6 +440,7 @@ mod tests {
|
||||
AccountKeyring,
|
||||
Ed25519Keyring,
|
||||
};
|
||||
use sp_runtime::MultiSignature;
|
||||
use substrate_subxt_client::{
|
||||
DatabaseConfig,
|
||||
Role,
|
||||
@@ -463,7 +449,10 @@ mod tests {
|
||||
};
|
||||
use tempdir::TempDir;
|
||||
|
||||
pub(crate) async fn test_client() -> (Client<crate::NodeTemplateRuntime>, TempDir) {
|
||||
pub(crate) type TestRuntime = crate::NodeTemplateRuntime;
|
||||
|
||||
pub(crate) async fn test_client() -> (Client<TestRuntime>, TempDir) {
|
||||
env_logger::try_init().ok();
|
||||
let tmp = TempDir::new("subxt-").expect("failed to create tempdir");
|
||||
let config = SubxtClientConfig {
|
||||
impl_name: "substrate-subxt-full-client",
|
||||
@@ -474,8 +463,8 @@ mod tests {
|
||||
path: tmp.path().into(),
|
||||
cache_size: 128,
|
||||
},
|
||||
builder: node_template::service::new_full,
|
||||
chain_spec: node_template::chain_spec::development_config(),
|
||||
builder: test_node::service::new_full,
|
||||
chain_spec: test_node::chain_spec::development_config(),
|
||||
role: Role::Authority(AccountKeyring::Alice),
|
||||
};
|
||||
let client = ClientBuilder::new()
|
||||
@@ -488,7 +477,6 @@ mod tests {
|
||||
|
||||
#[async_std::test]
|
||||
async fn test_tx_transfer_balance() {
|
||||
env_logger::try_init().ok();
|
||||
let mut signer = PairSigner::new(AccountKeyring::Alice.pair());
|
||||
let dest = AccountKeyring::Bob.to_account_id().into();
|
||||
|
||||
|
||||
@@ -58,6 +58,9 @@ pub enum MetadataError {
|
||||
/// Event is not in metadata.
|
||||
#[error("Event {0} not found")]
|
||||
EventNotFound(u8),
|
||||
/// Event is not in metadata.
|
||||
#[error("Error {0} not found")]
|
||||
ErrorNotFound(u8),
|
||||
/// Storage is not in metadata.
|
||||
#[error("Storage {0} not found")]
|
||||
StorageNotFound(&'static str),
|
||||
@@ -75,6 +78,7 @@ pub struct Metadata {
|
||||
modules: HashMap<String, ModuleMetadata>,
|
||||
modules_with_calls: HashMap<String, ModuleWithCalls>,
|
||||
modules_with_events: HashMap<String, ModuleWithEvents>,
|
||||
modules_with_errors: HashMap<String, ModuleWithErrors>,
|
||||
}
|
||||
|
||||
impl Metadata {
|
||||
@@ -116,6 +120,16 @@ impl Metadata {
|
||||
.ok_or(MetadataError::ModuleIndexNotFound(module_index))
|
||||
}
|
||||
|
||||
pub(crate) fn module_with_errors(
|
||||
&self,
|
||||
module_index: u8,
|
||||
) -> Result<&ModuleWithErrors, MetadataError> {
|
||||
self.modules_with_errors
|
||||
.values()
|
||||
.find(|&module| module.index == module_index)
|
||||
.ok_or(MetadataError::ModuleIndexNotFound(module_index))
|
||||
}
|
||||
|
||||
/// Pretty print metadata.
|
||||
pub fn pretty(&self) -> String {
|
||||
let mut string = String::new();
|
||||
@@ -206,6 +220,25 @@ impl ModuleWithEvents {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ModuleWithErrors {
|
||||
index: u8,
|
||||
name: String,
|
||||
errors: HashMap<u8, String>,
|
||||
}
|
||||
|
||||
impl ModuleWithErrors {
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn error(&self, index: u8) -> Result<&String, MetadataError> {
|
||||
self.errors
|
||||
.get(&index)
|
||||
.ok_or(MetadataError::ErrorNotFound(index))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StorageMetadata {
|
||||
module_prefix: String,
|
||||
@@ -437,6 +470,7 @@ impl TryFrom<RuntimeMetadataPrefixed> for Metadata {
|
||||
let mut modules = HashMap::new();
|
||||
let mut modules_with_calls = HashMap::new();
|
||||
let mut modules_with_events = HashMap::new();
|
||||
let mut modules_with_errors = HashMap::new();
|
||||
for module in convert(meta.modules)?.into_iter() {
|
||||
let module_name = convert(module.name.clone())?;
|
||||
|
||||
@@ -490,11 +524,24 @@ impl TryFrom<RuntimeMetadataPrefixed> for Metadata {
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut error_map = HashMap::new();
|
||||
for (index, error) in convert(module.errors)?.into_iter().enumerate() {
|
||||
error_map.insert(index as u8, convert_error(error)?);
|
||||
}
|
||||
modules_with_errors.insert(
|
||||
module_name.clone(),
|
||||
ModuleWithErrors {
|
||||
index: modules_with_errors.len() as u8,
|
||||
name: module_name.clone(),
|
||||
errors: error_map,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(Metadata {
|
||||
modules,
|
||||
modules_with_calls,
|
||||
modules_with_events,
|
||||
modules_with_errors,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -534,3 +581,9 @@ fn convert_entry(
|
||||
default,
|
||||
})
|
||||
}
|
||||
|
||||
fn convert_error(
|
||||
error: frame_metadata::ErrorMetadata,
|
||||
) -> Result<String, ConversionError> {
|
||||
convert(error.name)
|
||||
}
|
||||
|
||||
+34
-96
@@ -68,17 +68,14 @@ use crate::{
|
||||
events::{
|
||||
EventsDecoder,
|
||||
RawEvent,
|
||||
RuntimeEvent,
|
||||
},
|
||||
frame::{
|
||||
system::{
|
||||
Phase,
|
||||
System,
|
||||
SystemEvent,
|
||||
},
|
||||
system::System,
|
||||
Event,
|
||||
},
|
||||
metadata::Metadata,
|
||||
runtimes::Runtime,
|
||||
subscription::EventSubscription,
|
||||
};
|
||||
|
||||
pub type ChainBlock<T> =
|
||||
@@ -109,12 +106,12 @@ where
|
||||
}
|
||||
|
||||
/// Client for substrate rpc interfaces
|
||||
pub struct Rpc<T: System> {
|
||||
pub struct Rpc<T: Runtime> {
|
||||
client: Client,
|
||||
marker: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: System> Clone for Rpc<T> {
|
||||
impl<T: Runtime> Clone for Rpc<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
client: self.client.clone(),
|
||||
@@ -123,7 +120,7 @@ impl<T: System> Clone for Rpc<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: System> Rpc<T> {
|
||||
impl<T: Runtime> Rpc<T> {
|
||||
pub fn new(client: Client) -> Self {
|
||||
Self {
|
||||
client,
|
||||
@@ -258,7 +255,7 @@ impl<T: System> Rpc<T> {
|
||||
/// Subscribe to substrate System Events
|
||||
pub async fn subscribe_events(
|
||||
&self,
|
||||
) -> Result<Subscription<StorageChangeSet<<T as System>::Hash>>, Error> {
|
||||
) -> Result<Subscription<StorageChangeSet<T::Hash>>, Error> {
|
||||
let mut storage_key = twox_128(b"System").to_vec();
|
||||
storage_key.extend(twox_128(b"Events").to_vec());
|
||||
log::debug!("Events storage key {:?}", hex::encode(&storage_key));
|
||||
@@ -362,14 +359,31 @@ impl<T: System> Rpc<T> {
|
||||
block_hash,
|
||||
signed_block.block.extrinsics.len()
|
||||
);
|
||||
wait_for_block_events(
|
||||
decoder,
|
||||
ext_hash,
|
||||
signed_block,
|
||||
block_hash,
|
||||
events_sub,
|
||||
)
|
||||
.await
|
||||
let ext_index = signed_block
|
||||
.block
|
||||
.extrinsics
|
||||
.iter()
|
||||
.position(|ext| {
|
||||
let hash = T::Hashing::hash_of(ext);
|
||||
hash == ext_hash
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
Error::Other(format!(
|
||||
"Failed to find Extrinsic with hash {:?}",
|
||||
ext_hash,
|
||||
))
|
||||
})?;
|
||||
let mut sub = EventSubscription::new(events_sub, decoder);
|
||||
sub.filter_extrinsic(block_hash, ext_index);
|
||||
let mut events = vec![];
|
||||
while let Some(event) = sub.next().await {
|
||||
events.push(event?);
|
||||
}
|
||||
Ok(ExtrinsicSuccess {
|
||||
block: block_hash,
|
||||
extrinsic: ext_hash,
|
||||
events,
|
||||
})
|
||||
}
|
||||
None => {
|
||||
Err(format!("Failed to find block {:?}", block_hash).into())
|
||||
@@ -403,36 +417,16 @@ pub struct ExtrinsicSuccess<T: System> {
|
||||
/// Extrinsic hash.
|
||||
pub extrinsic: T::Hash,
|
||||
/// Raw runtime events, can be decoded by the caller.
|
||||
pub events: Vec<RuntimeEvent<T>>,
|
||||
pub events: Vec<RawEvent>,
|
||||
}
|
||||
|
||||
impl<T: System> ExtrinsicSuccess<T> {
|
||||
/// Find the Event for the given module/variant, with raw encoded event data.
|
||||
/// Returns `None` if the Event is not found.
|
||||
pub fn find_event_raw(&self, module: &str, variant: &str) -> Option<&RawEvent> {
|
||||
self.events.iter().find_map(|evt| {
|
||||
match evt {
|
||||
RuntimeEvent::Raw(ref raw)
|
||||
if raw.module == module && raw.variant == variant =>
|
||||
{
|
||||
Some(raw)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns all System Events
|
||||
pub fn system_events(&self) -> Vec<&SystemEvent<T>> {
|
||||
self.events
|
||||
.iter()
|
||||
.filter_map(|evt| {
|
||||
match evt {
|
||||
RuntimeEvent::System(evt) => Some(evt),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
.find(|raw| raw.module == module && raw.variant == variant)
|
||||
}
|
||||
|
||||
/// Find the Event for the given module/variant, attempting to decode the event data.
|
||||
@@ -446,59 +440,3 @@ impl<T: System> ExtrinsicSuccess<T> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for events for the block triggered by the extrinsic
|
||||
pub async fn wait_for_block_events<T: System>(
|
||||
decoder: EventsDecoder<T>,
|
||||
ext_hash: T::Hash,
|
||||
signed_block: ChainBlock<T>,
|
||||
block_hash: T::Hash,
|
||||
events_subscription: Subscription<StorageChangeSet<T::Hash>>,
|
||||
) -> Result<ExtrinsicSuccess<T>, Error> {
|
||||
let ext_index = signed_block
|
||||
.block
|
||||
.extrinsics
|
||||
.iter()
|
||||
.position(|ext| {
|
||||
let hash = T::Hashing::hash_of(ext);
|
||||
hash == ext_hash
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
Error::Other(format!("Failed to find Extrinsic with hash {:?}", ext_hash))
|
||||
})?;
|
||||
|
||||
let mut subscription = events_subscription;
|
||||
while let change_set = subscription.next().await {
|
||||
// only interested in events for the given block
|
||||
if change_set.block != block_hash {
|
||||
continue
|
||||
}
|
||||
let mut events = Vec::new();
|
||||
for (_key, data) in change_set.changes {
|
||||
if let Some(data) = data {
|
||||
match decoder.decode_events(&mut &data.0[..]) {
|
||||
Ok(raw_events) => {
|
||||
for (phase, event) in raw_events {
|
||||
if let Phase::ApplyExtrinsic(i) = phase {
|
||||
if i as usize == ext_index {
|
||||
events.push(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
return if !events.is_empty() {
|
||||
Ok(ExtrinsicSuccess {
|
||||
block: block_hash,
|
||||
extrinsic: ext_hash,
|
||||
events,
|
||||
})
|
||||
} else {
|
||||
Err(format!("No events found for block {}", block_hash).into())
|
||||
}
|
||||
}
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
+58
-5
@@ -15,6 +15,7 @@
|
||||
// along with substrate-subxt. If not, see <http://www.gnu.org/licenses/>.
|
||||
#![allow(missing_docs)]
|
||||
|
||||
use codec::Encode;
|
||||
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
|
||||
use sp_runtime::{
|
||||
generic::Header,
|
||||
@@ -112,17 +113,49 @@ impl_opaque_keys! {
|
||||
}
|
||||
}
|
||||
|
||||
use crate::frame::{
|
||||
balances::{
|
||||
AccountData,
|
||||
Balances,
|
||||
},
|
||||
use crate::{
|
||||
contracts::Contracts,
|
||||
extra::{
|
||||
DefaultExtra,
|
||||
SignedExtra,
|
||||
},
|
||||
frame::{
|
||||
balances::{
|
||||
AccountData,
|
||||
Balances,
|
||||
},
|
||||
contracts::Contracts,
|
||||
sudo::Sudo,
|
||||
system::System,
|
||||
},
|
||||
session::Session,
|
||||
staking::Staking,
|
||||
system::System,
|
||||
Encoded,
|
||||
};
|
||||
|
||||
/// Runtime trait.
|
||||
pub trait Runtime: System + Sized + Send + Sync + 'static {
|
||||
/// Signature type.
|
||||
type Signature: Verify + Encode + Send + Sync + 'static;
|
||||
/// Transaction extras.
|
||||
type Extra: SignedExtra<Self> + Send + Sync + 'static;
|
||||
}
|
||||
|
||||
/// Extra type.
|
||||
pub type Extra<T> = <<T as Runtime>::Extra as SignedExtra<T>>::Extra;
|
||||
|
||||
/// UncheckedExtrinsic type.
|
||||
pub type UncheckedExtrinsic<T> = sp_runtime::generic::UncheckedExtrinsic<
|
||||
<T as System>::Address,
|
||||
Encoded,
|
||||
<T as Runtime>::Signature,
|
||||
Extra<T>,
|
||||
>;
|
||||
|
||||
/// SignedPayload type.
|
||||
pub type SignedPayload<T> = sp_runtime::generic::SignedPayload<Encoded, Extra<T>>;
|
||||
|
||||
/// Concrete type definitions compatible with those in the default substrate `node_runtime`
|
||||
///
|
||||
/// # Note
|
||||
@@ -141,6 +174,11 @@ impl Staking for DefaultNodeRuntime {
|
||||
type RewardPoint = u32;
|
||||
}
|
||||
|
||||
impl Runtime for DefaultNodeRuntime {
|
||||
type Signature = MultiSignature;
|
||||
type Extra = DefaultExtra<Self>;
|
||||
}
|
||||
|
||||
impl System for DefaultNodeRuntime {
|
||||
type Index = u32;
|
||||
type BlockNumber = u32;
|
||||
@@ -165,6 +203,8 @@ impl Session for DefaultNodeRuntime {
|
||||
|
||||
impl Contracts for DefaultNodeRuntime {}
|
||||
|
||||
impl Sudo for DefaultNodeRuntime {}
|
||||
|
||||
/// Concrete type definitions compatible with the node template.
|
||||
///
|
||||
/// # Note
|
||||
@@ -174,6 +214,11 @@ impl Contracts for DefaultNodeRuntime {}
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub struct NodeTemplateRuntime;
|
||||
|
||||
impl Runtime for NodeTemplateRuntime {
|
||||
type Signature = MultiSignature;
|
||||
type Extra = DefaultExtra<Self>;
|
||||
}
|
||||
|
||||
impl System for NodeTemplateRuntime {
|
||||
type Index = u32;
|
||||
type BlockNumber = u32;
|
||||
@@ -190,6 +235,8 @@ impl Balances for NodeTemplateRuntime {
|
||||
type Balance = u128;
|
||||
}
|
||||
|
||||
impl Sudo for NodeTemplateRuntime {}
|
||||
|
||||
/// Concrete type definitions compatible with those for kusama, v0.7
|
||||
///
|
||||
/// # Note
|
||||
@@ -200,6 +247,12 @@ impl Balances for NodeTemplateRuntime {
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub struct KusamaRuntime;
|
||||
|
||||
#[cfg(feature = "kusama")]
|
||||
impl Runtime for KusamaRuntime {
|
||||
type Signature = MultiSignature;
|
||||
type Extra = DefaultExtra<Self>;
|
||||
}
|
||||
|
||||
#[cfg(feature = "kusama")]
|
||||
impl System for KusamaRuntime {
|
||||
type Index = u32;
|
||||
|
||||
+31
-54
@@ -19,29 +19,26 @@
|
||||
|
||||
use crate::{
|
||||
extra::SignedExtra,
|
||||
frame::system::System,
|
||||
Encoded,
|
||||
};
|
||||
use codec::Encode;
|
||||
use sp_core::Pair;
|
||||
use sp_runtime::{
|
||||
generic::{
|
||||
runtimes::{
|
||||
Runtime,
|
||||
SignedPayload,
|
||||
UncheckedExtrinsic,
|
||||
},
|
||||
traits::{
|
||||
IdentifyAccount,
|
||||
Verify,
|
||||
},
|
||||
};
|
||||
use codec::Encode;
|
||||
use sp_core::Pair;
|
||||
use sp_runtime::traits::{
|
||||
IdentifyAccount,
|
||||
SignedExtension,
|
||||
Verify,
|
||||
};
|
||||
use std::{
|
||||
future::Future,
|
||||
marker::PhantomData,
|
||||
pin::Pin,
|
||||
};
|
||||
|
||||
/// Extrinsic signer.
|
||||
pub trait Signer<T: System, S: Encode, E: SignedExtra<T>> {
|
||||
pub trait Signer<T: Runtime> {
|
||||
/// Returns the account id.
|
||||
fn account_id(&self) -> &T::AccountId;
|
||||
|
||||
@@ -54,42 +51,30 @@ pub trait Signer<T: System, S: Encode, E: SignedExtra<T>> {
|
||||
/// refused the operation.
|
||||
fn sign(
|
||||
&self,
|
||||
extrinsic: SignedPayload<Encoded, E::Extra>,
|
||||
) -> Pin<
|
||||
Box<
|
||||
dyn Future<
|
||||
Output = Result<
|
||||
UncheckedExtrinsic<T::Address, Encoded, S, E::Extra>,
|
||||
String,
|
||||
>,
|
||||
> + Send
|
||||
+ Sync,
|
||||
>,
|
||||
>;
|
||||
extrinsic: SignedPayload<T>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<UncheckedExtrinsic<T>, String>> + Send + Sync>>;
|
||||
}
|
||||
|
||||
/// Extrinsic signer using a private key.
|
||||
#[derive(Debug)]
|
||||
pub struct PairSigner<T: System, S: Encode, E: SignedExtra<T>, P: Pair> {
|
||||
_marker: PhantomData<(S, E)>,
|
||||
pub struct PairSigner<T: Runtime, P: Pair> {
|
||||
account_id: T::AccountId,
|
||||
nonce: Option<T::Index>,
|
||||
signer: P,
|
||||
}
|
||||
|
||||
impl<T, S, E, P> PairSigner<T, S, E, P>
|
||||
impl<T, P> PairSigner<T, P>
|
||||
where
|
||||
T: System,
|
||||
S: Encode + Verify + From<P::Signature>,
|
||||
S::Signer: From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
|
||||
E: SignedExtra<T>,
|
||||
T: Runtime,
|
||||
T::Signature: From<P::Signature>,
|
||||
<T::Signature as Verify>::Signer:
|
||||
From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
|
||||
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();
|
||||
let account_id =
|
||||
<T::Signature as Verify>::Signer::from(signer.public()).into_account();
|
||||
Self {
|
||||
_marker: PhantomData,
|
||||
account_id,
|
||||
nonce: None,
|
||||
signer,
|
||||
@@ -112,14 +97,14 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, E, P> Signer<T, S, E> for PairSigner<T, S, E, P>
|
||||
impl<T, P> Signer<T> for PairSigner<T, P>
|
||||
where
|
||||
T: System + 'static,
|
||||
T: Runtime,
|
||||
T::AccountId: Into<T::Address> + 'static,
|
||||
S: Encode + 'static + Send + Sync,
|
||||
E: SignedExtra<T> + 'static,
|
||||
<<T::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
|
||||
Send + Sync,
|
||||
P: Pair + 'static,
|
||||
P::Signature: Into<S> + 'static,
|
||||
P::Signature: Into<T::Signature> + 'static,
|
||||
{
|
||||
fn account_id(&self) -> &T::AccountId {
|
||||
&self.account_id
|
||||
@@ -131,25 +116,17 @@ where
|
||||
|
||||
fn sign(
|
||||
&self,
|
||||
extrinsic: SignedPayload<Encoded, E::Extra>,
|
||||
) -> Pin<
|
||||
Box<
|
||||
dyn Future<
|
||||
Output = Result<
|
||||
UncheckedExtrinsic<T::Address, Encoded, S, E::Extra>,
|
||||
String,
|
||||
>,
|
||||
> + Send
|
||||
+ Sync,
|
||||
>,
|
||||
> {
|
||||
extrinsic: SignedPayload<T>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<UncheckedExtrinsic<T>, String>> + Send + Sync>>
|
||||
{
|
||||
let signature = extrinsic.using_encoded(|payload| self.signer.sign(payload));
|
||||
let (call, extra, _) = extrinsic.deconstruct();
|
||||
Box::pin(futures::future::ok(UncheckedExtrinsic::new_signed(
|
||||
let extrinsic = UncheckedExtrinsic::<T>::new_signed(
|
||||
call,
|
||||
self.account_id.clone().into(),
|
||||
signature.into(),
|
||||
extra,
|
||||
)))
|
||||
);
|
||||
Box::pin(async move { Ok(extrinsic) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// 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/>.
|
||||
|
||||
use jsonrpsee::client::Subscription;
|
||||
use sp_core::storage::StorageChangeSet;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::{
|
||||
error::Error,
|
||||
events::{
|
||||
EventsDecoder,
|
||||
RawEvent,
|
||||
},
|
||||
frame::{
|
||||
system::Phase,
|
||||
Event,
|
||||
},
|
||||
runtimes::Runtime,
|
||||
};
|
||||
|
||||
/// Event subscription simplifies filtering a storage change set stream for
|
||||
/// events of interest.
|
||||
pub struct EventSubscription<T: Runtime> {
|
||||
subscription: Subscription<StorageChangeSet<T::Hash>>,
|
||||
decoder: EventsDecoder<T>,
|
||||
block: Option<T::Hash>,
|
||||
extrinsic: Option<usize>,
|
||||
event: Option<(&'static str, &'static str)>,
|
||||
events: VecDeque<RawEvent>,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
impl<T: Runtime> EventSubscription<T> {
|
||||
/// Creates a new event subscription.
|
||||
pub fn new(
|
||||
subscription: Subscription<StorageChangeSet<T::Hash>>,
|
||||
decoder: EventsDecoder<T>,
|
||||
) -> Self {
|
||||
Self {
|
||||
subscription,
|
||||
decoder,
|
||||
block: None,
|
||||
extrinsic: None,
|
||||
event: None,
|
||||
events: Default::default(),
|
||||
finished: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Only returns events contained in the block with the given hash.
|
||||
pub fn filter_block(&mut self, block: T::Hash) {
|
||||
self.block = Some(block);
|
||||
}
|
||||
|
||||
/// Only returns events from block emitted by extrinsic with index.
|
||||
pub fn filter_extrinsic(&mut self, block: T::Hash, ext_index: usize) {
|
||||
self.block = Some(block);
|
||||
self.extrinsic = Some(ext_index);
|
||||
}
|
||||
|
||||
/// Filters events by type.
|
||||
pub fn filter_event<E: Event<T>>(&mut self) {
|
||||
self.event = Some((E::MODULE, E::EVENT));
|
||||
}
|
||||
|
||||
/// Gets the next event.
|
||||
pub async fn next(&mut self) -> Option<Result<RawEvent, Error>> {
|
||||
loop {
|
||||
if let Some(event) = self.events.pop_front() {
|
||||
return Some(Ok(event))
|
||||
}
|
||||
if self.finished {
|
||||
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
|
||||
}
|
||||
}
|
||||
for (_key, data) in change_set.changes {
|
||||
if let Some(data) = data {
|
||||
let raw_events = match self.decoder.decode_events(&mut &data.0[..]) {
|
||||
Ok(events) => events,
|
||||
Err(error) => return Some(Err(error)),
|
||||
};
|
||||
for (phase, event) in raw_events {
|
||||
if let Phase::ApplyExtrinsic(i) = phase {
|
||||
if let Some(ext_index) = self.extrinsic {
|
||||
if i as usize != ext_index {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if let Some((module, variant)) = self.event {
|
||||
if event.module != module || event.variant != variant {
|
||||
continue
|
||||
}
|
||||
}
|
||||
self.events.push_back(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user