Improve error handling in proc-macros, handle DispatchError etc. (#123)

* Improve error handling.

* Fix build.

* Handle runtime errors.

* Add runtime trait for better type inference.

* Use runtime trait part 1.

* wip

* Add support for sudo.

* Finish error handling.

* Fix tests.

* Fix clippy warnings.
This commit is contained in:
David Craven
2020-06-22 08:39:40 +02:00
committed by GitHub
parent 21d07c6c24
commit 3080ec91a6
23 changed files with 557 additions and 373 deletions
+52 -8
View File
@@ -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
View File
@@ -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
View File
@@ -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(
+70 -26
View File
@@ -110,36 +110,56 @@ pub struct TransferEvent<T: Balances> {
mod tests {
use super::*;
use crate::{
system::{
AccountStore,
AccountStoreExt,
error::{
Error,
RuntimeError,
},
tests::test_client,
signer::{
PairSigner,
Signer,
},
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 +177,28 @@ 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");
}
}
}
+1
View File
@@ -31,6 +31,7 @@ use sp_core::storage::StorageKey;
pub mod balances;
pub mod contracts;
pub mod sudo;
pub mod system;
/// Store trait.
+78
View File
@@ -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
View File
@@ -155,21 +155,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 {
@@ -178,3 +163,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,
}
+45 -60
View File
@@ -48,10 +48,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;
@@ -59,14 +56,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;
@@ -83,7 +73,6 @@ pub use crate::{
error::Error,
events::{
EventsDecoder,
EventsError,
RawEvent,
},
extra::*,
@@ -105,7 +94,6 @@ use crate::{
AccountStoreExt,
Phase,
System,
SystemEvent,
},
rpc::{
ChainBlock,
@@ -115,13 +103,13 @@ use crate::{
/// ClientBuilder for constructing a Client.
#[derive(Default)]
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 {
@@ -144,7 +132,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 {
@@ -173,15 +161,15 @@ impl<T: System + Send + Sync, S, E> ClientBuilder<T, S, E> {
}
/// Client to interface with a substrate node.
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(),
@@ -193,7 +181,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
@@ -309,14 +297,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.
@@ -325,7 +314,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 {
@@ -334,12 +327,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)
}
@@ -347,13 +338,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())
@@ -373,12 +362,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
}
@@ -386,12 +370,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
@@ -403,10 +382,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
@@ -416,10 +396,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>();
@@ -429,7 +410,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 {
@@ -441,6 +422,7 @@ impl codec::Encode for Encoded {
#[cfg(test)]
mod tests {
use super::*;
use codec::Encode;
use sp_core::{
storage::{
well_known_keys,
@@ -452,6 +434,7 @@ mod tests {
AccountKeyring,
Ed25519Keyring,
};
use sp_runtime::MultiSignature;
use substrate_subxt_client::{
DatabaseConfig,
Role,
@@ -460,7 +443,9 @@ 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) {
let tmp = TempDir::new("subxt-").expect("failed to create tempdir");
let config = SubxtClientConfig {
impl_name: "substrate-subxt-full-client",
+53
View File
@@ -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)
}
+3 -25
View File
@@ -68,13 +68,11 @@ use crate::{
events::{
EventsDecoder,
RawEvent,
RuntimeEvent,
},
frame::{
system::{
Phase,
System,
SystemEvent,
},
Event,
},
@@ -403,36 +401,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.
@@ -486,7 +464,7 @@ pub async fn wait_for_block_events<T: System>(
}
}
}
Err(err) => return Err(err.into()),
Err(err) => return Err(err),
}
}
}
+56 -6
View File
@@ -14,6 +14,7 @@
// 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 codec::Encode;
use sp_runtime::{
generic::Header,
traits::{
@@ -25,15 +26,45 @@ use sp_runtime::{
OpaqueExtrinsic,
};
use crate::frame::{
balances::{
AccountData,
Balances,
use crate::{
extra::{
DefaultExtra,
SignedExtra,
},
contracts::Contracts,
system::System,
frame::{
balances::{
AccountData,
Balances,
},
contracts::Contracts,
sudo::Sudo,
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
@@ -43,6 +74,11 @@ use crate::frame::{
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DefaultNodeRuntime;
impl Runtime for DefaultNodeRuntime {
type Signature = MultiSignature;
type Extra = DefaultExtra<Self>;
}
impl System for DefaultNodeRuntime {
type Index = u32;
type BlockNumber = u32;
@@ -61,6 +97,8 @@ impl Balances for DefaultNodeRuntime {
impl Contracts for DefaultNodeRuntime {}
impl Sudo for DefaultNodeRuntime {}
/// Concrete type definitions compatible with the node template.
///
/// # Note
@@ -70,6 +108,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;
@@ -86,6 +129,8 @@ impl Balances for NodeTemplateRuntime {
type Balance = u128;
}
impl Sudo for NodeTemplateRuntime {}
/// Concrete type definitions compatible with those for kusama, v0.7
///
/// # Note
@@ -95,6 +140,11 @@ impl Balances for NodeTemplateRuntime {
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct KusamaRuntime;
impl Runtime for KusamaRuntime {
type Signature = MultiSignature;
type Extra = DefaultExtra<Self>;
}
impl System for KusamaRuntime {
type Index = u32;
type BlockNumber = u32;
+31 -58
View File
@@ -19,33 +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,
SignedExtension,
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>>
where
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync,
{
pub trait Signer<T: Runtime> {
/// Returns the account id.
fn account_id(&self) -> &T::AccountId;
@@ -58,41 +51,30 @@ where
/// 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.
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,
@@ -115,15 +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,
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync,
P::Signature: Into<T::Signature> + 'static,
{
fn account_id(&self) -> &T::AccountId {
&self.account_id
@@ -135,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) })
}
}