mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-14 05:11:09 +00:00
Double map and plain storage support, introduce macros (#93)
* Support custom clients. * Simplify trait bounds. * Plain and double map storage support. * Simplify more trait bounds. * Add proc macro. * Add Call, Event and Store traits. * Update proc-macros. * Add with_system for proc-macro. * proc-macro: test: support signature and extra fields. * proc-macro: test: support sharing state accross steps. * proc-macro: test: fetch state sequentially. * Elide lifetimes. * Add test for plain storage. * Run rustfmt.
This commit is contained in:
+15
-5
@@ -37,7 +37,6 @@ use codec::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
frame::balances::Balances,
|
||||
metadata::{
|
||||
EventArg,
|
||||
Metadata,
|
||||
@@ -66,23 +65,28 @@ pub struct RawEvent {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Events error.
|
||||
#[derive(Debug, thiserror::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.
|
||||
pub struct EventsDecoder<T> {
|
||||
metadata: Metadata, // todo: [AJ] borrow?
|
||||
type_sizes: HashMap<String, usize>,
|
||||
marker: PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T: System + Balances + 'static> TryFrom<Metadata> for EventsDecoder<T> {
|
||||
impl<T: System> TryFrom<Metadata> for EventsDecoder<T> {
|
||||
type Error = EventsError;
|
||||
|
||||
fn try_from(metadata: Metadata) -> Result<Self, Self::Error> {
|
||||
@@ -108,15 +112,19 @@ impl<T: System + Balances + 'static> TryFrom<Metadata> for EventsDecoder<T> {
|
||||
decoder.register_type_size::<T::AccountId>("AccountId")?;
|
||||
decoder.register_type_size::<T::BlockNumber>("BlockNumber")?;
|
||||
decoder.register_type_size::<T::Hash>("Hash")?;
|
||||
decoder.register_type_size::<<T as Balances>::Balance>("Balance")?;
|
||||
// VoteThreshold enum index
|
||||
decoder.register_type_size::<u8>("VoteThreshold")?;
|
||||
|
||||
Ok(decoder)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: System + Balances + 'static> EventsDecoder<T> {
|
||||
impl<T: System> EventsDecoder<T> {
|
||||
/// Register system types.
|
||||
pub fn with_system(&mut self) -> Result<(), EventsError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Register a type.
|
||||
pub fn register_type_size<U>(&mut self, name: &str) -> Result<usize, EventsError>
|
||||
where
|
||||
U: Default + Codec + Send + 'static,
|
||||
@@ -130,6 +138,7 @@ impl<T: System + Balances + 'static> EventsDecoder<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check missing type sizes.
|
||||
pub fn check_missing_type_sizes(&self) {
|
||||
let mut missing = HashSet::new();
|
||||
for module in self.metadata.modules_with_events() {
|
||||
@@ -194,6 +203,7 @@ impl<T: System + Balances + 'static> EventsDecoder<T> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode events.
|
||||
pub fn decode_events(
|
||||
&self,
|
||||
input: &mut &[u8],
|
||||
|
||||
+57
-16
@@ -16,15 +16,24 @@
|
||||
|
||||
//! Implements support for the pallet_balances module.
|
||||
|
||||
use crate::frame::{
|
||||
system::System,
|
||||
Call,
|
||||
use crate::{
|
||||
frame::{
|
||||
system::System,
|
||||
Call,
|
||||
Event,
|
||||
Store,
|
||||
},
|
||||
metadata::{
|
||||
Metadata,
|
||||
MetadataError,
|
||||
},
|
||||
};
|
||||
use codec::{
|
||||
Decode,
|
||||
Encode,
|
||||
};
|
||||
use frame_support::Parameter;
|
||||
use sp_core::storage::StorageKey;
|
||||
use sp_runtime::traits::{
|
||||
AtLeast32Bit,
|
||||
MaybeSerialize,
|
||||
@@ -32,6 +41,8 @@ use sp_runtime::traits::{
|
||||
};
|
||||
use std::fmt::Debug;
|
||||
|
||||
const MODULE: &str = "Balances";
|
||||
|
||||
/// The subset of the `pallet_balances::Trait` that a client must implement.
|
||||
pub trait Balances: System {
|
||||
/// The balance of an account.
|
||||
@@ -70,15 +81,22 @@ pub struct AccountData<Balance> {
|
||||
pub fee_frozen: Balance,
|
||||
}
|
||||
|
||||
const MODULE: &str = "Balances";
|
||||
const TRANSFER: &str = "transfer";
|
||||
/// The total issuance of the balances module.
|
||||
#[derive(Encode)]
|
||||
pub struct TotalIssuance<T>(pub core::marker::PhantomData<T>);
|
||||
|
||||
/// Arguments for transferring a balance
|
||||
#[derive(codec::Encode)]
|
||||
pub struct TransferArgs<T: Balances> {
|
||||
to: <T as System>::Address,
|
||||
#[codec(compact)]
|
||||
amount: <T as Balances>::Balance,
|
||||
impl<T: Balances> Store<T> for TotalIssuance<T> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const FIELD: &'static str = "TotalIssuance";
|
||||
type Returns = T::Balance;
|
||||
|
||||
fn key(&self, metadata: &Metadata) -> Result<StorageKey, MetadataError> {
|
||||
Ok(metadata
|
||||
.module(Self::MODULE)?
|
||||
.storage(Self::FIELD)?
|
||||
.plain()?
|
||||
.key())
|
||||
}
|
||||
}
|
||||
|
||||
/// Transfer some liquid free balance to another account.
|
||||
@@ -87,9 +105,32 @@ pub struct TransferArgs<T: Balances> {
|
||||
/// It will decrease the total issuance of the system by the `TransferFee`.
|
||||
/// If the sender's account is below the existential deposit as a result
|
||||
/// of the transfer, the account will be reaped.
|
||||
pub fn transfer<T: Balances>(
|
||||
to: <T as System>::Address,
|
||||
amount: <T as Balances>::Balance,
|
||||
) -> Call<TransferArgs<T>> {
|
||||
Call::new(MODULE, TRANSFER, TransferArgs { to, amount })
|
||||
#[derive(Encode)]
|
||||
pub struct TransferCall<'a, T: Balances> {
|
||||
/// Destination of the transfer.
|
||||
pub to: &'a <T as System>::Address,
|
||||
/// Amount to transfer.
|
||||
#[codec(compact)]
|
||||
pub amount: T::Balance,
|
||||
}
|
||||
|
||||
impl<'a, T: Balances> Call<T> for TransferCall<'a, T> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const FUNCTION: &'static str = "transfer";
|
||||
}
|
||||
|
||||
/// Transfer event.
|
||||
#[derive(Debug, Decode, Eq, PartialEq)]
|
||||
pub struct TransferEvent<T: Balances> {
|
||||
/// Account balance was transfered from.
|
||||
pub from: <T as System>::AccountId,
|
||||
/// Account balance was transfered to.
|
||||
pub to: <T as System>::AccountId,
|
||||
/// Amount of balance that was transfered.
|
||||
pub amount: T::Balance,
|
||||
}
|
||||
|
||||
impl<T: Balances> Event<T> for TransferEvent<T> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const EVENT: &'static str = "transfer";
|
||||
}
|
||||
|
||||
+94
-95
@@ -20,23 +20,15 @@ use crate::frame::{
|
||||
balances::Balances,
|
||||
system::System,
|
||||
Call,
|
||||
Event,
|
||||
};
|
||||
use codec::{
|
||||
Decode,
|
||||
Encode,
|
||||
};
|
||||
use codec::Encode;
|
||||
|
||||
const MODULE: &str = "Contracts";
|
||||
|
||||
mod calls {
|
||||
pub const PUT_CODE: &str = "put_code";
|
||||
pub const INSTANTIATE: &str = "instantiate";
|
||||
pub const CALL: &str = "call";
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
mod events {
|
||||
pub const CODE_STORED: &str = "CodeStored";
|
||||
pub const INSTANTIATED: &str = "Instantiated";
|
||||
}
|
||||
|
||||
/// Gas units are chosen to be represented by u64 so that gas metering
|
||||
/// instructions can operate on them efficiently.
|
||||
pub type Gas = u64;
|
||||
@@ -44,40 +36,21 @@ pub type Gas = u64;
|
||||
/// The subset of the `pallet_contracts::Trait` that a client must implement.
|
||||
pub trait Contracts: System + Balances {}
|
||||
|
||||
/// Arguments for uploading contract code to the chain
|
||||
#[derive(Encode)]
|
||||
pub struct PutCodeArgs {
|
||||
#[codec(compact)]
|
||||
gas_limit: Gas,
|
||||
code: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Arguments for creating an instance of a contract
|
||||
#[derive(Encode)]
|
||||
pub struct InstantiateArgs<T: Contracts> {
|
||||
#[codec(compact)]
|
||||
endowment: <T as Balances>::Balance,
|
||||
#[codec(compact)]
|
||||
gas_limit: Gas,
|
||||
code_hash: <T as System>::Hash,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Arguments for calling a contract
|
||||
#[derive(Encode)]
|
||||
pub struct CallArgs<T: Contracts> {
|
||||
dest: <T as System>::Address,
|
||||
value: <T as Balances>::Balance,
|
||||
#[codec(compact)]
|
||||
gas_limit: Gas,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Stores the given binary Wasm code into the chain's storage and returns
|
||||
/// its `codehash`.
|
||||
/// You can instantiate contracts only with stored code.
|
||||
pub fn put_code(gas_limit: Gas, code: Vec<u8>) -> Call<PutCodeArgs> {
|
||||
Call::new(MODULE, calls::PUT_CODE, PutCodeArgs { gas_limit, code })
|
||||
#[derive(Debug, Encode)]
|
||||
pub struct PutCodeCall<'a> {
|
||||
/// Gas limit.
|
||||
#[codec(compact)]
|
||||
pub gas_limit: Gas,
|
||||
/// Wasm blob.
|
||||
pub code: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a, T: Contracts> Call<T> for PutCodeCall<'a> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const FUNCTION: &'static str = "put_code";
|
||||
}
|
||||
|
||||
/// Creates a new contract from the `codehash` generated by `put_code`,
|
||||
@@ -93,22 +66,23 @@ pub fn put_code(gas_limit: Gas, code: Vec<u8>) -> Call<PutCodeArgs> {
|
||||
/// of the account. That code will be invoked upon any call received by
|
||||
/// this account.
|
||||
/// - The contract is initialized.
|
||||
pub fn instantiate<T: Contracts>(
|
||||
endowment: <T as Balances>::Balance,
|
||||
gas_limit: Gas,
|
||||
code_hash: <T as System>::Hash,
|
||||
data: Vec<u8>,
|
||||
) -> Call<InstantiateArgs<T>> {
|
||||
Call::new(
|
||||
MODULE,
|
||||
calls::INSTANTIATE,
|
||||
InstantiateArgs {
|
||||
endowment,
|
||||
gas_limit,
|
||||
code_hash,
|
||||
data,
|
||||
},
|
||||
)
|
||||
#[derive(Debug, Encode)]
|
||||
pub struct InstantiateCall<'a, T: Contracts> {
|
||||
/// Initial balance transfered to the contract.
|
||||
#[codec(compact)]
|
||||
pub endowment: <T as Balances>::Balance,
|
||||
/// Gas limit.
|
||||
#[codec(compact)]
|
||||
pub gas_limit: Gas,
|
||||
/// Code hash returned by the put_code call.
|
||||
pub code_hash: &'a <T as System>::Hash,
|
||||
/// Data to initialize the contract with.
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a, T: Contracts> Call<T> for InstantiateCall<'a, T> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const FUNCTION: &'static str = "instantiate";
|
||||
}
|
||||
|
||||
/// Makes a call to an account, optionally transferring some balance.
|
||||
@@ -119,22 +93,46 @@ pub fn instantiate<T: Contracts>(
|
||||
/// * If no account exists and the call value is not less than
|
||||
/// `existential_deposit`, a regular account will be created and any value
|
||||
/// will be transferred.
|
||||
pub fn call<T: Contracts>(
|
||||
dest: <T as System>::Address,
|
||||
value: <T as Balances>::Balance,
|
||||
gas_limit: Gas,
|
||||
data: Vec<u8>,
|
||||
) -> Call<CallArgs<T>> {
|
||||
Call::new(
|
||||
MODULE,
|
||||
calls::CALL,
|
||||
CallArgs {
|
||||
dest,
|
||||
value,
|
||||
gas_limit,
|
||||
data,
|
||||
},
|
||||
)
|
||||
#[derive(Debug, Encode)]
|
||||
pub struct CallCall<'a, T: Contracts> {
|
||||
/// Address of the contract.
|
||||
pub dest: &'a <T as System>::Address,
|
||||
/// Value to transfer to the contract.
|
||||
pub value: <T as Balances>::Balance,
|
||||
/// Gas limit.
|
||||
#[codec(compact)]
|
||||
pub gas_limit: Gas,
|
||||
/// Data to send to the contract.
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a, T: Contracts> Call<T> for CallCall<'a, T> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const FUNCTION: &'static str = "call";
|
||||
}
|
||||
|
||||
/// Code stored event.
|
||||
#[derive(Debug, Decode)]
|
||||
pub struct CodeStoredEvent<T: Contracts> {
|
||||
/// Code hash of the contract.
|
||||
pub code_hash: T::Hash,
|
||||
}
|
||||
|
||||
impl<T: Contracts> Event<T> for CodeStoredEvent<T> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const EVENT: &'static str = "CodeStored";
|
||||
}
|
||||
|
||||
/// Instantiated event.
|
||||
#[derive(Debug, Decode)]
|
||||
pub struct InstantiatedEvent<T: Contracts>(
|
||||
pub <T as System>::AccountId,
|
||||
pub <T as System>::AccountId,
|
||||
);
|
||||
|
||||
impl<T: Contracts> Event<T> for InstantiatedEvent<T> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const EVENT: &'static str = "Instantiated";
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -147,22 +145,16 @@ mod tests {
|
||||
Verify,
|
||||
};
|
||||
|
||||
use super::events;
|
||||
use super::*;
|
||||
use crate::{
|
||||
frame::contracts::MODULE,
|
||||
tests::test_client,
|
||||
Balances,
|
||||
Client,
|
||||
DefaultNodeRuntime as Runtime,
|
||||
Error,
|
||||
System,
|
||||
};
|
||||
|
||||
type AccountId = <Runtime as System>::AccountId;
|
||||
|
||||
async fn put_code<T, P, S>(client: &Client<T, S>, signer: P) -> Result<T::Hash, Error>
|
||||
where
|
||||
T: System + Balances + Send + Sync,
|
||||
T: Contracts + Send + Sync,
|
||||
T::Address: From<T::AccountId>,
|
||||
P: Pair,
|
||||
P::Signature: Codec,
|
||||
@@ -179,10 +171,17 @@ mod tests {
|
||||
|
||||
let xt = client.xt(signer, None).await?;
|
||||
|
||||
let result = xt.watch().submit(super::put_code(500_000, wasm)).await?;
|
||||
let result = xt
|
||||
.watch()
|
||||
.submit(PutCodeCall {
|
||||
gas_limit: 500_000,
|
||||
code: &wasm,
|
||||
})
|
||||
.await?;
|
||||
let code_hash = result
|
||||
.find_event::<T::Hash>(MODULE, events::CODE_STORED)
|
||||
.ok_or(Error::Other("Failed to find CodeStored event".into()))??;
|
||||
.find_event::<CodeStoredEvent<T>>()?
|
||||
.ok_or(Error::Other("Failed to find CodeStored event".into()))?
|
||||
.code_hash;
|
||||
|
||||
Ok(code_hash)
|
||||
}
|
||||
@@ -219,16 +218,16 @@ mod tests {
|
||||
let xt = client.xt(signer, None).await?;
|
||||
let result = xt
|
||||
.watch()
|
||||
.submit(super::instantiate::<Runtime>(
|
||||
100_000_000_000_000,
|
||||
500_000,
|
||||
code_hash,
|
||||
Vec::new(),
|
||||
))
|
||||
.submit(InstantiateCall {
|
||||
endowment: 100_000_000_000_000,
|
||||
gas_limit: 500_000,
|
||||
code_hash: &code_hash,
|
||||
data: &[],
|
||||
})
|
||||
.await?;
|
||||
let event = result
|
||||
.find_event::<(AccountId, AccountId)>(MODULE, events::INSTANTIATED)
|
||||
.ok_or(Error::Other("Failed to find Instantiated event".into()))??;
|
||||
.find_event::<InstantiatedEvent<_>>()?
|
||||
.ok_or(Error::Other("Failed to find Instantiated event".into()))?;
|
||||
Ok(event)
|
||||
});
|
||||
|
||||
|
||||
+54
-19
@@ -16,29 +16,64 @@
|
||||
|
||||
//! Implements support for built-in runtime modules.
|
||||
|
||||
use codec::Encode;
|
||||
use crate::{
|
||||
events::{
|
||||
EventsDecoder,
|
||||
EventsError,
|
||||
},
|
||||
metadata::{
|
||||
Metadata,
|
||||
MetadataError,
|
||||
},
|
||||
};
|
||||
use codec::{
|
||||
Decode,
|
||||
Encode,
|
||||
};
|
||||
use sp_core::storage::StorageKey;
|
||||
|
||||
pub mod balances;
|
||||
pub mod contracts;
|
||||
pub mod system;
|
||||
|
||||
/// Creates module calls
|
||||
pub struct Call<T: Encode> {
|
||||
/// Module name
|
||||
pub module: &'static str,
|
||||
/// Function name
|
||||
pub function: &'static str,
|
||||
/// Call arguments
|
||||
pub args: T,
|
||||
}
|
||||
|
||||
impl<T: Encode> Call<T> {
|
||||
/// Create a module call
|
||||
pub fn new(module: &'static str, function: &'static str, args: T) -> Self {
|
||||
Call {
|
||||
module,
|
||||
function,
|
||||
args,
|
||||
}
|
||||
/// Store trait.
|
||||
pub trait Store<T>: Encode {
|
||||
/// Module name.
|
||||
const MODULE: &'static str;
|
||||
/// Field name.
|
||||
const FIELD: &'static str;
|
||||
/// Return type.
|
||||
type Returns: Decode;
|
||||
/// Returns the `StorageKey`.
|
||||
fn key(&self, metadata: &Metadata) -> Result<StorageKey, MetadataError>;
|
||||
/// Returns the default value.
|
||||
fn default(
|
||||
&self,
|
||||
metadata: &Metadata,
|
||||
) -> Result<Option<Self::Returns>, MetadataError> {
|
||||
Ok(metadata
|
||||
.module(Self::MODULE)?
|
||||
.storage(Self::FIELD)?
|
||||
.default())
|
||||
}
|
||||
}
|
||||
|
||||
/// Call trait.
|
||||
pub trait Call<T>: Encode {
|
||||
/// Module name.
|
||||
const MODULE: &'static str;
|
||||
/// Function name.
|
||||
const FUNCTION: &'static str;
|
||||
/// Load event decoder.
|
||||
fn events_decoder(_decoder: &mut EventsDecoder<T>) -> Result<(), EventsError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Event trait.
|
||||
pub trait Event<T>: Decode {
|
||||
/// Module name.
|
||||
const MODULE: &'static str;
|
||||
/// Event name.
|
||||
const EVENT: &'static str;
|
||||
}
|
||||
|
||||
+27
-59
@@ -22,11 +22,8 @@ use codec::{
|
||||
Encode,
|
||||
};
|
||||
use frame_support::Parameter;
|
||||
use futures::future::{
|
||||
self,
|
||||
Future,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use sp_core::storage::StorageKey;
|
||||
use sp_runtime::{
|
||||
traits::{
|
||||
AtLeast32Bit,
|
||||
@@ -40,24 +37,21 @@ use sp_runtime::{
|
||||
MaybeSerialize,
|
||||
MaybeSerializeDeserialize,
|
||||
Member,
|
||||
SignedExtension,
|
||||
SimpleBitOps,
|
||||
},
|
||||
RuntimeDebug,
|
||||
};
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
pin::Pin,
|
||||
};
|
||||
use std::fmt::Debug;
|
||||
|
||||
use crate::{
|
||||
error::Error,
|
||||
extrinsic::SignedExtra,
|
||||
frame::{
|
||||
balances::Balances,
|
||||
Call,
|
||||
Store,
|
||||
},
|
||||
metadata::{
|
||||
Metadata,
|
||||
MetadataError,
|
||||
},
|
||||
Client,
|
||||
};
|
||||
|
||||
/// The subset of the `frame::Trait` that a client must implement.
|
||||
@@ -116,7 +110,7 @@ pub trait System: 'static + Eq + Clone + Debug {
|
||||
+ Default;
|
||||
|
||||
/// The address type. This instead of `<frame_system::Trait::Lookup as StaticLookup>::Source`.
|
||||
type Address: Codec + Clone + PartialEq + Debug;
|
||||
type Address: Codec + Clone + PartialEq + Debug + Send + Sync;
|
||||
|
||||
/// The block header.
|
||||
type Header: Parameter
|
||||
@@ -147,59 +141,33 @@ pub struct AccountInfo<T: System> {
|
||||
pub data: T::AccountData,
|
||||
}
|
||||
|
||||
/// The System extension trait for the Client.
|
||||
pub trait SystemStore {
|
||||
/// System type.
|
||||
type System: System;
|
||||
const MODULE: &str = "System";
|
||||
|
||||
/// Returns the nonce and account data for an account_id.
|
||||
fn account(
|
||||
&self,
|
||||
account_id: <Self::System as System>::AccountId,
|
||||
) -> Pin<Box<dyn Future<Output = Result<AccountInfo<Self::System>, Error>> + Send>>;
|
||||
}
|
||||
/// Account field of the `System` module.
|
||||
#[derive(Encode)]
|
||||
pub struct AccountStore<'a, T: System>(pub &'a T::AccountId);
|
||||
|
||||
impl<T: System + Balances + Sync + Send + 'static, S: 'static, E> SystemStore
|
||||
for Client<T, S, E>
|
||||
where
|
||||
E: SignedExtra<T> + SignedExtension + 'static,
|
||||
{
|
||||
type System = T;
|
||||
impl<'a, T: System> Store<T> for AccountStore<'a, T> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const FIELD: &'static str = "Account";
|
||||
type Returns = AccountInfo<T>;
|
||||
|
||||
fn account(
|
||||
&self,
|
||||
account_id: <Self::System as System>::AccountId,
|
||||
) -> Pin<Box<dyn Future<Output = Result<AccountInfo<Self::System>, Error>> + Send>>
|
||||
{
|
||||
let account_map = || {
|
||||
Ok(self
|
||||
.metadata
|
||||
.module("System")?
|
||||
.storage("Account")?
|
||||
.get_map()?)
|
||||
};
|
||||
let map = match account_map() {
|
||||
Ok(map) => map,
|
||||
Err(err) => return Box::pin(future::err(err)),
|
||||
};
|
||||
let client = self.clone();
|
||||
Box::pin(async move {
|
||||
client
|
||||
.fetch_or(map.key(account_id), None, map.default())
|
||||
.await
|
||||
})
|
||||
fn key(&self, metadata: &Metadata) -> Result<StorageKey, MetadataError> {
|
||||
Ok(metadata
|
||||
.module(Self::MODULE)?
|
||||
.storage(Self::FIELD)?
|
||||
.map()?
|
||||
.key(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
const MODULE: &str = "System";
|
||||
const SET_CODE: &str = "set_code";
|
||||
|
||||
/// Arguments for updating the runtime code
|
||||
pub type SetCode = Vec<u8>;
|
||||
#[derive(Encode)]
|
||||
pub struct SetCodeCall<'a>(pub &'a Vec<u8>);
|
||||
|
||||
/// Sets the new code.
|
||||
pub fn set_code(code: Vec<u8>) -> Call<SetCode> {
|
||||
Call::new(MODULE, SET_CODE, code)
|
||||
impl<'a, T: System> Call<T> for SetCodeCall<'a> {
|
||||
const MODULE: &'static str = MODULE;
|
||||
const FUNCTION: &'static str = "set_code";
|
||||
}
|
||||
|
||||
use frame_support::weights::DispatchInfo;
|
||||
|
||||
+186
-189
@@ -46,7 +46,6 @@ use std::{
|
||||
|
||||
use codec::{
|
||||
Codec,
|
||||
Decode,
|
||||
Encode,
|
||||
};
|
||||
use futures::future;
|
||||
@@ -80,32 +79,35 @@ mod metadata;
|
||||
mod rpc;
|
||||
mod runtimes;
|
||||
|
||||
pub use self::{
|
||||
pub use crate::{
|
||||
error::Error,
|
||||
events::RawEvent,
|
||||
events::{
|
||||
EventsDecoder,
|
||||
EventsError,
|
||||
RawEvent,
|
||||
},
|
||||
extrinsic::*,
|
||||
frame::*,
|
||||
metadata::{
|
||||
Metadata,
|
||||
MetadataError,
|
||||
},
|
||||
rpc::{
|
||||
BlockNumber,
|
||||
ExtrinsicSuccess,
|
||||
},
|
||||
runtimes::*,
|
||||
};
|
||||
use self::{
|
||||
events::{
|
||||
EventsDecoder,
|
||||
EventsError,
|
||||
},
|
||||
use crate::{
|
||||
frame::{
|
||||
balances::Balances,
|
||||
system::{
|
||||
AccountStore,
|
||||
Phase,
|
||||
System,
|
||||
SystemEvent,
|
||||
SystemStore,
|
||||
},
|
||||
},
|
||||
metadata::Metadata,
|
||||
rpc::{
|
||||
ChainBlock,
|
||||
Rpc,
|
||||
@@ -117,6 +119,7 @@ use self::{
|
||||
pub struct ClientBuilder<T: System, S = MultiSignature, E = DefaultExtra<T>> {
|
||||
_marker: std::marker::PhantomData<(T, S, E)>,
|
||||
url: Option<String>,
|
||||
client: Option<jsonrpsee::Client>,
|
||||
}
|
||||
|
||||
impl<T: System, S, E> ClientBuilder<T, S, E> {
|
||||
@@ -125,19 +128,39 @@ impl<T: System, S, E> ClientBuilder<T, S, E> {
|
||||
Self {
|
||||
_marker: std::marker::PhantomData,
|
||||
url: None,
|
||||
client: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the jsonrpsee client.
|
||||
pub fn set_client<P: Into<jsonrpsee::Client>>(mut self, client: P) -> Self {
|
||||
self.client = Some(client.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the substrate rpc address.
|
||||
pub fn set_url(mut self, url: &str) -> Self {
|
||||
self.url = Some(url.to_string());
|
||||
pub fn set_url<P: Into<String>>(mut self, url: P) -> Self {
|
||||
self.url = Some(url.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Creates a new Client.
|
||||
pub async fn build(self) -> Result<Client<T, S, E>, Error> {
|
||||
let url = self.url.unwrap_or("ws://127.0.0.1:9944".to_string());
|
||||
let rpc = Rpc::connect_ws(&url).await?;
|
||||
let client = if let Some(client) = self.client {
|
||||
client
|
||||
} else {
|
||||
let url = self
|
||||
.url
|
||||
.as_ref()
|
||||
.map(|s| &**s)
|
||||
.unwrap_or("ws://127.0.0.1:9944");
|
||||
if url.starts_with("ws://") || url.starts_with("wss://") {
|
||||
jsonrpsee::ws_client(url).await?
|
||||
} else {
|
||||
jsonrpsee::http_client(url)
|
||||
}
|
||||
};
|
||||
let rpc = Rpc::new(client).await?;
|
||||
|
||||
let (metadata, genesis_hash, runtime_version) = future::join3(
|
||||
rpc.metadata(),
|
||||
@@ -176,43 +199,25 @@ impl<T: System, S, E> Clone for Client<T, S, E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: System + Balances + Sync + Send + 'static, S: 'static, E> Client<T, S, E>
|
||||
where
|
||||
E: SignedExtra<T> + SignedExtension + 'static,
|
||||
{
|
||||
impl<T: System, S, E> Client<T, S, E> {
|
||||
/// Returns the chain metadata.
|
||||
pub fn metadata(&self) -> &Metadata {
|
||||
&self.metadata
|
||||
}
|
||||
|
||||
/// Fetch a StorageKey.
|
||||
pub async fn fetch<V: Decode>(
|
||||
pub async fn fetch<F: Store<T>>(
|
||||
&self,
|
||||
key: StorageKey,
|
||||
store: F,
|
||||
hash: Option<T::Hash>,
|
||||
) -> Result<Option<V>, Error> {
|
||||
self.rpc.storage::<V>(key, hash).await
|
||||
}
|
||||
|
||||
/// Fetch a StorageKey or return the default.
|
||||
pub async fn fetch_or<V: Decode>(
|
||||
&self,
|
||||
key: StorageKey,
|
||||
hash: Option<T::Hash>,
|
||||
default: V,
|
||||
) -> Result<V, Error> {
|
||||
let result = self.fetch(key, hash).await?;
|
||||
Ok(result.unwrap_or(default))
|
||||
}
|
||||
|
||||
/// Fetch a StorageKey or return the default.
|
||||
pub async fn fetch_or_default<V: Decode + Default>(
|
||||
&self,
|
||||
key: StorageKey,
|
||||
hash: Option<T::Hash>,
|
||||
) -> Result<V, Error> {
|
||||
let result = self.fetch(key, hash).await?;
|
||||
Ok(result.unwrap_or_default())
|
||||
) -> Result<Option<F::Returns>, Error> {
|
||||
let key = store.key(&self.metadata)?;
|
||||
let value = self.rpc.storage::<F::Returns>(key, hash).await?;
|
||||
if let Some(v) = value {
|
||||
Ok(Some(v))
|
||||
} else {
|
||||
Ok(store.default(&self.metadata)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Query historical storage entries
|
||||
@@ -301,24 +306,31 @@ where
|
||||
let headers = self.rpc.subscribe_finalized_blocks().await?;
|
||||
Ok(headers)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, E> Client<T, S, E>
|
||||
where
|
||||
T: System + Balances + Send + Sync,
|
||||
S: 'static,
|
||||
E: SignedExtra<T> + SignedExtension + 'static,
|
||||
{
|
||||
/// Creates raw payload to be signed for the supplied `Call` without private key
|
||||
pub async fn create_raw_payload<C: Encode>(
|
||||
pub async fn create_raw_payload<C: Call<T>>(
|
||||
&self,
|
||||
account_id: <T as System>::AccountId,
|
||||
call: Call<C>,
|
||||
) -> Result<
|
||||
SignedPayload<Encoded, <E as SignedExtra<T>>::Extra>,
|
||||
Error
|
||||
>
|
||||
{
|
||||
let account_nonce = self.account(account_id).await?.nonce;
|
||||
account_id: &<T as System>::AccountId,
|
||||
call: C,
|
||||
) -> Result<SignedPayload<Encoded, <E as SignedExtra<T>>::Extra>, Error> {
|
||||
let account_nonce = self
|
||||
.fetch(AccountStore(account_id), None)
|
||||
.await?
|
||||
.unwrap()
|
||||
.nonce;
|
||||
let version = self.runtime_version.spec_version;
|
||||
let genesis_hash = self.genesis_hash;
|
||||
let call = self
|
||||
.metadata()
|
||||
.module_with_calls(&call.module)
|
||||
.and_then(|module| module.call(&call.function, call.args))?;
|
||||
.module_with_calls(C::MODULE)
|
||||
.and_then(|module| module.call(C::FUNCTION, call))?;
|
||||
let extra: E = E::new(version, account_nonce, genesis_hash);
|
||||
let raw_payload = SignedPayload::new(call, extra.extra())?;
|
||||
Ok(raw_payload)
|
||||
@@ -339,7 +351,12 @@ where
|
||||
let account_id = S::Signer::from(signer.public()).into_account();
|
||||
let nonce = match nonce {
|
||||
Some(nonce) => nonce,
|
||||
None => self.account(account_id).await?.nonce,
|
||||
None => {
|
||||
self.fetch(AccountStore(&account_id), None)
|
||||
.await?
|
||||
.unwrap()
|
||||
.nonce
|
||||
}
|
||||
};
|
||||
|
||||
let genesis_hash = self.genesis_hash;
|
||||
@@ -364,11 +381,7 @@ pub struct XtBuilder<T: System, P, S, E> {
|
||||
signer: P,
|
||||
}
|
||||
|
||||
impl<T: System + Balances + Send + Sync + 'static, P, S: 'static, E> XtBuilder<T, P, S, E>
|
||||
where
|
||||
P: Pair,
|
||||
E: SignedExtra<T> + SignedExtension + 'static,
|
||||
{
|
||||
impl<T: System, P, S, E> XtBuilder<T, P, S, E> {
|
||||
/// Returns the chain metadata.
|
||||
pub fn metadata(&self) -> &Metadata {
|
||||
self.client.metadata()
|
||||
@@ -392,7 +405,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: System + Balances + Send + Sync + 'static, P, S: 'static, E> XtBuilder<T, P, S, E>
|
||||
impl<T: System + Send + Sync, P, S: 'static, E> XtBuilder<T, P, S, E>
|
||||
where
|
||||
P: Pair,
|
||||
S: Verify + Codec + From<P::Signature>,
|
||||
@@ -401,24 +414,21 @@ where
|
||||
E: SignedExtra<T> + SignedExtension + 'static,
|
||||
{
|
||||
/// Creates and signs an Extrinsic for the supplied `Call`
|
||||
pub fn create_and_sign<C>(
|
||||
pub fn create_and_sign<C: Call<T>>(
|
||||
&self,
|
||||
call: Call<C>,
|
||||
call: C,
|
||||
) -> Result<
|
||||
UncheckedExtrinsic<T::Address, Encoded, S, <E as SignedExtra<T>>::Extra>,
|
||||
Error,
|
||||
>
|
||||
where
|
||||
C: codec::Encode,
|
||||
{
|
||||
> {
|
||||
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(&call.module)
|
||||
.and_then(|module| module.call(&call.function, call.args))?;
|
||||
.module_with_calls(C::MODULE)
|
||||
.and_then(|module| module.call(C::FUNCTION, call))?;
|
||||
|
||||
log::info!(
|
||||
"Creating Extrinsic with genesis hash {:?} and account nonce {:?}",
|
||||
@@ -432,7 +442,7 @@ where
|
||||
}
|
||||
|
||||
/// Submits a transaction to the chain.
|
||||
pub async fn submit<C: Encode>(&self, call: Call<C>) -> Result<T::Hash, Error> {
|
||||
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)
|
||||
@@ -457,15 +467,7 @@ pub struct EventsSubscriber<T: System, P, S, E> {
|
||||
decoder: Result<EventsDecoder<T>, EventsError>,
|
||||
}
|
||||
|
||||
impl<T: System + Balances + 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,
|
||||
{
|
||||
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>,
|
||||
@@ -481,13 +483,20 @@ where
|
||||
}
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: System + Send + Sync, 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: Encode>(
|
||||
self,
|
||||
call: Call<C>,
|
||||
) -> Result<ExtrinsicSuccess<T>, Error> {
|
||||
let decoder = self.decoder?;
|
||||
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
|
||||
@@ -516,143 +525,131 @@ mod tests {
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
DefaultNodeRuntime as Runtime,
|
||||
Error,
|
||||
};
|
||||
|
||||
pub(crate) async fn test_client() -> Client<Runtime> {
|
||||
ClientBuilder::<Runtime>::new()
|
||||
pub(crate) async fn test_client() -> Client<crate::DefaultNodeRuntime> {
|
||||
ClientBuilder::new()
|
||||
.build()
|
||||
.await
|
||||
.expect("Error creating client")
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[async_std::test]
|
||||
#[ignore] // requires locally running substrate node
|
||||
fn test_tx_transfer_balance() {
|
||||
async fn test_tx_transfer_balance() {
|
||||
env_logger::try_init().ok();
|
||||
let transfer = async_std::task::block_on(async move {
|
||||
let signer = AccountKeyring::Alice.pair();
|
||||
let dest = AccountKeyring::Bob.to_account_id();
|
||||
let signer = AccountKeyring::Alice.pair();
|
||||
let dest = AccountKeyring::Bob.to_account_id().into();
|
||||
|
||||
let client = test_client().await;
|
||||
let mut xt = client.xt(signer, None).await?;
|
||||
let _ = xt
|
||||
.submit(balances::transfer::<Runtime>(dest.clone().into(), 10_000))
|
||||
.await?;
|
||||
let client = test_client().await;
|
||||
let mut xt = client.xt(signer, None).await.unwrap();
|
||||
let _ = xt
|
||||
.submit(balances::TransferCall {
|
||||
to: &dest,
|
||||
amount: 10_000,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// check that nonce is handled correctly
|
||||
xt.increment_nonce()
|
||||
.submit(balances::transfer::<Runtime>(dest.clone().into(), 10_000))
|
||||
.await
|
||||
});
|
||||
|
||||
assert!(transfer.is_ok())
|
||||
// check that nonce is handled correctly
|
||||
xt.increment_nonce()
|
||||
.submit(balances::TransferCall {
|
||||
to: &dest,
|
||||
amount: 10_000,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[async_std::test]
|
||||
#[ignore] // requires locally running substrate node
|
||||
fn test_getting_hash() {
|
||||
let result: Result<_, Error> = async_std::task::block_on(async move {
|
||||
let client = test_client().await;
|
||||
let block_hash = client.block_hash(None).await?;
|
||||
Ok(block_hash)
|
||||
});
|
||||
|
||||
assert!(result.is_ok())
|
||||
async fn test_getting_hash() {
|
||||
let client = test_client().await;
|
||||
client.block_hash(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[async_std::test]
|
||||
#[ignore] // requires locally running substrate node
|
||||
fn test_getting_block() {
|
||||
let result: Result<_, Error> = async_std::task::block_on(async move {
|
||||
let client = test_client().await;
|
||||
let block_hash = client.block_hash(None).await?;
|
||||
let block = client.block(block_hash).await?;
|
||||
Ok(block)
|
||||
});
|
||||
|
||||
assert!(result.is_ok())
|
||||
async fn test_getting_block() {
|
||||
let client = test_client().await;
|
||||
let block_hash = client.block_hash(None).await.unwrap();
|
||||
client.block(block_hash).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[async_std::test]
|
||||
#[ignore] // requires locally running substrate node
|
||||
fn test_state_read_free_balance() {
|
||||
let result: Result<_, Error> = async_std::task::block_on(async move {
|
||||
let account = AccountKeyring::Alice.to_account_id();
|
||||
let client = test_client().await;
|
||||
let balance = client.account(account.into()).await?.data.free;
|
||||
Ok(balance)
|
||||
});
|
||||
|
||||
assert!(result.is_ok())
|
||||
async fn test_state_total_issuance() {
|
||||
let client = test_client().await;
|
||||
client
|
||||
.fetch(balances::TotalIssuance(Default::default()), None)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[async_std::test]
|
||||
#[ignore] // requires locally running substrate node
|
||||
fn test_chain_subscribe_blocks() {
|
||||
let result: Result<_, Error> = async_std::task::block_on(async move {
|
||||
let client = test_client().await;
|
||||
let mut blocks = client.subscribe_blocks().await?;
|
||||
let block = blocks.next().await;
|
||||
Ok(block)
|
||||
});
|
||||
|
||||
assert!(result.is_ok())
|
||||
async fn test_state_read_free_balance() {
|
||||
let client = test_client().await;
|
||||
let account = AccountKeyring::Alice.to_account_id();
|
||||
client
|
||||
.fetch(AccountStore(&account), None)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[async_std::test]
|
||||
#[ignore] // requires locally running substrate node
|
||||
fn test_chain_subscribe_finalized_blocks() {
|
||||
let result: Result<_, Error> = async_std::task::block_on(async move {
|
||||
let client = test_client().await;
|
||||
let mut blocks = client.subscribe_finalized_blocks().await?;
|
||||
let block = blocks.next().await;
|
||||
Ok(block)
|
||||
});
|
||||
|
||||
assert!(result.is_ok())
|
||||
async fn test_chain_subscribe_blocks() {
|
||||
let client = test_client().await;
|
||||
let mut blocks = client.subscribe_blocks().await.unwrap();
|
||||
blocks.next().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[async_std::test]
|
||||
#[ignore] // requires locally running substrate node
|
||||
fn test_create_raw_payload() {
|
||||
let result: Result<_, Error> = async_std::task::block_on(async move {
|
||||
let signer_pair = Ed25519Keyring::Alice.pair();
|
||||
let signer_account_id = Ed25519Keyring::Alice.to_account_id();
|
||||
let dest = AccountKeyring::Bob.to_account_id();
|
||||
async fn test_chain_subscribe_finalized_blocks() {
|
||||
let client = test_client().await;
|
||||
let mut blocks = client.subscribe_finalized_blocks().await.unwrap();
|
||||
blocks.next().await;
|
||||
}
|
||||
|
||||
let client = test_client().await;
|
||||
#[async_std::test]
|
||||
#[ignore] // requires locally running substrate node
|
||||
async fn test_create_raw_payload() {
|
||||
let signer_pair = Ed25519Keyring::Alice.pair();
|
||||
let signer_account_id = Ed25519Keyring::Alice.to_account_id();
|
||||
let dest = AccountKeyring::Bob.to_account_id().into();
|
||||
|
||||
// create raw payload with AccoundId and sign it
|
||||
let raw_payload = client
|
||||
.create_raw_payload(
|
||||
signer_account_id,
|
||||
balances::transfer::<Runtime>(dest.clone().into(), 10_000),
|
||||
)
|
||||
.await?;
|
||||
let raw_signature =
|
||||
signer_pair.sign(raw_payload.encode().as_slice());
|
||||
let raw_multisig = MultiSignature::from(raw_signature);
|
||||
let client = test_client().await;
|
||||
|
||||
// create signature with Xtbuilder
|
||||
let xt = client.xt(signer_pair.clone(), None).await?;
|
||||
let xt_multi_sig = xt
|
||||
.create_and_sign(balances::transfer::<Runtime>(
|
||||
dest.clone().into(),
|
||||
10_000,
|
||||
))?
|
||||
.signature
|
||||
.unwrap()
|
||||
.1;
|
||||
// create raw payload with AccoundId and sign it
|
||||
let raw_payload = client
|
||||
.create_raw_payload(
|
||||
&signer_account_id,
|
||||
balances::TransferCall {
|
||||
to: &dest,
|
||||
amount: 10_000,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let raw_signature = signer_pair.sign(raw_payload.encode().as_slice());
|
||||
let raw_multisig = MultiSignature::from(raw_signature);
|
||||
|
||||
// compare signatures
|
||||
assert_eq!(raw_multisig, xt_multi_sig);
|
||||
// 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,
|
||||
})
|
||||
.unwrap()
|
||||
.signature
|
||||
.unwrap()
|
||||
.1;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
assert!(result.is_ok())
|
||||
// compare signatures
|
||||
assert_eq!(raw_multisig, xt_multi_sig);
|
||||
}
|
||||
}
|
||||
|
||||
+126
-54
@@ -39,26 +39,33 @@ use sp_core::storage::StorageKey;
|
||||
|
||||
use crate::Encoded;
|
||||
|
||||
/// Metadata error.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MetadataError {
|
||||
/// Failed to parse metadata.
|
||||
#[error("Error converting substrate metadata: {0}")]
|
||||
Conversion(#[from] ConversionError),
|
||||
#[error("Module not found")]
|
||||
/// Module is not in metadata.
|
||||
#[error("Module {0} not found")]
|
||||
ModuleNotFound(String),
|
||||
#[error("Module with events not found")]
|
||||
ModuleWithEventsNotFound(u8),
|
||||
#[error("Call not found")]
|
||||
/// Module is not in metadata.
|
||||
#[error("Module index {0} not found")]
|
||||
ModuleIndexNotFound(u8),
|
||||
/// Call is not in metadata.
|
||||
#[error("Call {0} not found")]
|
||||
CallNotFound(&'static str),
|
||||
#[error("Event not found")]
|
||||
/// Event is not in metadata.
|
||||
#[error("Event {0} not found")]
|
||||
EventNotFound(u8),
|
||||
#[error("Storage not found")]
|
||||
/// Storage is not in metadata.
|
||||
#[error("Storage {0} not found")]
|
||||
StorageNotFound(&'static str),
|
||||
/// Storage type does not match requested type.
|
||||
#[error("Storage type error")]
|
||||
StorageTypeError,
|
||||
#[error("Map value type error")]
|
||||
MapValueTypeError,
|
||||
}
|
||||
|
||||
/// Runtime metadata.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Metadata {
|
||||
modules: HashMap<String, ModuleMetadata>,
|
||||
@@ -67,6 +74,7 @@ pub struct Metadata {
|
||||
}
|
||||
|
||||
impl Metadata {
|
||||
/// Returns `ModuleMetadata`.
|
||||
pub fn module<S>(&self, name: S) -> Result<&ModuleMetadata, MetadataError>
|
||||
where
|
||||
S: ToString,
|
||||
@@ -77,7 +85,10 @@ impl Metadata {
|
||||
.ok_or(MetadataError::ModuleNotFound(name))
|
||||
}
|
||||
|
||||
pub fn module_with_calls<S>(&self, name: S) -> Result<&ModuleWithCalls, MetadataError>
|
||||
pub(crate) fn module_with_calls<S>(
|
||||
&self,
|
||||
name: S,
|
||||
) -> Result<&ModuleWithCalls, MetadataError>
|
||||
where
|
||||
S: ToString,
|
||||
{
|
||||
@@ -87,20 +98,21 @@ impl Metadata {
|
||||
.ok_or(MetadataError::ModuleNotFound(name))
|
||||
}
|
||||
|
||||
pub fn modules_with_events(&self) -> impl Iterator<Item = &ModuleWithEvents> {
|
||||
pub(crate) fn modules_with_events(&self) -> impl Iterator<Item = &ModuleWithEvents> {
|
||||
self.modules_with_events.values()
|
||||
}
|
||||
|
||||
pub fn module_with_events(
|
||||
pub(crate) fn module_with_events(
|
||||
&self,
|
||||
module_index: u8,
|
||||
) -> Result<&ModuleWithEvents, MetadataError> {
|
||||
self.modules_with_events
|
||||
.values()
|
||||
.find(|&module| module.index == module_index)
|
||||
.ok_or(MetadataError::ModuleWithEventsNotFound(module_index))
|
||||
.ok_or(MetadataError::ModuleIndexNotFound(module_index))
|
||||
}
|
||||
|
||||
/// Pretty print metadata.
|
||||
pub fn pretty(&self) -> String {
|
||||
let mut string = String::new();
|
||||
for (name, module) in &self.modules {
|
||||
@@ -200,22 +212,78 @@ pub struct StorageMetadata {
|
||||
}
|
||||
|
||||
impl StorageMetadata {
|
||||
pub fn get_map<K: Encode, V: Decode + Clone>(
|
||||
&self,
|
||||
) -> Result<StorageMap<K, V>, MetadataError> {
|
||||
pub fn prefix(&self) -> Vec<u8> {
|
||||
let mut bytes = sp_core::twox_128(self.module_prefix.as_bytes()).to_vec();
|
||||
bytes.extend(&sp_core::twox_128(self.storage_prefix.as_bytes())[..]);
|
||||
bytes
|
||||
}
|
||||
|
||||
pub fn default<V: Decode>(&self) -> Option<V> {
|
||||
// substrate handles the default different for A => B vs A => Option<B>
|
||||
Decode::decode(&mut &self.default[..]).ok()
|
||||
}
|
||||
|
||||
pub fn hash(hasher: &StorageHasher, bytes: &[u8]) -> Vec<u8> {
|
||||
match hasher {
|
||||
StorageHasher::Identity => bytes.to_vec(),
|
||||
StorageHasher::Blake2_128 => sp_core::blake2_128(bytes).to_vec(),
|
||||
StorageHasher::Blake2_128Concat => {
|
||||
// copied from substrate Blake2_128Concat::hash since StorageHasher is not public
|
||||
sp_core::blake2_128(bytes)
|
||||
.iter()
|
||||
.chain(bytes)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
StorageHasher::Blake2_256 => sp_core::blake2_256(bytes).to_vec(),
|
||||
StorageHasher::Twox128 => sp_core::twox_128(bytes).to_vec(),
|
||||
StorageHasher::Twox256 => sp_core::twox_256(bytes).to_vec(),
|
||||
StorageHasher::Twox64Concat => sp_core::twox_64(bytes).to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hash_key<K: Encode>(hasher: &StorageHasher, key: &K) -> Vec<u8> {
|
||||
Self::hash(hasher, &key.encode())
|
||||
}
|
||||
|
||||
pub fn plain(&self) -> Result<StoragePlain, MetadataError> {
|
||||
match &self.ty {
|
||||
StorageEntryType::Plain(_) => {
|
||||
Ok(StoragePlain {
|
||||
prefix: self.prefix(),
|
||||
})
|
||||
}
|
||||
_ => Err(MetadataError::StorageTypeError),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map<K: Encode>(&self) -> Result<StorageMap<K>, MetadataError> {
|
||||
match &self.ty {
|
||||
StorageEntryType::Map { hasher, .. } => {
|
||||
let module_prefix = self.module_prefix.as_bytes().to_vec();
|
||||
let storage_prefix = self.storage_prefix.as_bytes().to_vec();
|
||||
let hasher = hasher.to_owned();
|
||||
let default = Decode::decode(&mut &self.default[..])
|
||||
.map_err(|_| MetadataError::MapValueTypeError)?;
|
||||
Ok(StorageMap {
|
||||
_marker: PhantomData,
|
||||
module_prefix,
|
||||
storage_prefix,
|
||||
hasher,
|
||||
default,
|
||||
prefix: self.prefix(),
|
||||
hasher: hasher.clone(),
|
||||
})
|
||||
}
|
||||
_ => Err(MetadataError::StorageTypeError),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn double_map<K1: Encode, K2: Encode>(
|
||||
&self,
|
||||
) -> Result<StorageDoubleMap<K1, K2>, MetadataError> {
|
||||
match &self.ty {
|
||||
StorageEntryType::DoubleMap {
|
||||
hasher,
|
||||
key2_hasher,
|
||||
..
|
||||
} => {
|
||||
Ok(StorageDoubleMap {
|
||||
_marker: PhantomData,
|
||||
prefix: self.prefix(),
|
||||
hasher1: hasher.clone(),
|
||||
hasher2: key2_hasher.clone(),
|
||||
})
|
||||
}
|
||||
_ => Err(MetadataError::StorageTypeError),
|
||||
@@ -224,41 +292,45 @@ impl StorageMetadata {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StorageMap<K, V> {
|
||||
_marker: PhantomData<K>,
|
||||
module_prefix: Vec<u8>,
|
||||
storage_prefix: Vec<u8>,
|
||||
hasher: StorageHasher,
|
||||
default: V,
|
||||
pub struct StoragePlain {
|
||||
prefix: Vec<u8>,
|
||||
}
|
||||
|
||||
impl<K: Encode, V: Decode + Clone> StorageMap<K, V> {
|
||||
pub fn key(&self, key: K) -> StorageKey {
|
||||
let mut bytes = sp_core::twox_128(&self.module_prefix).to_vec();
|
||||
bytes.extend(&sp_core::twox_128(&self.storage_prefix)[..]);
|
||||
let encoded_key = key.encode();
|
||||
let hash = match self.hasher {
|
||||
StorageHasher::Identity => encoded_key.to_vec(),
|
||||
StorageHasher::Blake2_128 => sp_core::blake2_128(&encoded_key).to_vec(),
|
||||
StorageHasher::Blake2_128Concat => {
|
||||
// copied from substrate Blake2_128Concat::hash since StorageHasher is not public
|
||||
sp_core::blake2_128(&encoded_key)
|
||||
.iter()
|
||||
.chain(&encoded_key)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
StorageHasher::Blake2_256 => sp_core::blake2_256(&encoded_key).to_vec(),
|
||||
StorageHasher::Twox128 => sp_core::twox_128(&encoded_key).to_vec(),
|
||||
StorageHasher::Twox256 => sp_core::twox_256(&encoded_key).to_vec(),
|
||||
StorageHasher::Twox64Concat => sp_core::twox_64(&encoded_key).to_vec(),
|
||||
};
|
||||
bytes.extend(hash);
|
||||
impl StoragePlain {
|
||||
pub fn key(&self) -> StorageKey {
|
||||
StorageKey(self.prefix.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StorageMap<K> {
|
||||
_marker: PhantomData<K>,
|
||||
prefix: Vec<u8>,
|
||||
hasher: StorageHasher,
|
||||
}
|
||||
|
||||
impl<K: Encode> StorageMap<K> {
|
||||
pub fn key(&self, key: &K) -> StorageKey {
|
||||
let mut bytes = self.prefix.clone();
|
||||
bytes.extend(StorageMetadata::hash_key(&self.hasher, key));
|
||||
StorageKey(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default(&self) -> V {
|
||||
self.default.clone()
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StorageDoubleMap<K1, K2> {
|
||||
_marker: PhantomData<(K1, K2)>,
|
||||
prefix: Vec<u8>,
|
||||
hasher1: StorageHasher,
|
||||
hasher2: StorageHasher,
|
||||
}
|
||||
|
||||
impl<K1: Encode, K2: Encode> StorageDoubleMap<K1, K2> {
|
||||
pub fn key(&self, key1: &K1, key2: &K2) -> StorageKey {
|
||||
let mut bytes = self.prefix.clone();
|
||||
bytes.extend(StorageMetadata::hash_key(&self.hasher1, key1));
|
||||
bytes.extend(StorageMetadata::hash_key(&self.hasher2, key2));
|
||||
StorageKey(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-19
@@ -71,12 +71,12 @@ use crate::{
|
||||
RuntimeEvent,
|
||||
},
|
||||
frame::{
|
||||
balances::Balances,
|
||||
system::{
|
||||
Phase,
|
||||
System,
|
||||
SystemEvent,
|
||||
},
|
||||
Event,
|
||||
},
|
||||
metadata::Metadata,
|
||||
};
|
||||
@@ -115,14 +115,10 @@ pub struct Rpc<T: System> {
|
||||
marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> Rpc<T>
|
||||
where
|
||||
T: System,
|
||||
{
|
||||
pub async fn connect_ws(url: &str) -> Result<Self, Error> {
|
||||
let client = jsonrpsee::ws_client(&url).await?;
|
||||
impl<T: System> Rpc<T> {
|
||||
pub async fn new(client: Client) -> Result<Self, Error> {
|
||||
Ok(Rpc {
|
||||
client: client.into(),
|
||||
client,
|
||||
marker: PhantomData,
|
||||
})
|
||||
}
|
||||
@@ -140,6 +136,7 @@ where
|
||||
self.client.request("state_getStorage", params).await?;
|
||||
match data {
|
||||
Some(data) => {
|
||||
log::debug!("state_getStorage {:?}", data.0);
|
||||
let value = Decode::decode(&mut &data.0[..])?;
|
||||
Ok(Some(value))
|
||||
}
|
||||
@@ -247,9 +244,7 @@ where
|
||||
.await?;
|
||||
Ok(version)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: System + Balances + 'static> Rpc<T> {
|
||||
/// Subscribe to substrate System Events
|
||||
pub async fn subscribe_events(
|
||||
&self,
|
||||
@@ -432,19 +427,18 @@ impl<T: System> ExtrinsicSuccess<T> {
|
||||
|
||||
/// Find the Event for the given module/variant, attempting to decode the event data.
|
||||
/// Returns `None` if the Event is not found.
|
||||
/// Returns `Err` if the data fails to decode into the supplied type
|
||||
pub fn find_event<E: Decode>(
|
||||
&self,
|
||||
module: &str,
|
||||
variant: &str,
|
||||
) -> Option<Result<E, CodecError>> {
|
||||
self.find_event_raw(module, variant)
|
||||
.map(|evt| E::decode(&mut &evt.data[..]))
|
||||
/// Returns `Err` if the data fails to decode into the supplied type.
|
||||
pub fn find_event<E: Event<T>>(&self) -> Result<Option<E>, CodecError> {
|
||||
if let Some(event) = self.find_event_raw(E::MODULE, E::EVENT) {
|
||||
Ok(Some(E::decode(&mut &event.data[..])?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for events for the block triggered by the extrinsic
|
||||
pub async fn wait_for_block_events<T: System + Balances + 'static>(
|
||||
pub async fn wait_for_block_events<T: System>(
|
||||
decoder: EventsDecoder<T>,
|
||||
ext_hash: T::Hash,
|
||||
signed_block: ChainBlock<T>,
|
||||
|
||||
Reference in New Issue
Block a user