Merge branch 'master' into staking

This commit is contained in:
Demi M. Obenour
2020-05-14 12:22:18 -04:00
23 changed files with 785 additions and 587 deletions
+19 -22
View File
@@ -14,6 +14,15 @@
// 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::{
Codec,
Compact,
Decode,
Encode,
Error as CodecError,
Input,
Output,
};
use std::{
collections::{
HashMap,
@@ -25,16 +34,7 @@ use std::{
Send,
},
};
use codec::{
Codec,
Compact,
Decode,
Encode,
Error as CodecError,
Input,
Output,
};
use thiserror::Error;
use crate::{
metadata::{
@@ -66,7 +66,7 @@ pub struct RawEvent {
}
/// Events error.
#[derive(Debug, thiserror::Error)]
#[derive(Debug, Error)]
pub enum EventsError {
/// Codec error.
#[error("Scale codec error: {0:?}")]
@@ -80,6 +80,7 @@ pub enum EventsError {
}
/// Event decoder.
#[derive(Debug)]
pub struct EventsDecoder<T> {
metadata: Metadata,
type_sizes: HashMap<String, usize>,
@@ -119,11 +120,6 @@ impl<T: System> TryFrom<Metadata> for 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
@@ -225,6 +221,12 @@ impl<T: System> EventsDecoder<T> {
let event_variant = input.read_byte()?;
let event_metadata = module.event(event_variant)?;
log::debug!(
"received event '{}::{}'",
module.name(),
event_metadata.name
);
let mut event_data = Vec::<u8>::new();
self.decode_raw_bytes(
&event_metadata.arguments(),
@@ -232,12 +234,7 @@ impl<T: System> EventsDecoder<T> {
&mut event_data,
)?;
log::debug!(
"received event '{}::{}', raw bytes: {}",
module.name(),
event_metadata.name,
hex::encode(&event_data),
);
log::debug!("raw bytes: {}", hex::encode(&event_data),);
RuntimeEvent::Raw(RawEvent {
module: module.name().to_string(),
+23 -18
View File
@@ -14,14 +14,15 @@
// 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 std::marker::PhantomData;
use codec::{
Codec,
Decode,
Encode,
};
use core::{
fmt::Debug,
marker::PhantomData,
};
use sp_core::Pair;
use sp_runtime::{
generic::{
@@ -52,7 +53,7 @@ use crate::frame::{
/// This is modified from the substrate version to allow passing in of the version, which is
/// returned via `additional_signed()`.
#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug)]
pub struct CheckVersion<T: System + Send + Sync>(
pub struct CheckVersion<T: System>(
pub PhantomData<T>,
/// Local version to be used for `AdditionalSigned`
#[codec(skip)]
@@ -61,7 +62,7 @@ pub struct CheckVersion<T: System + Send + Sync>(
impl<T> SignedExtension for CheckVersion<T>
where
T: System + Send + Sync,
T: System + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckVersion";
type AccountId = u64;
@@ -82,7 +83,7 @@ where
/// This is modified from the substrate version to allow passing in of the genesis hash, which is
/// returned via `additional_signed()`.
#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug)]
pub struct CheckGenesis<T: System + Send + Sync>(
pub struct CheckGenesis<T: System>(
pub PhantomData<T>,
/// Local genesis hash to be used for `AdditionalSigned`
#[codec(skip)]
@@ -91,7 +92,7 @@ pub struct CheckGenesis<T: System + Send + Sync>(
impl<T> SignedExtension for CheckGenesis<T>
where
T: System + Send + Sync,
T: System + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckGenesis";
type AccountId = u64;
@@ -113,7 +114,7 @@ where
/// returned via `additional_signed()`. It assumes therefore `Era::Immortal` (The transaction is
/// valid forever)
#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug)]
pub struct CheckEra<T: System + Send + Sync>(
pub struct CheckEra<T: System>(
/// The default structure for the Extra encoding
pub (Era, PhantomData<T>),
/// Local genesis hash to be used for `AdditionalSigned`
@@ -123,7 +124,7 @@ pub struct CheckEra<T: System + Send + Sync>(
impl<T> SignedExtension for CheckEra<T>
where
T: System + Send + Sync,
T: System + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckEra";
type AccountId = u64;
@@ -139,11 +140,11 @@ where
/// Nonce check and increment to give replay protection for transactions.
#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug)]
pub struct CheckNonce<T: System + Send + Sync>(#[codec(compact)] pub T::Index);
pub struct CheckNonce<T: System>(#[codec(compact)] pub T::Index);
impl<T> SignedExtension for CheckNonce<T>
where
T: System + Send + Sync,
T: System + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckNonce";
type AccountId = u64;
@@ -159,11 +160,11 @@ where
/// Resource limit check.
#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug)]
pub struct CheckWeight<T: System + Send + Sync>(pub PhantomData<T>);
pub struct CheckWeight<T: System>(pub PhantomData<T>);
impl<T> SignedExtension for CheckWeight<T>
where
T: System + Send + Sync,
T: System + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckWeight";
type AccountId = u64;
@@ -184,7 +185,7 @@ pub struct ChargeTransactionPayment<T: Balances>(#[codec(compact)] pub T::Balanc
impl<T> SignedExtension for ChargeTransactionPayment<T>
where
T: Balances + Send + Sync,
T: Balances + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "ChargeTransactionPayment";
type AccountId = u64;
@@ -200,11 +201,11 @@ where
/// Checks if a transaction would exhausts the block gas limit.
#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug)]
pub struct CheckBlockGasLimit<T: System + Send + Sync>(pub PhantomData<T>);
pub struct CheckBlockGasLimit<T: System>(pub PhantomData<T>);
impl<T> SignedExtension for CheckBlockGasLimit<T>
where
T: System + Send + Sync,
T: System + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckBlockGasLimit";
type AccountId = u64;
@@ -238,7 +239,9 @@ pub struct DefaultExtra<T: System> {
genesis_hash: T::Hash,
}
impl<T: System + Balances + Send + Sync> SignedExtra<T> for DefaultExtra<T> {
impl<T: System + Balances + Clone + Debug + Eq + Send + Sync> SignedExtra<T>
for DefaultExtra<T>
{
type Extra = (
CheckVersion<T>,
CheckGenesis<T>,
@@ -270,7 +273,9 @@ impl<T: System + Balances + Send + Sync> SignedExtra<T> for DefaultExtra<T> {
}
}
impl<T: System + Balances + Send + Sync> SignedExtension for DefaultExtra<T> {
impl<T: System + Balances + Clone + Debug + Eq + Send + Sync> SignedExtension
for DefaultExtra<T>
{
const IDENTIFIER: &'static str = "DefaultExtra";
type AccountId = T::AccountId;
type Call = ();
+66 -40
View File
@@ -16,24 +16,16 @@
//! Implements support for the pallet_balances module.
use crate::{
frame::{
system::System,
Call,
Event,
Store,
},
metadata::{
Metadata,
MetadataError,
},
use crate::frame::system::{
System,
SystemEventsDecoder,
};
use codec::{
Decode,
Encode,
};
use core::marker::PhantomData;
use frame_support::Parameter;
use sp_core::storage::StorageKey;
use sp_runtime::traits::{
AtLeast32Bit,
MaybeSerialize,
@@ -41,9 +33,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.
#[module]
pub trait Balances: System {
/// The balance of an account.
type Balance: Parameter
@@ -58,7 +49,7 @@ pub trait Balances: System {
}
/// All balance information for an account.
#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, Default)]
#[derive(Clone, Debug, Eq, PartialEq, Default, Decode, Encode)]
pub struct AccountData<Balance> {
/// Non-reserved part of the balance. There may still be restrictions on this, but it is the
/// total pool what may in principle be transferred, reserved and used for tipping.
@@ -82,21 +73,11 @@ pub struct AccountData<Balance> {
}
/// The total issuance of the balances module.
#[derive(Encode)]
pub struct TotalIssuance<T>(pub core::marker::PhantomData<T>);
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())
}
#[derive(Clone, Debug, Eq, PartialEq, Store, Encode)]
pub struct TotalIssuanceStore<T: Balances> {
#[store(returns = T::Balance)]
/// Runtime marker.
pub _runtime: PhantomData<T>,
}
/// Transfer some liquid free balance to another account.
@@ -105,7 +86,7 @@ impl<T: Balances> Store<T> for TotalIssuance<T> {
/// 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.
#[derive(Encode)]
#[derive(Clone, Debug, PartialEq, Call, Encode)]
pub struct TransferCall<'a, T: Balances> {
/// Destination of the transfer.
pub to: &'a <T as System>::Address,
@@ -114,13 +95,8 @@ pub struct TransferCall<'a, T: Balances> {
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)]
#[derive(Clone, Debug, Eq, PartialEq, Event, Decode)]
pub struct TransferEvent<T: Balances> {
/// Account balance was transfered from.
pub from: <T as System>::AccountId,
@@ -130,7 +106,57 @@ pub struct TransferEvent<T: Balances> {
pub amount: T::Balance,
}
impl<T: Balances> Event<T> for TransferEvent<T> {
const MODULE: &'static str = MODULE;
const EVENT: &'static str = "transfer";
#[cfg(test)]
mod tests {
use super::*;
use crate::{
system::{
AccountStore,
AccountStoreExt,
},
tests::test_client,
};
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]
#[ignore] // requires locally running substrate node
async fn test_state_total_issuance() {
env_logger::try_init().ok();
let client = test_client().await;
let total_issuance = client.total_issuance().await.unwrap();
assert_ne!(total_issuance, 0);
}
#[async_std::test]
#[ignore] // requires locally running substrate node
async fn test_state_read_free_balance() {
env_logger::try_init().ok();
let client = test_client().await;
let account = AccountKeyring::Alice.to_account_id();
let info = client.account(&account).await.unwrap();
assert_ne!(info.data.free, 0);
}
}
+54 -136
View File
@@ -17,42 +17,40 @@
//! Implements support for the pallet_contracts module.
use crate::frame::{
balances::Balances,
system::System,
Call,
Event,
balances::{
Balances,
BalancesEventsDecoder,
},
system::{
System,
SystemEventsDecoder,
},
};
use codec::{
Decode,
Encode,
};
const MODULE: &str = "Contracts";
use core::marker::PhantomData;
/// Gas units are chosen to be represented by u64 so that gas metering
/// instructions can operate on them efficiently.
pub type Gas = u64;
/// The subset of the `pallet_contracts::Trait` that a client must implement.
#[module]
pub trait Contracts: System + Balances {}
/// Stores the given binary Wasm code into the chain's storage and returns
/// its `codehash`.
/// You can instantiate contracts only with stored code.
#[derive(Debug, Encode)]
pub struct PutCodeCall<'a> {
/// Gas limit.
#[codec(compact)]
pub gas_limit: Gas,
#[derive(Clone, Debug, Eq, PartialEq, Call, Encode)]
pub struct PutCodeCall<'a, T: Contracts> {
/// Runtime marker.
pub _runtime: PhantomData<T>,
/// 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`,
/// optionally transferring some balance.
///
@@ -66,7 +64,7 @@ impl<'a, T: Contracts> Call<T> for PutCodeCall<'a> {
/// of the account. That code will be invoked upon any call received by
/// this account.
/// - The contract is initialized.
#[derive(Debug, Encode)]
#[derive(Clone, Debug, Eq, PartialEq, Call, Encode)]
pub struct InstantiateCall<'a, T: Contracts> {
/// Initial balance transfered to the contract.
#[codec(compact)]
@@ -80,11 +78,6 @@ pub struct InstantiateCall<'a, T: Contracts> {
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.
///
/// * If the account is a smart-contract account, the associated code will
@@ -93,7 +86,7 @@ impl<'a, T: Contracts> Call<T> for InstantiateCall<'a, T> {
/// * 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.
#[derive(Debug, Encode)]
#[derive(Clone, Debug, PartialEq, Call, Encode)]
pub struct CallCall<'a, T: Contracts> {
/// Address of the contract.
pub dest: &'a <T as System>::Address,
@@ -106,136 +99,61 @@ pub struct CallCall<'a, T: Contracts> {
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)]
#[derive(Clone, Debug, Eq, PartialEq, Event, 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";
#[derive(Clone, Debug, Eq, PartialEq, Event, Decode)]
pub struct InstantiatedEvent<T: Contracts> {
/// Caller that instantiated the contract.
pub caller: <T as System>::AccountId,
/// The address of the contract.
pub contract: <T as System>::AccountId,
}
#[cfg(test)]
mod tests {
use codec::Codec;
use sp_core::Pair;
use sp_keyring::AccountKeyring;
use sp_runtime::traits::{
IdentifyAccount,
Verify,
};
use super::*;
use crate::{
tests::test_client,
Client,
Error,
};
async fn put_code<T, P, S>(client: &Client<T, S>, signer: P) -> Result<T::Hash, Error>
where
T: Contracts + Send + Sync,
T::Address: From<T::AccountId>,
P: Pair,
P::Signature: Codec,
S: Verify + Codec + From<P::Signature> + 'static,
S::Signer: From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
{
const CONTRACT: &str = r#"
subxt_test!({
name: test_put_code_and_instantiate,
prelude: {
const CONTRACT: &str = r#"
(module
(func (export "call"))
(func (export "deploy"))
)
"#;
let wasm = wabt::wat2wasm(CONTRACT).expect("invalid wabt");
let xt = client.xt(signer, None).await?;
let result = xt
.watch()
.submit(PutCodeCall {
gas_limit: 500_000,
let wasm = wabt::wat2wasm(CONTRACT).expect("invalid wabt");
let code_hash;
},
step: {
call: PutCodeCall {
_runtime: PhantomData,
code: &wasm,
})
.await?;
let code_hash = result
.find_event::<CodeStoredEvent<T>>()?
.ok_or(Error::Other("Failed to find CodeStored event".into()))?
.code_hash;
Ok(code_hash)
}
#[test]
#[ignore] // requires locally running substrate node
fn tx_put_code() {
env_logger::try_init().ok();
let code_hash: Result<_, Error> = async_std::task::block_on(async move {
let signer = AccountKeyring::Alice.pair();
let client = test_client().await;
let code_hash = put_code(&client, signer).await?;
Ok(code_hash)
});
assert!(
code_hash.is_ok(),
"Contracts CodeStored event should be received and decoded"
);
}
#[test]
#[ignore] // requires locally running substrate node
fn tx_instantiate() {
env_logger::try_init().ok();
let result: Result<_, Error> = async_std::task::block_on(async move {
let signer = AccountKeyring::Bob.pair();
let client = test_client().await;
let code_hash = put_code(&client, signer.clone()).await?;
log::info!("Code hash: {:?}", code_hash);
let xt = client.xt(signer, None).await?;
let result = xt
.watch()
.submit(InstantiateCall {
endowment: 100_000_000_000_000,
gas_limit: 500_000,
code_hash: &code_hash,
data: &[],
})
.await?;
let event = result
.find_event::<InstantiatedEvent<_>>()?
.ok_or(Error::Other("Failed to find Instantiated event".into()))?;
Ok(event)
});
log::info!("Instantiate result: {:?}", result);
assert!(
result.is_ok(),
"Contract should be instantiated successfully"
);
}
},
event: CodeStoredEvent {
code_hash: {
code_hash = event.code_hash.clone();
event.code_hash.clone()
},
},
},
step: {
call: InstantiateCall {
endowment: 100_000_000_000_000,
gas_limit: 500_000_000,
code_hash: &code_hash,
data: &[],
},
event: InstantiatedEvent {
caller: alice.clone(),
contract: event.contract.clone(),
},
},
});
}
+2 -5
View File
@@ -48,14 +48,11 @@ pub trait Store<T>: Encode {
/// 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> {
fn default(&self, metadata: &Metadata) -> Result<Self::Returns, MetadataError> {
Ok(metadata
.module(Self::MODULE)?
.storage(Self::FIELD)?
.default())
.default()?)
}
}
+28 -45
View File
@@ -21,9 +21,12 @@ use codec::{
Decode,
Encode,
};
use frame_support::Parameter;
use core::marker::PhantomData;
use frame_support::{
weights::DispatchInfo,
Parameter,
};
use serde::de::DeserializeOwned;
use sp_core::storage::StorageKey;
use sp_runtime::{
traits::{
AtLeast32Bit,
@@ -39,23 +42,13 @@ use sp_runtime::{
Member,
SimpleBitOps,
},
RuntimeDebug,
DispatchError,
};
use std::fmt::Debug;
use crate::{
frame::{
Call,
Store,
},
metadata::{
Metadata,
MetadataError,
},
};
/// The subset of the `frame::Trait` that a client must implement.
pub trait System: 'static + Eq + Clone + Debug {
#[module]
pub trait System {
/// Account index (aka nonce) type. This stores the number of previous
/// transactions associated with a sender account.
type Index: Parameter
@@ -98,6 +91,7 @@ pub trait System: 'static + Eq + Clone + Debug {
+ AsMut<[u8]>;
/// The hashing system (algorithm) being used in the runtime (e.g. Blake2).
#[module(ignore)]
type Hashing: Hash<Output = Self::Hash>;
/// The user account identifier type for the runtime.
@@ -110,14 +104,17 @@ pub trait System: 'static + Eq + Clone + Debug {
+ Default;
/// The address type. This instead of `<frame_system::Trait::Lookup as StaticLookup>::Source`.
#[module(ignore)]
type Address: Codec + Clone + PartialEq + Debug + Send + Sync;
/// The block header.
#[module(ignore)]
type Header: Parameter
+ Header<Number = Self::BlockNumber, Hash = Self::Hash>
+ DeserializeOwned;
/// Extrinsic type within blocks.
#[module(ignore)]
type Extrinsic: Parameter + Member + Extrinsic + Debug + MaybeSerializeDeserialize;
/// Data to be associated with an account (other than nonce/transaction counter, which this
@@ -129,7 +126,7 @@ pub trait System: 'static + Eq + Clone + Debug {
pub type RefCount = u8;
/// Information of an account.
#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)]
#[derive(Clone, Debug, Eq, PartialEq, Default, Decode, Encode)]
pub struct AccountInfo<T: System> {
/// The number of transactions this account has sent.
pub nonce: T::Index,
@@ -141,54 +138,40 @@ pub struct AccountInfo<T: System> {
pub data: T::AccountData,
}
const MODULE: &str = "System";
/// Account field of the `System` module.
#[derive(Encode)]
pub struct AccountStore<'a, T: System>(pub &'a T::AccountId);
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 key(&self, metadata: &Metadata) -> Result<StorageKey, MetadataError> {
Ok(metadata
.module(Self::MODULE)?
.storage(Self::FIELD)?
.map()?
.key(self.0))
}
#[derive(Clone, Debug, Eq, PartialEq, Store, Encode)]
pub struct AccountStore<'a, T: System> {
#[store(returns = AccountInfo<T>)]
/// Account to retrieve the `AccountInfo<T>` for.
pub account_id: &'a T::AccountId,
}
/// Arguments for updating the runtime code
#[derive(Encode)]
pub struct SetCodeCall<'a>(pub &'a Vec<u8>);
impl<'a, T: System> Call<T> for SetCodeCall<'a> {
const MODULE: &'static str = MODULE;
const FUNCTION: &'static str = "set_code";
#[derive(Clone, Debug, Eq, PartialEq, Call, Encode)]
pub struct SetCodeCall<'a, T: System> {
/// Runtime marker.
pub _runtime: PhantomData<T>,
/// Runtime wasm blob.
pub code: &'a [u8],
}
use frame_support::weights::DispatchInfo;
/// Event for the System module.
#[derive(Clone, Debug, codec::Decode)]
#[derive(Clone, Debug, Eq, PartialEq, Decode)]
pub enum SystemEvent<T: System> {
/// An extrinsic completed successfully.
ExtrinsicSuccess(DispatchInfo),
/// An extrinsic failed.
ExtrinsicFailed(sp_runtime::DispatchError, DispatchInfo),
ExtrinsicFailed(DispatchError, DispatchInfo),
/// `:code` was updated.
CodeUpdated,
/// A new account was created.
NewAccount(T::AccountId),
/// An account was reaped.
ReapedAccount(T::AccountId),
KilledAccount(T::AccountId),
}
/// A phase of a block's execution.
#[derive(codec::Decode)]
#[derive(Clone, Debug, Eq, PartialEq, Decode)]
pub enum Phase {
/// Applying an extrinsic.
ApplyExtrinsic(u32),
+44 -35
View File
@@ -39,6 +39,12 @@
)]
#![allow(clippy::type_complexity)]
#[macro_use]
extern crate substrate_subxt_proc_macro;
pub use sp_core;
pub use sp_runtime;
use std::{
convert::TryFrom,
marker::PhantomData,
@@ -50,6 +56,7 @@ use codec::{
};
use futures::future;
use jsonrpsee::client::Subscription;
use sc_rpc_api::state::ReadProof;
use sp_core::{
storage::{
StorageChangeSet,
@@ -97,12 +104,13 @@ pub use crate::{
ExtrinsicSuccess,
},
runtimes::*,
substrate_subxt_proc_macro::*,
};
use crate::{
frame::{
balances::Balances,
system::{
AccountStore,
AccountStoreExt,
Phase,
System,
SystemEvent,
@@ -160,8 +168,7 @@ impl<T: System, S, E> ClientBuilder<T, S, E> {
jsonrpsee::http_client(url)
}
};
let rpc = Rpc::new(client).await?;
let rpc = Rpc::new(client);
let (metadata, genesis_hash, runtime_version) = future::join3(
rpc.metadata(),
rpc.genesis_hash(),
@@ -210,11 +217,11 @@ impl<T: System, S, E> Client<T, S, E> {
&self,
store: F,
hash: Option<T::Hash>,
) -> Result<Option<F::Returns>, Error> {
) -> Result<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))
Ok(v)
} else {
Ok(store.default(&self.metadata)?)
}
@@ -263,6 +270,19 @@ impl<T: System, S, E> Client<T, S, E> {
Ok(block)
}
/// Get proof of storage entries at a specific block's state.
pub async fn read_proof<H>(
&self,
keys: Vec<StorageKey>,
hash: Option<H>,
) -> Result<ReadProof<T::Hash>, Error>
where
H: Into<T::Hash> + 'static,
{
let proof = self.rpc.read_proof(keys, hash.map(|h| h.into())).await?;
Ok(proof)
}
/// Create and submit an extrinsic and return corresponding Hash if successful
pub async fn submit_extrinsic<X: Encode>(
&self,
@@ -310,7 +330,7 @@ impl<T: System, S, E> Client<T, S, E> {
impl<T, S, E> Client<T, S, E>
where
T: System + Balances + Send + Sync,
T: System + Balances + Send + Sync + 'static,
S: 'static,
E: SignedExtra<T> + SignedExtension + 'static,
{
@@ -320,11 +340,7 @@ where
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 account_nonce = self.account(account_id).await?.nonce;
let version = self.runtime_version.spec_version;
let genesis_hash = self.genesis_hash;
let call = self
@@ -351,12 +367,7 @@ where
let account_id = S::Signer::from(signer.public()).into_account();
let nonce = match nonce {
Some(nonce) => nonce,
None => {
self.fetch(AccountStore(&account_id), None)
.await?
.unwrap()
.nonce
}
None => self.account(&account_id).await?.nonce,
};
let genesis_hash = self.genesis_hash;
@@ -405,7 +416,7 @@ impl<T: System, P, S, E> XtBuilder<T, P, S, E> {
}
}
impl<T: System + Send + Sync, P, S: 'static, E> XtBuilder<T, P, S, E>
impl<T: System + Send + Sync + 'static, P, S: 'static, E> XtBuilder<T, P, S, E>
where
P: Pair,
S: Verify + Codec + From<P::Signature>,
@@ -485,7 +496,7 @@ impl<T: System, P, S, E> EventsSubscriber<T, P, S, E> {
}
}
impl<T: System + Send + Sync, P, S: 'static, E> EventsSubscriber<T, P, S, E>
impl<T: System + Send + Sync + 'static, P, S: 'static, E> EventsSubscriber<T, P, S, E>
where
P: Pair,
S: Verify + Codec + From<P::Signature>,
@@ -508,7 +519,7 @@ where
/// Wraps an already encoded byte vector, prevents being encoded as a raw byte vector as part of
/// the transaction payload
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct Encoded(pub Vec<u8>);
impl codec::Encode for Encoded {
@@ -519,6 +530,10 @@ impl codec::Encode for Encoded {
#[cfg(test)]
mod tests {
use sp_core::storage::{
well_known_keys,
StorageKey,
};
use sp_keyring::{
AccountKeyring,
Ed25519Keyring,
@@ -577,24 +592,18 @@ mod tests {
#[async_std::test]
#[ignore] // requires locally running substrate node
async fn test_state_total_issuance() {
async fn test_getting_read_proof() {
let client = test_client().await;
let block_hash = client.block_hash(None).await.unwrap();
client
.fetch(balances::TotalIssuance(Default::default()), None)
.read_proof(
vec![
StorageKey(well_known_keys::HEAP_PAGES.to_vec()),
StorageKey(well_known_keys::EXTRINSIC_INDEX.to_vec()),
],
block_hash,
)
.await
.unwrap()
.unwrap();
}
#[async_std::test]
#[ignore] // requires locally running substrate node
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();
}
+7 -3
View File
@@ -24,6 +24,7 @@ use std::{
use codec::{
Decode,
Encode,
Error as CodecError,
};
use frame_metadata::{
@@ -63,6 +64,9 @@ pub enum MetadataError {
/// Storage type does not match requested type.
#[error("Storage type error")]
StorageTypeError,
/// Default error.
#[error("Failed to decode default: {0}")]
DefaultError(CodecError),
}
/// Runtime metadata.
@@ -218,9 +222,9 @@ impl StorageMetadata {
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 default<V: Decode>(&self) -> Result<V, MetadataError> {
Decode::decode(&mut &self.default[..])
.map_err(|err| MetadataError::DefaultError(err))
}
pub fn hash(hasher: &StorageHasher, bytes: &[u8]) -> Vec<u8> {
+30 -11
View File
@@ -19,13 +19,16 @@
// Related: https://github.com/paritytech/substrate-subxt/issues/66
#![allow(irrefutable_let_patterns)]
use std::convert::TryInto;
use codec::{
Decode,
Encode,
Error as CodecError,
};
use core::{
convert::TryInto,
marker::PhantomData,
};
use frame_metadata::RuntimeMetadataPrefixed;
use jsonrpsee::{
client::Subscription,
common::{
@@ -34,10 +37,8 @@ use jsonrpsee::{
},
Client,
};
use num_traits::bounds::Bounded;
use frame_metadata::RuntimeMetadataPrefixed;
use sc_rpc_api::state::ReadProof;
use serde::Serialize;
use sp_core::{
storage::{
@@ -61,7 +62,6 @@ use sp_runtime::{
};
use sp_transaction_pool::TransactionStatus;
use sp_version::RuntimeVersion;
use std::marker::PhantomData;
use crate::{
error::Error,
@@ -109,18 +109,26 @@ where
}
/// Client for substrate rpc interfaces
#[derive(Clone)]
pub struct Rpc<T: System> {
client: Client,
marker: std::marker::PhantomData<T>,
marker: PhantomData<T>,
}
impl<T: System> Clone for Rpc<T> {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
marker: PhantomData,
}
}
}
impl<T: System> Rpc<T> {
pub async fn new(client: Client) -> Result<Self, Error> {
Ok(Rpc {
pub fn new(client: Client) -> Self {
Self {
client,
marker: PhantomData,
})
}
}
/// Fetch a storage key
@@ -230,6 +238,17 @@ impl<T: System> Rpc<T> {
Ok(block)
}
/// Get proof of storage entries at a specific block's state.
pub async fn read_proof(
&self,
keys: Vec<StorageKey>,
hash: Option<T::Hash>,
) -> Result<ReadProof<T::Hash>, Error> {
let params = Params::Array(vec![to_json_value(keys)?, to_json_value(hash)?]);
let proof = self.client.request("state_getReadProof", params).await?;
Ok(proof)
}
/// Fetch the runtime version
pub async fn runtime_version(
&self,