Configurable Config and Extra types (#373)

* WIP config

* WIP separate default config

* Separate trait impls on client

* WIP introduce new ApiConfig (to be renamed) trait

* Update generated polkadot codegen

* Allow configuring Config and Extra types independently

* Add extra default configuration

* Revert ir parsing of config attr

* Add default-features = false to substrate deps

* Revert "Add default-features = false to substrate deps"

This reverts commit 099d20cd4cbf8000ff938d1dc090ecbc28a5e788.
This commit is contained in:
Andrew Jones
2022-01-06 09:39:38 +00:00
committed by GitHub
parent 30665bf1c2
commit ca5345c47e
22 changed files with 11057 additions and 5027 deletions
+8 -5
View File
@@ -68,7 +68,7 @@ pub fn generate_calls(
pub fn #fn_name(
&self,
#( #call_fn_args, )*
) -> ::subxt::SubmittableExtrinsic<'a, T, #call_struct_name> {
) -> ::subxt::SubmittableExtrinsic<'a, T, E, A, #call_struct_name> {
let call = #call_struct_name { #( #call_args, )* };
::subxt::SubmittableExtrinsic::new(self.client, call)
}
@@ -82,16 +82,19 @@ pub fn generate_calls(
use super::#types_mod_ident;
#( #call_structs )*
pub struct TransactionApi<'a, T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>> {
pub struct TransactionApi<'a, T: ::subxt::Config, E, A> {
client: &'a ::subxt::Client<T>,
marker: ::core::marker::PhantomData<(E, A)>,
}
impl<'a, T: ::subxt::Config> TransactionApi<'a, T>
impl<'a, T, E, A> TransactionApi<'a, T, E, A>
where
T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>,
T: ::subxt::Config,
E: ::subxt::SignedExtra<T>,
A: ::subxt::AccountData<T>,
{
pub fn new(client: &'a ::subxt::Client<T>) -> Self {
Self { client }
Self { client, marker: ::core::marker::PhantomData }
}
#( #call_fns )*
+27 -44
View File
@@ -152,6 +152,7 @@ impl RuntimeGenerator {
)
})
.collect::<Vec<_>>();
let modules = pallets_with_mod_names.iter().map(|(pallet, mod_name)| {
let calls = if let Some(ref calls) = pallet.calls {
calls::generate_calls(&type_gen, pallet, calls, types_mod_ident)
@@ -222,76 +223,55 @@ impl RuntimeGenerator {
#( #modules )*
#types_mod
/// Default configuration of common types for a target Substrate runtime.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DefaultConfig;
/// The default storage entry from which to fetch an account nonce, required for
/// constructing a transaction.
pub type DefaultAccountData = self::system::storage::Account;
impl ::subxt::Config for DefaultConfig {
type Index = u32;
type BlockNumber = u32;
type Hash = ::subxt::sp_core::H256;
type Hashing = ::subxt::sp_runtime::traits::BlakeTwo256;
type AccountId = ::subxt::sp_runtime::AccountId32;
type Address = ::subxt::sp_runtime::MultiAddress<Self::AccountId, u32>;
type Header = ::subxt::sp_runtime::generic::Header<
Self::BlockNumber, ::subxt::sp_runtime::traits::BlakeTwo256
>;
type Signature = ::subxt::sp_runtime::MultiSignature;
type Extrinsic = ::subxt::sp_runtime::OpaqueExtrinsic;
}
impl ::subxt::ExtrinsicExtraData<DefaultConfig> for DefaultConfig {
type AccountData = AccountData;
type Extra = ::subxt::DefaultExtra<DefaultConfig>;
}
pub type AccountData = self::system::storage::Account;
impl ::subxt::AccountData<DefaultConfig> for AccountData {
fn nonce(result: &<Self as ::subxt::StorageEntry>::Value) -> <DefaultConfig as ::subxt::Config>::Index {
impl ::subxt::AccountData<::subxt::DefaultConfig> for DefaultAccountData {
fn nonce(result: &<Self as ::subxt::StorageEntry>::Value) -> <::subxt::DefaultConfig as ::subxt::Config>::Index {
result.nonce
}
fn storage_entry(account_id: <DefaultConfig as ::subxt::Config>::AccountId) -> Self {
fn storage_entry(account_id: <::subxt::DefaultConfig as ::subxt::Config>::AccountId) -> Self {
Self(account_id)
}
}
pub struct RuntimeApi<T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>> {
pub struct RuntimeApi<T: ::subxt::Config, E> {
pub client: ::subxt::Client<T>,
marker: ::core::marker::PhantomData<E>,
}
impl<T> ::core::convert::From<::subxt::Client<T>> for RuntimeApi<T>
impl<T, E> ::core::convert::From<::subxt::Client<T>> for RuntimeApi<T, E>
where
T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>,
T: ::subxt::Config,
E: ::subxt::SignedExtra<T>,
{
fn from(client: ::subxt::Client<T>) -> Self {
Self { client }
Self { client, marker: ::core::marker::PhantomData }
}
}
impl<'a, T> RuntimeApi<T>
impl<'a, T, E> RuntimeApi<T, E>
where
T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>,
T: ::subxt::Config,
E: ::subxt::SignedExtra<T>,
{
pub fn storage(&'a self) -> StorageApi<'a, T> {
StorageApi { client: &self.client }
}
pub fn tx(&'a self) -> TransactionApi<'a, T> {
TransactionApi { client: &self.client }
pub fn tx(&'a self) -> TransactionApi<'a, T, E, DefaultAccountData> {
TransactionApi { client: &self.client, marker: ::core::marker::PhantomData }
}
}
pub struct StorageApi<'a, T>
where
T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>,
{
pub struct StorageApi<'a, T: ::subxt::Config> {
client: &'a ::subxt::Client<T>,
}
impl<'a, T> StorageApi<'a, T>
where
T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>,
T: ::subxt::Config,
{
#(
pub fn #pallets_with_storage(&self) -> #pallets_with_storage::storage::StorageApi<'a, T> {
@@ -300,16 +280,19 @@ impl RuntimeGenerator {
)*
}
pub struct TransactionApi<'a, T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>> {
pub struct TransactionApi<'a, T: ::subxt::Config, E, A> {
client: &'a ::subxt::Client<T>,
marker: ::core::marker::PhantomData<(E, A)>,
}
impl<'a, T> TransactionApi<'a, T>
impl<'a, T, E, A> TransactionApi<'a, T, E, A>
where
T: ::subxt::Config + ::subxt::ExtrinsicExtraData<T>,
T: ::subxt::Config,
E: ::subxt::SignedExtra<T>,
A: ::subxt::AccountData<T>,
{
#(
pub fn #pallets_with_calls(&self) -> #pallets_with_calls::calls::TransactionApi<'a, T> {
pub fn #pallets_with_calls(&self) -> #pallets_with_calls::calls::TransactionApi<'a, T, E, A> {
#pallets_with_calls::calls::TransactionApi::new(self.client)
}
)*
-1
View File
@@ -74,7 +74,6 @@ impl ItemMod {
#[allow(clippy::large_enum_variant)]
#[derive(Debug, PartialEq, Eq)]
#[allow(clippy::large_enum_variant)]
pub enum Item {
Rust(syn::Item),
Subxt(SubxtItem),
+6 -2
View File
@@ -22,7 +22,11 @@
//! polkadot --dev --tmp
//! ```
use subxt::ClientBuilder;
use subxt::{
ClientBuilder,
DefaultConfig,
DefaultExtra,
};
#[subxt::subxt(runtime_metadata_path = "examples/polkadot_metadata.scale")]
pub mod polkadot {}
@@ -34,7 +38,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api = ClientBuilder::new()
.build()
.await?
.to_runtime_api::<polkadot::RuntimeApi<polkadot::DefaultConfig>>();
.to_runtime_api::<polkadot::RuntimeApi<DefaultConfig, DefaultExtra<DefaultConfig>>>();
let mut iter = api.storage().system().account_iter(None).await?;
+6 -2
View File
@@ -14,7 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with subxt. If not, see <http://www.gnu.org/licenses/>.
use subxt::ClientBuilder;
use subxt::{
ClientBuilder,
DefaultConfig,
DefaultExtra,
};
#[subxt::subxt(runtime_metadata_path = "examples/polkadot_metadata.scale")]
pub mod polkadot {}
@@ -27,7 +31,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.set_url("wss://rpc.polkadot.io:443")
.build()
.await?
.to_runtime_api::<polkadot::RuntimeApi<polkadot::DefaultConfig>>();
.to_runtime_api::<polkadot::RuntimeApi<DefaultConfig, DefaultExtra<DefaultConfig>>>();
let block_number = 1;
+3 -1
View File
@@ -25,6 +25,8 @@
use sp_keyring::AccountKeyring;
use subxt::{
ClientBuilder,
DefaultConfig,
DefaultExtra,
PairSigner,
};
@@ -41,7 +43,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api = ClientBuilder::new()
.build()
.await?
.to_runtime_api::<polkadot::RuntimeApi<polkadot::DefaultConfig>>();
.to_runtime_api::<polkadot::RuntimeApi<DefaultConfig, DefaultExtra<DefaultConfig>>>();
let hash = api
.tx()
.balances()
+5 -3
View File
@@ -26,6 +26,8 @@ use futures::StreamExt;
use sp_keyring::AccountKeyring;
use subxt::{
ClientBuilder,
DefaultConfig,
DefaultExtra,
PairSigner,
};
@@ -53,7 +55,7 @@ async fn simple_transfer() -> Result<(), Box<dyn std::error::Error>> {
let api = ClientBuilder::new()
.build()
.await?
.to_runtime_api::<polkadot::RuntimeApi<polkadot::DefaultConfig>>();
.to_runtime_api::<polkadot::RuntimeApi<DefaultConfig, DefaultExtra<_>>>();
let balance_transfer = api
.tx()
@@ -85,7 +87,7 @@ async fn simple_transfer_separate_events() -> Result<(), Box<dyn std::error::Err
let api = ClientBuilder::new()
.build()
.await?
.to_runtime_api::<polkadot::RuntimeApi<polkadot::DefaultConfig>>();
.to_runtime_api::<polkadot::RuntimeApi<DefaultConfig, DefaultExtra<_>>>();
let balance_transfer = api
.tx()
@@ -136,7 +138,7 @@ async fn handle_transfer_events() -> Result<(), Box<dyn std::error::Error>> {
let api = ClientBuilder::new()
.build()
.await?
.to_runtime_api::<polkadot::RuntimeApi<polkadot::DefaultConfig>>();
.to_runtime_api::<polkadot::RuntimeApi<DefaultConfig, DefaultExtra<_>>>();
let mut balance_transfer_progress = api
.tx()
+4 -2
View File
@@ -25,6 +25,8 @@
use sp_keyring::AccountKeyring;
use subxt::{
ClientBuilder,
DefaultConfig,
DefaultExtra,
EventSubscription,
PairSigner,
};
@@ -42,11 +44,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api = ClientBuilder::new()
.build()
.await?
.to_runtime_api::<polkadot::RuntimeApi<polkadot::DefaultConfig>>();
.to_runtime_api::<polkadot::RuntimeApi<DefaultConfig, DefaultExtra<DefaultConfig>>>();
let sub = api.client.rpc().subscribe_events().await?;
let decoder = api.client.events_decoder();
let mut sub = EventSubscription::<polkadot::DefaultConfig>::new(sub, decoder);
let mut sub = EventSubscription::<DefaultConfig>::new(sub, decoder);
sub.filter_event::<polkadot::balances::events::Transfer>();
api.tx()
+24 -18
View File
@@ -38,7 +38,6 @@ use crate::{
AccountData,
Call,
Config,
ExtrinsicExtraData,
Metadata,
};
use std::sync::Arc;
@@ -185,19 +184,26 @@ impl<T: Config> Client<T> {
}
/// A constructed call ready to be signed and submitted.
pub struct SubmittableExtrinsic<'client, T: Config, C> {
pub struct SubmittableExtrinsic<'client, T: Config, E, A, C> {
client: &'client Client<T>,
call: C,
marker: std::marker::PhantomData<(E, A)>,
}
impl<'client, T, C> SubmittableExtrinsic<'client, T, C>
impl<'client, T, E, A, C> SubmittableExtrinsic<'client, T, E, A, C>
where
T: Config + ExtrinsicExtraData<T>,
T: Config,
E: SignedExtra<T>,
A: AccountData<T>,
C: Call + Send + Sync,
{
/// Create a new [`SubmittableExtrinsic`].
pub fn new(client: &'client Client<T>, call: C) -> Self {
Self { client, call }
Self {
client,
call,
marker: Default::default(),
}
}
/// Creates and signs an extrinsic and submits it to the chain.
@@ -206,10 +212,11 @@ where
/// and obtain details about it, once it has made it into a block.
pub async fn sign_and_submit_then_watch(
self,
signer: &(dyn Signer<T> + Send + Sync),
signer: &(dyn Signer<T, E> + Send + Sync),
) -> Result<TransactionProgress<'client, T>, Error>
where
<<<T as ExtrinsicExtraData<T>>::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync + 'static
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
Send + Sync + 'static,
{
// Sign the call data to create our extrinsic.
let extrinsic = self.create_signed(signer, Default::default()).await?;
@@ -231,10 +238,11 @@ where
/// and has been included in the transaction pool.
pub async fn sign_and_submit(
self,
signer: &(dyn Signer<T> + Send + Sync),
signer: &(dyn Signer<T, E> + Send + Sync),
) -> Result<T::Hash, Error>
where
<<<T as ExtrinsicExtraData<T>>::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync + 'static
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
Send + Sync + 'static,
{
let extrinsic = self.create_signed(signer, Default::default()).await?;
self.client.rpc().submit_extrinsic(extrinsic).await
@@ -243,25 +251,23 @@ where
/// Creates a signed extrinsic.
pub async fn create_signed(
&self,
signer: &(dyn Signer<T> + Send + Sync),
additional_params: <T::Extra as SignedExtra<T>>::Parameters,
) -> Result<UncheckedExtrinsic<T>, Error>
signer: &(dyn Signer<T, E> + Send + Sync),
additional_params: E::Parameters,
) -> Result<UncheckedExtrinsic<T, E>, Error>
where
<<<T as ExtrinsicExtraData<T>>::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync + 'static
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
Send + Sync + 'static,
{
let account_nonce = if let Some(nonce) = signer.nonce() {
nonce
} else {
let account_storage_entry =
<<T as ExtrinsicExtraData<T>>::AccountData as AccountData<T>>::storage_entry(signer.account_id().clone());
let account_storage_entry = A::storage_entry(signer.account_id().clone());
let account_data = self
.client
.storage()
.fetch_or_default(&account_storage_entry, None)
.await?;
<<T as ExtrinsicExtraData<T>>::AccountData as AccountData<T>>::nonce(
&account_data,
)
A::nonce(&account_data)
};
let call = self
.client
+19 -13
View File
@@ -14,10 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with subxt. If not, see <http://www.gnu.org/licenses/>.
use crate::{
SignedExtra,
StorageEntry,
};
use crate::StorageEntry;
use codec::{
Codec,
Encode,
@@ -35,7 +32,7 @@ use sp_runtime::traits::{
};
/// Runtime types.
pub trait Config: Clone + Sized + Send + Sync + 'static {
pub trait Config: Clone + Default + Sized + Send + Sync + 'static {
/// Account index (aka nonce) type. This stores the number of previous
/// transactions associated with a sender account.
type Index: Parameter + Member + Default + AtLeast32Bit + Copy + scale_info::TypeInfo;
@@ -85,6 +82,23 @@ pub trait Config: Clone + Sized + Send + Sync + 'static {
pub trait Parameter: Codec + EncodeLike + Clone + Eq + Debug {}
impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + Debug {}
/// Default set of commonly used types by Substrate runtimes.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DefaultConfig;
impl Config for DefaultConfig {
type Index = u32;
type BlockNumber = u32;
type Hash = sp_core::H256;
type Hashing = sp_runtime::traits::BlakeTwo256;
type AccountId = sp_runtime::AccountId32;
type Address = sp_runtime::MultiAddress<Self::AccountId, u32>;
type Header =
sp_runtime::generic::Header<Self::BlockNumber, sp_runtime::traits::BlakeTwo256>;
type Signature = sp_runtime::MultiSignature;
type Extrinsic = sp_runtime::OpaqueExtrinsic;
}
/// Trait to fetch data about an account.
///
/// Should be implemented on a type implementing `StorageEntry`,
@@ -95,11 +109,3 @@ pub trait AccountData<T: Config>: StorageEntry {
/// Get the nonce from the storage entry value.
fn nonce(result: &<Self as StorageEntry>::Value) -> T::Index;
}
/// Trait to configure the extra data for an extrinsic.
pub trait ExtrinsicExtraData<T: Config> {
/// The type of the [`StorageEntry`] which can be used to retrieve an account nonce.
type AccountData: AccountData<T>;
/// The type of extra data and additional signed data to be included in a transaction.
type Extra: SignedExtra<T> + Send + Sync + 'static;
}
+71 -19
View File
@@ -62,7 +62,7 @@ where
T: Config + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckSpecVersion";
type AccountId = u64;
type AccountId = T::AccountId;
type Call = ();
type AdditionalSigned = u32;
type Pre = ();
@@ -102,7 +102,7 @@ where
T: Config + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckTxVersion";
type AccountId = u64;
type AccountId = T::AccountId;
type Call = ();
type AdditionalSigned = u32;
type Pre = ();
@@ -142,7 +142,7 @@ where
T: Config + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckGenesis";
type AccountId = u64;
type AccountId = T::AccountId;
type Call = ();
type AdditionalSigned = T::Hash;
type Pre = ();
@@ -184,7 +184,7 @@ where
T: Config + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckMortality";
type AccountId = u64;
type AccountId = T::AccountId;
type Call = ();
type AdditionalSigned = T::Hash;
type Pre = ();
@@ -214,7 +214,7 @@ where
T: Config + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckNonce";
type AccountId = u64;
type AccountId = T::AccountId;
type Call = ();
type AdditionalSigned = ();
type Pre = ();
@@ -244,7 +244,7 @@ where
T: Config + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "CheckWeight";
type AccountId = u64;
type AccountId = T::AccountId;
type Call = ();
type AdditionalSigned = ();
type Pre = ();
@@ -266,19 +266,58 @@ where
/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
/// in the queue.
#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug, TypeInfo)]
#[derive(Encode, Decode, Clone, Debug, Default, Eq, PartialEq, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct ChargeAssetTxPayment {
pub struct ChargeTransactionPayment<T: Config>(
#[codec(compact)] u128,
pub PhantomData<T>,
);
impl<T> SignedExtension for ChargeTransactionPayment<T>
where
T: Config + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "ChargeTransactionPayment";
type AccountId = T::AccountId;
type Call = ();
type AdditionalSigned = ();
type Pre = ();
fn additional_signed(
&self,
) -> Result<Self::AdditionalSigned, TransactionValidityError> {
Ok(())
}
fn pre_dispatch(
self,
_who: &Self::AccountId,
_call: &Self::Call,
_info: &DispatchInfoOf<Self::Call>,
_len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
Ok(())
}
}
/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
/// in the queue.
#[derive(Encode, Decode, Clone, Default, Eq, PartialEq, Debug, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct ChargeAssetTxPayment<T: Config> {
/// The tip for the block author.
#[codec(compact)]
pub tip: u128,
/// The asset with which to pay the tip.
pub asset_id: Option<u32>,
/// Marker for unused type parameter.
pub marker: PhantomData<T>,
}
impl SignedExtension for ChargeAssetTxPayment {
impl<T> SignedExtension for ChargeAssetTxPayment<T>
where
T: Config + Clone + Debug + Eq + Send + Sync,
{
const IDENTIFIER: &'static str = "ChargeAssetTxPayment";
type AccountId = u64;
type AccountId = T::AccountId;
type Call = ();
type AdditionalSigned = ();
type Pre = ();
@@ -321,14 +360,19 @@ pub trait SignedExtra<T: Config>: SignedExtension {
/// Default `SignedExtra` for substrate runtimes.
#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct DefaultExtra<T: Config> {
pub struct DefaultExtraWithTxPayment<T: Config, X> {
spec_version: u32,
tx_version: u32,
nonce: T::Index,
genesis_hash: T::Hash,
marker: PhantomData<X>,
}
impl<T: Config + Clone + Debug + Eq + Send + Sync> SignedExtra<T> for DefaultExtra<T> {
impl<T, X> SignedExtra<T> for DefaultExtraWithTxPayment<T, X>
where
T: Config + Clone + Debug + Eq + Send + Sync,
X: SignedExtension<AccountId = T::AccountId, Call = ()> + Default,
{
type Extra = (
CheckSpecVersion<T>,
CheckTxVersion<T>,
@@ -336,7 +380,7 @@ impl<T: Config + Clone + Debug + Eq + Send + Sync> SignedExtra<T> for DefaultExt
CheckMortality<T>,
CheckNonce<T>,
CheckWeight<T>,
ChargeAssetTxPayment,
X,
);
type Parameters = ();
@@ -347,11 +391,12 @@ impl<T: Config + Clone + Debug + Eq + Send + Sync> SignedExtra<T> for DefaultExt
genesis_hash: T::Hash,
_params: Self::Parameters,
) -> Self {
DefaultExtra {
DefaultExtraWithTxPayment {
spec_version,
tx_version,
nonce,
genesis_hash,
marker: PhantomData,
}
}
@@ -363,15 +408,17 @@ impl<T: Config + Clone + Debug + Eq + Send + Sync> SignedExtra<T> for DefaultExt
CheckMortality((Era::Immortal, PhantomData), self.genesis_hash),
CheckNonce(self.nonce),
CheckWeight(PhantomData),
ChargeAssetTxPayment {
tip: u128::default(),
asset_id: None,
},
X::default(),
)
}
}
impl<T: Config + Clone + Debug + Eq + Send + Sync> SignedExtension for DefaultExtra<T> {
impl<T, X: SignedExtension<AccountId = T::AccountId, Call = ()> + Default> SignedExtension
for DefaultExtraWithTxPayment<T, X>
where
T: Config + Clone + Debug + Eq + Send + Sync,
X: SignedExtension,
{
const IDENTIFIER: &'static str = "DefaultExtra";
type AccountId = T::AccountId;
type Call = ();
@@ -394,3 +441,8 @@ impl<T: Config + Clone + Debug + Eq + Send + Sync> SignedExtension for DefaultEx
Ok(())
}
}
/// A default `SignedExtra` configuration, with [`ChargeTransactionPayment`] for tipping.
///
/// Note that this must match the `SignedExtra` type in the target runtime's extrinsic definition.
pub type DefaultExtra<T> = DefaultExtraWithTxPayment<T, ChargeTransactionPayment<T>>;
+14 -16
View File
@@ -29,6 +29,7 @@ pub use self::{
CheckTxVersion,
CheckWeight,
DefaultExtra,
DefaultExtraWithTxPayment,
SignedExtra,
},
signer::{
@@ -44,47 +45,44 @@ use crate::{
Config,
Encoded,
Error,
ExtrinsicExtraData,
};
/// UncheckedExtrinsic type.
pub type UncheckedExtrinsic<T> = sp_runtime::generic::UncheckedExtrinsic<
pub type UncheckedExtrinsic<T, E> = sp_runtime::generic::UncheckedExtrinsic<
<T as Config>::Address,
Encoded,
<T as Config>::Signature,
<<T as ExtrinsicExtraData<T>>::Extra as SignedExtra<T>>::Extra,
<E as SignedExtra<T>>::Extra,
>;
/// SignedPayload type.
pub type SignedPayload<T> = sp_runtime::generic::SignedPayload<
Encoded,
<<T as ExtrinsicExtraData<T>>::Extra as SignedExtra<T>>::Extra,
>;
pub type SignedPayload<T, E> =
sp_runtime::generic::SignedPayload<Encoded, <E as SignedExtra<T>>::Extra>;
/// Creates a signed extrinsic
pub async fn create_signed<T>(
pub async fn create_signed<T, E>(
runtime_version: &RuntimeVersion,
genesis_hash: T::Hash,
nonce: T::Index,
call: Encoded,
signer: &(dyn Signer<T> + Send + Sync),
additional_params: <T::Extra as SignedExtra<T>>::Parameters,
) -> Result<UncheckedExtrinsic<T>, Error>
signer: &(dyn Signer<T, E> + Send + Sync),
additional_params: E::Parameters,
) -> Result<UncheckedExtrinsic<T, E>, Error>
where
T: Config + ExtrinsicExtraData<T>,
<<<T as ExtrinsicExtraData<T>>::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
Send + Sync,
T: Config,
E: SignedExtra<T>,
<E::Extra as SignedExtension>::AdditionalSigned: Send + Sync,
{
let spec_version = runtime_version.spec_version;
let tx_version = runtime_version.transaction_version;
let extra = <T as ExtrinsicExtraData<T>>::Extra::new(
let extra = E::new(
spec_version,
tx_version,
nonce,
genesis_hash,
additional_params,
);
let payload = SignedPayload::<T>::new(call, extra.extra())?;
let payload = SignedPayload::<T, E>::new(call, extra.extra())?;
let signed = signer.sign(payload).await?;
Ok(signed)
}
+19 -17
View File
@@ -18,14 +18,11 @@
//! [substrate](https://github.com/paritytech/substrate) node via RPC.
use super::{
SignedExtra,
SignedPayload,
UncheckedExtrinsic,
};
use crate::{
Config,
ExtrinsicExtraData,
SignedExtra,
};
use crate::Config;
use codec::Encode;
use sp_core::Pair;
use sp_runtime::traits::{
@@ -36,7 +33,7 @@ use sp_runtime::traits::{
/// Extrinsic signer.
#[async_trait::async_trait]
pub trait Signer<T: Config + ExtrinsicExtraData<T>> {
pub trait Signer<T: Config, E: SignedExtra<T>> {
/// Returns the account id.
fn account_id(&self) -> &T::AccountId;
@@ -49,21 +46,23 @@ pub trait Signer<T: Config + ExtrinsicExtraData<T>> {
/// refused the operation.
async fn sign(
&self,
extrinsic: SignedPayload<T>,
) -> Result<UncheckedExtrinsic<T>, String>;
extrinsic: SignedPayload<T, E>,
) -> Result<UncheckedExtrinsic<T, E>, String>;
}
/// Extrinsic signer using a private key.
#[derive(Clone, Debug)]
pub struct PairSigner<T: Config, P: Pair> {
pub struct PairSigner<T: Config, E, P: Pair> {
account_id: T::AccountId,
nonce: Option<T::Index>,
signer: P,
marker: std::marker::PhantomData<E>,
}
impl<T, P> PairSigner<T, P>
impl<T, E, P> PairSigner<T, E, P>
where
T: Config + ExtrinsicExtraData<T>,
T: Config,
E: SignedExtra<T>,
T::Signature: From<P::Signature>,
<T::Signature as Verify>::Signer:
From<P::Public> + IdentifyAccount<AccountId = T::AccountId>,
@@ -77,6 +76,7 @@ where
account_id,
nonce: None,
signer,
marker: Default::default(),
}
}
@@ -97,11 +97,13 @@ where
}
#[async_trait::async_trait]
impl<T, P> Signer<T> for PairSigner<T, P>
impl<T, E, P> Signer<T, E> for PairSigner<T, E, P>
where
T: Config + ExtrinsicExtraData<T>,
T: Config,
E: SignedExtra<T>,
T::AccountId: Into<T::Address> + 'static,
<<<T as ExtrinsicExtraData<T>>::Extra as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync + 'static,
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned:
Send + Sync + 'static,
P: Pair + 'static,
P::Signature: Into<T::Signature> + 'static,
{
@@ -115,11 +117,11 @@ where
async fn sign(
&self,
extrinsic: SignedPayload<T>,
) -> Result<UncheckedExtrinsic<T>, String> {
extrinsic: SignedPayload<T, E>,
) -> Result<UncheckedExtrinsic<T, E>, String> {
let signature = extrinsic.using_encoded(|payload| self.signer.sign(payload));
let (call, extra, _) = extrinsic.deconstruct();
let extrinsic = UncheckedExtrinsic::<T>::new_signed(
let extrinsic = UncheckedExtrinsic::<T, E>::new_signed(
call,
self.account_id.clone().into(),
signature.into(),
+2 -1
View File
@@ -78,7 +78,7 @@ pub use crate::{
config::{
AccountData,
Config,
ExtrinsicExtraData,
DefaultConfig,
},
error::{
Error,
@@ -92,6 +92,7 @@ pub use crate::{
},
extrinsic::{
DefaultExtra,
DefaultExtraWithTxPayment,
PairSigner,
SignedExtra,
Signer,
+2 -18
View File
@@ -259,24 +259,8 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::DefaultConfig;
use sp_core::H256;
#[derive(Clone)]
struct MockConfig;
impl Config for MockConfig {
type Index = u32;
type BlockNumber = u32;
type Hash = sp_core::H256;
type Hashing = sp_runtime::traits::BlakeTwo256;
type AccountId = sp_runtime::AccountId32;
type Address = sp_runtime::MultiAddress<Self::AccountId, u32>;
type Header = sp_runtime::generic::Header<
Self::BlockNumber,
sp_runtime::traits::BlakeTwo256,
>;
type Signature = sp_runtime::MultiSignature;
type Extrinsic = sp_runtime::OpaqueExtrinsic;
}
fn named_event(event_name: &str) -> RawEvent {
RawEvent {
@@ -315,7 +299,7 @@ mod tests {
for block_filter in [None, Some(H256::from([1; 32]))] {
for extrinsic_filter in [None, Some(1)] {
for event_filter in [None, Some(("b", "b"))] {
let mut subscription: EventSubscription<MockConfig> =
let mut subscription: EventSubscription<DefaultConfig> =
EventSubscription {
block_reader: BlockReader::Mock(Box::new(
vec![
File diff suppressed because it is too large Load Diff
+10 -12
View File
@@ -19,8 +19,8 @@ use crate::{
balances,
runtime_types,
system,
DefaultConfig,
},
pair_signer,
test_context,
};
use codec::Decode;
@@ -30,20 +30,18 @@ use sp_core::{
};
use sp_keyring::AccountKeyring;
use subxt::{
extrinsic::{
PairSigner,
Signer,
},
DefaultConfig,
Error,
EventSubscription,
PalletError,
RuntimeError,
Signer,
};
#[async_std::test]
async fn tx_basic_transfer() -> Result<(), subxt::Error> {
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let bob = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Bob.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let bob = pair_signer(AccountKeyring::Bob.pair());
let bob_address = bob.account_id().clone().into();
let cxt = test_context().await;
let api = &cxt.api;
@@ -114,7 +112,7 @@ async fn storage_total_issuance() {
#[async_std::test]
async fn storage_balance_lock() -> Result<(), subxt::Error> {
let bob = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Bob.pair());
let bob = pair_signer(AccountKeyring::Bob.pair());
let charlie = AccountKeyring::Charlie.to_account_id();
let cxt = test_context().await;
@@ -155,9 +153,9 @@ async fn storage_balance_lock() -> Result<(), subxt::Error> {
#[async_std::test]
async fn transfer_error() {
env_logger::try_init().ok();
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let alice_addr = alice.account_id().clone().into();
let hans = PairSigner::<DefaultConfig, _>::new(Pair::generate().0);
let hans = pair_signer(Pair::generate().0);
let hans_address = hans.account_id().clone().into();
let cxt = test_context().await;
@@ -198,7 +196,7 @@ async fn transfer_error() {
#[async_std::test]
async fn transfer_subscription() {
env_logger::try_init().ok();
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let bob = AccountKeyring::Bob.to_account_id();
let bob_addr = bob.clone().into();
let cxt = test_context().await;
@@ -230,7 +228,7 @@ async fn transfer_subscription() {
#[async_std::test]
async fn transfer_implicit_subscription() {
env_logger::try_init().ok();
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let bob = AccountKeyring::Bob.to_account_id();
let bob_addr = bob.clone().into();
let cxt = test_context().await;
+7 -3
View File
@@ -24,9 +24,10 @@ use crate::{
storage,
},
system,
DefaultConfig,
DefaultAccountData,
},
test_context,
NodeRuntimeSignedExtra,
TestContext,
};
use sp_core::sr25519::Pair;
@@ -34,6 +35,7 @@ use sp_runtime::MultiAddress;
use subxt::{
Client,
Config,
DefaultConfig,
Error,
PairSigner,
TransactionProgress,
@@ -41,7 +43,7 @@ use subxt::{
struct ContractsTestContext {
cxt: TestContext,
signer: PairSigner<DefaultConfig, Pair>,
signer: PairSigner<DefaultConfig, NodeRuntimeSignedExtra, Pair>,
}
type Hash = <DefaultConfig as Config>::Hash;
@@ -59,7 +61,9 @@ impl ContractsTestContext {
self.cxt.client()
}
fn contracts_tx(&self) -> TransactionApi<DefaultConfig> {
fn contracts_tx(
&self,
) -> TransactionApi<DefaultConfig, NodeRuntimeSignedExtra, DefaultAccountData> {
self.cxt.api.tx().contracts()
}
+12 -18
View File
@@ -21,8 +21,8 @@ use crate::{
ValidatorPrefs,
},
staking,
DefaultConfig,
},
pair_signer,
test_context,
};
use assert_matches::assert_matches;
@@ -32,12 +32,9 @@ use sp_core::{
};
use sp_keyring::AccountKeyring;
use subxt::{
extrinsic::{
PairSigner,
Signer,
},
Error,
RuntimeError,
Signer,
};
/// Helper function to generate a crypto pair from seed
@@ -55,7 +52,7 @@ fn default_validator_prefs() -> ValidatorPrefs {
#[async_std::test]
async fn validate_with_controller_account() {
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let cxt = test_context().await;
cxt.api
.tx()
@@ -71,7 +68,7 @@ async fn validate_with_controller_account() {
#[async_std::test]
async fn validate_not_possible_for_stash_account() -> Result<(), Error> {
let alice_stash = PairSigner::<DefaultConfig, _>::new(get_from_seed("Alice//stash"));
let alice_stash = pair_signer(get_from_seed("Alice//stash"));
let cxt = test_context().await;
let announce_validator = cxt
.api
@@ -91,8 +88,8 @@ async fn validate_not_possible_for_stash_account() -> Result<(), Error> {
#[async_std::test]
async fn nominate_with_controller_account() {
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let bob = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Bob.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let bob = pair_signer(AccountKeyring::Bob.pair());
let cxt = test_context().await;
cxt.api
@@ -109,9 +106,8 @@ async fn nominate_with_controller_account() {
#[async_std::test]
async fn nominate_not_possible_for_stash_account() -> Result<(), Error> {
let alice_stash =
PairSigner::<DefaultConfig, sr25519::Pair>::new(get_from_seed("Alice//stash"));
let bob = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Bob.pair());
let alice_stash = pair_signer(get_from_seed("Alice//stash"));
let bob = pair_signer(AccountKeyring::Bob.pair());
let cxt = test_context().await;
let nomination = cxt
@@ -133,11 +129,9 @@ async fn nominate_not_possible_for_stash_account() -> Result<(), Error> {
#[async_std::test]
async fn chill_works_for_controller_only() -> Result<(), Error> {
let alice_stash =
PairSigner::<DefaultConfig, sr25519::Pair>::new(get_from_seed("Alice//stash"));
let bob_stash =
PairSigner::<DefaultConfig, sr25519::Pair>::new(get_from_seed("Bob//stash"));
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice_stash = pair_signer(get_from_seed("Alice//stash"));
let bob_stash = pair_signer(get_from_seed("Bob//stash"));
let alice = pair_signer(AccountKeyring::Alice.pair());
let cxt = test_context().await;
// this will fail the second time, which is why this is one test, not two
@@ -191,7 +185,7 @@ async fn chill_works_for_controller_only() -> Result<(), Error> {
#[async_std::test]
async fn tx_bond() -> Result<(), Error> {
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let cxt = test_context().await;
let bond = cxt
+3 -4
View File
@@ -18,19 +18,18 @@ use crate::{
node_runtime::{
runtime_types,
sudo,
DefaultConfig,
},
pair_signer,
test_context,
};
use sp_keyring::AccountKeyring;
use subxt::extrinsic::PairSigner;
type Call = runtime_types::node_runtime::Call;
type BalancesCall = runtime_types::pallet_balances::pallet::Call;
#[async_std::test]
async fn test_sudo() -> Result<(), subxt::Error> {
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let bob = AccountKeyring::Bob.to_account_id().into();
let cxt = test_context().await;
@@ -56,7 +55,7 @@ async fn test_sudo() -> Result<(), subxt::Error> {
#[async_std::test]
async fn test_sudo_unchecked_weight() -> Result<(), subxt::Error> {
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let bob = AccountKeyring::Bob.to_account_id().into();
let cxt = test_context().await;
+5 -10
View File
@@ -15,22 +15,17 @@
// along with subxt. If not, see <http://www.gnu.org/licenses/>.
use crate::{
node_runtime::{
system,
DefaultConfig,
},
node_runtime::system,
pair_signer,
test_context,
};
use assert_matches::assert_matches;
use sp_keyring::AccountKeyring;
use subxt::extrinsic::{
PairSigner,
Signer,
};
use subxt::Signer;
#[async_std::test]
async fn storage_account() -> Result<(), subxt::Error> {
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let cxt = test_context().await;
let account_info = cxt
@@ -46,7 +41,7 @@ async fn storage_account() -> Result<(), subxt::Error> {
#[async_std::test]
async fn tx_remark_with_event() -> Result<(), subxt::Error> {
let alice = PairSigner::<DefaultConfig, _>::new(AccountKeyring::Alice.pair());
let alice = pair_signer(AccountKeyring::Alice.pair());
let cxt = test_context().await;
let found_event = cxt
+19 -6
View File
@@ -15,19 +15,26 @@
// along with subxt. If not, see <http://www.gnu.org/licenses/>.
pub use crate::{
node_runtime::{
self,
DefaultConfig,
},
node_runtime,
TestNodeProcess,
};
use sp_core::sr25519::Pair;
use sp_keyring::AccountKeyring;
use subxt::Client;
use subxt::{
extrinsic::ChargeAssetTxPayment,
Client,
DefaultConfig,
DefaultExtraWithTxPayment,
PairSigner,
};
/// substrate node should be installed on the $PATH
const SUBSTRATE_NODE_PATH: &str = "substrate";
pub type NodeRuntimeSignedExtra =
DefaultExtraWithTxPayment<DefaultConfig, ChargeAssetTxPayment<DefaultConfig>>;
pub async fn test_node_process_with(
key: AccountKeyring,
) -> TestNodeProcess<DefaultConfig> {
@@ -53,7 +60,7 @@ pub async fn test_node_process() -> TestNodeProcess<DefaultConfig> {
pub struct TestContext {
pub node_proc: TestNodeProcess<DefaultConfig>,
pub api: node_runtime::RuntimeApi<DefaultConfig>,
pub api: node_runtime::RuntimeApi<DefaultConfig, NodeRuntimeSignedExtra>,
}
impl TestContext {
@@ -68,3 +75,9 @@ pub async fn test_context() -> TestContext {
let api = node_proc.client().clone().to_runtime_api();
TestContext { node_proc, api }
}
pub fn pair_signer(
pair: Pair,
) -> PairSigner<DefaultConfig, NodeRuntimeSignedExtra, Pair> {
PairSigner::new(pair)
}