Split subxt (#102)

* Proc macro improvements.

* Use proc-macros.

* Update examples.

* Fix build.

* Run rustfmt.

* Fix total issuance test.

* Remove gas limit from put code call.

* Handle runtime errors.

* Fix tests.

* Make test more reliable.

* Revert "Handle runtime errors."

This reverts commit 26f30a9f4cfcfddfb3e49308cded46cfe6468697.

* Use expect instead of unwrap.

* Parse marker type.

* Fetch doesn't fail.
This commit is contained in:
David Craven
2020-05-12 13:25:22 +02:00
committed by GitHub
parent 825f3ab64c
commit f861f3fac4
21 changed files with 697 additions and 564 deletions
+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);
}
}
+55 -131
View File
@@ -17,39 +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> {
#[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.
///
@@ -63,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)]
@@ -77,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
@@ -90,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,
@@ -103,133 +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 { 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: 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_result.is_ok(),
format!(
"Error calling put_code and receiving CodeStored Event: {:?}",
code_hash_result
)
);
}
#[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_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(),
format!("Error instantiating contract: {:?}", result)
);
}
let wasm = wabt::wat2wasm(CONTRACT).expect("invalid wabt");
let code_hash;
},
step: {
call: PutCodeCall {
_runtime: PhantomData,
code: &wasm,
},
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
@@ -47,14 +47,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()?)
}
}
+27 -44
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,44 +138,30 @@ 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.
@@ -188,7 +171,7 @@ pub enum SystemEvent<T: System> {
}
/// A phase of a block's execution.
#[derive(codec::Decode)]
#[derive(Clone, Debug, Eq, PartialEq, Decode)]
pub enum Phase {
/// Applying an extrinsic.
ApplyExtrinsic(u32),