diff --git a/Cargo.lock b/Cargo.lock index 87ab3282f..c820a2c37 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -84,6 +84,7 @@ dependencies = [ "serde_json", "sp-application-crypto", "sp-core", + "sp-core-hashing", "sp-keyring", "sp-runtime", "sp-runtime-interface", diff --git a/examples/examples/benchmark_bulk_xt.rs b/examples/examples/benchmark_bulk_xt.rs index 75401b951..39f15cad5 100644 --- a/examples/examples/benchmark_bulk_xt.rs +++ b/examples/examples/benchmark_bulk_xt.rs @@ -18,21 +18,23 @@ // run this against test node with // > substrate-test-node --dev --execution native --ws-port 9979 -ltxpool=debug -use kitchensink_runtime::{AccountId, BalancesCall, Runtime, RuntimeCall, Signature}; -use sp_core::sr25519::Pair; +use kitchensink_runtime::{AccountId, BalancesCall, RuntimeCall}; use sp_keyring::AccountKeyring; use substrate_api_client::{ ac_primitives::{ - AssetTipExtrinsicParams, ExtrinsicSigner as GenericExtrinsicSigner, SignExtrinsic, + ExtrinsicSigner as GenericExtrinsicSigner, SignExtrinsic, SubstrateKitchensinkConfig, }, rpc::JsonrpseeClient, Api, SubmitExtrinsic, }; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + // Define an extrinsic signer type which sets the generic types of the `GenericExtrinsicSigner`. // This way, the types don't have to be reassigned with every usage of this type and makes // the code better readable. -type ExtrinsicSigner = GenericExtrinsicSigner; +type ExtrinsicSigner = GenericExtrinsicSigner; // To access the ExtrinsicAddress type of the Signer, we need to do this via the trait `SignExtrinsic`. // For better code readability, we define a simple type here and, at the same time, assign the @@ -46,9 +48,7 @@ async fn main() { // Initialize api and set the signer (sender) that is used to sign the extrinsics. let signer = AccountKeyring::Alice.pair(); let client = JsonrpseeClient::with_default_url().unwrap(); - // ! Careful: AssetTipExtrinsicParams is used here, because the substrate kitchensink runtime uses assets as tips. But for most - // runtimes, the PlainTipExtrinsicParams needs to be used. - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); + let mut api = Api::::new(client).unwrap(); api.set_signer(ExtrinsicSigner::new(signer)); let recipient: ExtrinsicAddressOf = AccountKeyring::Bob.to_account_id().into(); diff --git a/examples/examples/compose_extrinsic_offline.rs b/examples/examples/compose_extrinsic_offline.rs index 18e1cd18d..1390f59c0 100644 --- a/examples/examples/compose_extrinsic_offline.rs +++ b/examples/examples/compose_extrinsic_offline.rs @@ -16,15 +16,18 @@ //! This example shows how to use the compose_extrinsic_offline macro which generates an extrinsic //! without asking the node for nonce and does not need to know the metadata -use kitchensink_runtime::{BalancesCall, Runtime, RuntimeCall, Signature}; +use kitchensink_runtime::{BalancesCall, RuntimeCall}; use sp_keyring::AccountKeyring; use sp_runtime::{generic::Era, MultiAddress}; use substrate_api_client::{ - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner, GenericAdditionalParams}, + ac_primitives::{ExtrinsicSigner, GenericAdditionalParams, SubstrateKitchensinkConfig}, rpc::JsonrpseeClient, Api, GetChainInfo, SubmitAndWatch, XtStatus, }; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + #[tokio::main] async fn main() { env_logger::init(); @@ -35,11 +38,8 @@ async fn main() { // Api::new(..) is not actually an offline call, but retrieves metadata and other information from the node. // If this is not acceptable, use the Api::new_offline(..) function instead. There are no examples for this, // because of the constantly changing substrate node. But check out our unit tests - there are Apis created with `new_offline`. - // - // ! Careful: AssetTipExtrinsicParams is used here, because the substrate kitchensink runtime uses assets as tips. But for most - // runtimes, the PlainTipExtrinsicParams needs to be used. - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(signer)); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::::new(signer)); // Information for Era for mortal transactions (online). let last_finalized_header_hash = api.get_finalized_head().unwrap().unwrap(); diff --git a/examples/examples/contract_instantiate_with_code.rs b/examples/examples/contract_instantiate_with_code.rs index 456078afc..1a92ffd5d 100644 --- a/examples/examples/contract_instantiate_with_code.rs +++ b/examples/examples/contract_instantiate_with_code.rs @@ -16,16 +16,17 @@ //! This example is community maintained and not CI tested, therefore it may not work as is. use codec::Decode; -use kitchensink_runtime::{AccountId, Runtime, Signature}; +use kitchensink_runtime::AccountId; use sp_keyring::AccountKeyring; use substrate_api_client::{ - ac_node_api::StaticEvent, - ac_primitives::{ExtrinsicSigner, PlainTipExtrinsicParams}, - extrinsic::ContractsExtrinsics, - rpc::JsonrpseeClient, - Api, SubmitAndWatch, SubmitAndWatchUntilSuccess, XtStatus, + ac_compose_macros::primitives::SubstrateKitchensinkConfig, ac_node_api::StaticEvent, + ac_primitives::ExtrinsicSigner, extrinsic::ContractsExtrinsics, rpc::JsonrpseeClient, Api, + SubmitAndWatch, SubmitAndWatchUntilSuccess, XtStatus, }; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + #[allow(unused)] #[derive(Decode)] struct ContractInstantiatedEventArgs { @@ -45,10 +46,8 @@ async fn main() { // Initialize api and set the signer (sender) that is used to sign the extrinsics. let signer = AccountKeyring::Alice.pair(); let client = JsonrpseeClient::with_default_url().unwrap(); - // ! Careful: AssetTipExtrinsicParams is used here, because the substrate kitchensink runtime uses assets as tips. But for most - // runtimes, the PlainTipExtrinsicParams needs to be used. - let mut api = Api::<_, _, PlainTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(signer)); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::<_>::new(signer)); println!("[+] Alice's Account Nonce is {}", api.get_nonce().unwrap()); diff --git a/examples/examples/custom_nonce.rs b/examples/examples/custom_nonce.rs index 4096e684c..d530f43ca 100644 --- a/examples/examples/custom_nonce.rs +++ b/examples/examples/custom_nonce.rs @@ -16,15 +16,18 @@ //! This example shows how to use the compose_extrinsic_offline macro which generates an extrinsic //! without asking the node for nonce and does not need to know the metadata -use kitchensink_runtime::{BalancesCall, Runtime, RuntimeCall, Signature}; +use kitchensink_runtime::{BalancesCall, RuntimeCall}; use sp_keyring::AccountKeyring; use sp_runtime::{generic::Era, MultiAddress}; use substrate_api_client::{ - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner, GenericAdditionalParams}, + ac_primitives::{ExtrinsicSigner, GenericAdditionalParams, SubstrateKitchensinkConfig}, rpc::JsonrpseeClient, Api, Error, GetChainInfo, SubmitAndWatch, UnexpectedTxStatus, XtStatus, }; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig. +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + #[tokio::main] async fn main() { env_logger::init(); @@ -32,10 +35,8 @@ async fn main() { // Initialize api and set the signer (sender) that is used to sign the extrinsics. let signer = AccountKeyring::Alice.pair(); let client = JsonrpseeClient::with_default_url().unwrap(); - // ! Careful: AssetTipExtrinsicParams is used here, because the substrate kitchensink runtime uses assets as tips. But for most - // runtimes, the PlainTipExtrinsicParams needs to be used. - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(signer)); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::::new(signer)); // Information for Era for mortal transactions. let last_finalized_header_hash = api.get_finalized_head().unwrap().unwrap(); diff --git a/examples/examples/event_callback.rs b/examples/examples/event_callback.rs index 10b0e166c..4121b9e68 100644 --- a/examples/examples/event_callback.rs +++ b/examples/examples/event_callback.rs @@ -19,12 +19,15 @@ use log::debug; use sp_core::H256 as Hash; use substrate_api_client::{ - ac_primitives::PlainTipExtrinsicParams, rpc::JsonrpseeClient, Api, SubscribeEvents, + ac_primitives::SubstrateKitchensinkConfig, rpc::JsonrpseeClient, Api, SubscribeEvents, }; // This module depends on the specific node runtime. // Replace this crate by your own if you run a custom substrate node to get your custom events. -use kitchensink_runtime::{Runtime, RuntimeEvent}; +use kitchensink_runtime::RuntimeEvent; + +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. #[tokio::main] async fn main() { @@ -32,7 +35,7 @@ async fn main() { // Initialize the api. let client = JsonrpseeClient::with_default_url().unwrap(); - let api = Api::<(), _, PlainTipExtrinsicParams, Runtime>::new(client).unwrap(); + let api = Api::::new(client).unwrap(); println!("Subscribe to events"); let mut subscription = api.subscribe_events().unwrap(); diff --git a/examples/examples/event_error_details.rs b/examples/examples/event_error_details.rs index e32181c14..1bf20734a 100644 --- a/examples/examples/event_error_details.rs +++ b/examples/examples/event_error_details.rs @@ -14,17 +14,19 @@ */ use codec::Decode; -use kitchensink_runtime::{Runtime, Signature}; use sp_keyring::AccountKeyring; use sp_runtime::{AccountId32 as AccountId, MultiAddress}; use substrate_api_client::{ ac_node_api::StaticEvent, - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner}, + ac_primitives::{ExtrinsicSigner, SubstrateKitchensinkConfig}, extrinsic::BalancesExtrinsics, rpc::JsonrpseeClient, Api, GetAccountInformation, SubmitAndWatchUntilSuccess, }; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + #[derive(Decode)] struct TransferEventArgs { _from: AccountId, @@ -44,10 +46,8 @@ async fn main() { // Initialize api and set the signer (sender) that is used to sign the extrinsics. let alice_signer = AccountKeyring::Alice.pair(); let client = JsonrpseeClient::with_default_url().unwrap(); - // ! Careful: AssetTipExtrinsicParams is used here, because the substrate kitchensink runtime uses assets as tips. But for most - // runtimes, the PlainTipExtrinsicParams needs to be used. - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(alice_signer)); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::::new(alice_signer)); let alice = AccountKeyring::Alice.to_account_id(); let balance_of_alice = api.get_account_data(&alice).unwrap().unwrap().free; diff --git a/examples/examples/get_account_identity.rs b/examples/examples/get_account_identity.rs index 8788bb403..0e1e0b4d0 100644 --- a/examples/examples/get_account_identity.rs +++ b/examples/examples/get_account_identity.rs @@ -16,13 +16,13 @@ //! Example to show how to get the account identity display name from the identity pallet. use frame_support::traits::Currency; -use kitchensink_runtime::{Runtime as KitchensinkRuntime, Signature}; +use kitchensink_runtime::Runtime as KitchensinkRuntime; use pallet_identity::{Data, IdentityInfo, Registration}; use sp_core::{crypto::Pair, H256}; use sp_keyring::AccountKeyring; use substrate_api_client::{ ac_compose_macros::compose_extrinsic, - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner, UncheckedExtrinsicV4}, + ac_primitives::{ExtrinsicSigner, SubstrateKitchensinkConfig, UncheckedExtrinsicV4}, rpc::JsonrpseeClient, Api, GetStorage, SubmitAndWatch, XtStatus, }; @@ -33,6 +33,9 @@ type BalanceOf = <::Currency as Currency< type MaxRegistrarsOf = ::MaxRegistrars; type MaxAdditionalFieldsOf = ::MaxAdditionalFields; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + #[tokio::main] async fn main() { env_logger::init(); @@ -40,12 +43,8 @@ async fn main() { // Create the node-api client and set the signer. let client = JsonrpseeClient::with_default_url().unwrap(); let signer = AccountKeyring::Alice.pair(); - // ! Careful: AssetTipExtrinsicParams is used here, because the substrate kitchensink runtime uses assets as tips. But for most - // runtimes, the PlainTipExtrinsicParams needs to be used. - let mut api = - Api::<_, _, AssetTipExtrinsicParams, KitchensinkRuntime>::new(client) - .unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, KitchensinkRuntime>::new(signer.clone())); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::::new(signer.clone())); // Fill Identity storage. let info = IdentityInfo::> { diff --git a/examples/examples/get_blocks_async.rs b/examples/examples/get_blocks_async.rs index e08769455..6ce367204 100644 --- a/examples/examples/get_blocks_async.rs +++ b/examples/examples/get_blocks_async.rs @@ -16,10 +16,8 @@ //! Very simple example that shows how to fetch chain information with async. //! To compile this example for async you need to set the `--no-default-features` flag -use kitchensink_runtime::Runtime; -use sp_core::sr25519; use substrate_api_client::{ - ac_primitives::PlainTipExtrinsicParams, + ac_primitives::SubstrateKitchensinkConfig, rpc::{HandleSubscription, JsonrpseeClient}, Api, GetChainInfo, SubscribeChain, }; @@ -31,6 +29,9 @@ async fn main() { println!("Please compile this example with `--no-default-features` for it to run properly.") } +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + #[cfg(not(feature = "sync-examples"))] #[tokio::main] async fn main() { @@ -38,9 +39,7 @@ async fn main() { // Initialize the api. let client = JsonrpseeClient::with_default_url().unwrap(); - let api = Api::, Runtime>::new(client) - .await - .unwrap(); + let api = Api::::new(client).await.unwrap(); let (genesis_block, header_hash, signed_block) = futures::future::try_join3( api.get_genesis_block(), diff --git a/examples/examples/get_storage.rs b/examples/examples/get_storage.rs index fd2a4447b..e163f09c8 100644 --- a/examples/examples/get_storage.rs +++ b/examples/examples/get_storage.rs @@ -16,18 +16,20 @@ //! Very simple example that shows how to get some simple storage values. use frame_system::AccountInfo as GenericAccountInfo; -use kitchensink_runtime::{Runtime, Signature}; use sp_keyring::AccountKeyring; use substrate_api_client::{ - ac_primitives::{ExtrinsicSigner, PlainTipExtrinsicParams}, + ac_primitives::{Config, ExtrinsicSigner, SubstrateKitchensinkConfig}, rpc::JsonrpseeClient, Api, GetAccountInformation, GetStorage, }; -type IndexFor = ::Index; -type AccountDataFor = ::AccountData; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. -type AccountInfo = GenericAccountInfo, AccountDataFor>; +type AccountInfo = GenericAccountInfo< + ::Index, + ::AccountData, +>; #[tokio::main] async fn main() { @@ -35,7 +37,7 @@ async fn main() { // Initialize the api. let client = JsonrpseeClient::with_default_url().unwrap(); - let mut api = Api::<_, _, PlainTipExtrinsicParams, Runtime>::new(client).unwrap(); + let mut api = Api::::new(client).unwrap(); // get some plain storage value let result: u128 = api.get_storage("Balances", "TotalIssuance", None).unwrap().unwrap(); @@ -58,7 +60,7 @@ async fn main() { // get Alice's AccountNonce with api.get_nonce() let signer = AccountKeyring::Alice.pair(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(signer)); + api.set_signer(ExtrinsicSigner::<_>::new(signer)); println!("[+] Alice's Account Nonce is {}", api.get_nonce().unwrap()); println!( diff --git a/examples/examples/print_metadata.rs b/examples/examples/print_metadata.rs index 0228a5e62..b785aa617 100644 --- a/examples/examples/print_metadata.rs +++ b/examples/examples/print_metadata.rs @@ -16,9 +16,10 @@ //! Very simple example that shows how to pretty print the metadata. Has proven to be a helpful //! debugging tool. -use kitchensink_runtime::Runtime; -use sp_core::sr25519; -use substrate_api_client::{ac_primitives::PlainTipExtrinsicParams, rpc::JsonrpseeClient, Api}; +use substrate_api_client::{ac_primitives::SubstrateKitchensinkConfig, rpc::JsonrpseeClient, Api}; + +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. #[tokio::main] async fn main() { @@ -26,8 +27,7 @@ async fn main() { // Initialize the api, which retrieves the metadata from the node upon initialization. let client = JsonrpseeClient::with_default_url().unwrap(); - let mut api = - Api::, Runtime>::new(client).unwrap(); + let mut api = Api::::new(client).unwrap(); let meta = api.metadata().clone(); diff --git a/examples/examples/staking_batch_payout.rs b/examples/examples/staking_batch_payout.rs index e9fe549eb..f1621f669 100644 --- a/examples/examples/staking_batch_payout.rs +++ b/examples/examples/staking_batch_payout.rs @@ -12,12 +12,11 @@ */ use codec::{Decode, Encode}; -use kitchensink_runtime::{Runtime, Signature}; use pallet_staking::{ActiveEraInfo, Exposure}; use sp_keyring::AccountKeyring; use sp_runtime::{app_crypto::Ss58Codec, AccountId32}; use substrate_api_client::{ - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner}, + ac_primitives::{ExtrinsicSigner, SubstrateKitchensinkConfig}, extrinsic::{StakingExtrinsics, UtilityExtrinsics}, rpc::JsonrpseeClient, Api, GetStorage, SubmitAndWatch, SubmitAndWatchUntilSuccess, XtStatus, @@ -25,6 +24,9 @@ use substrate_api_client::{ const MAX_BATCHED_TRANSACTION: u32 = 9; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + pub type EraIndex = u32; pub struct GracePeriod { @@ -50,8 +52,8 @@ async fn main() { // Initialize api and set the signer (sender) that is used to sign the extrinsics. let alice = AccountKeyring::Alice.pair(); let client = JsonrpseeClient::with_default_url().unwrap(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(alice)); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::::new(alice)); // Give a valid validator account address. In the kitchinsink runtime, this is Alice. let validator_account = AccountKeyring::Alice.to_account_id(); @@ -139,12 +141,7 @@ async fn main() { pub fn get_last_reward_received_for( account: &AccountId32, current_era: EraIndex, - api: &substrate_api_client::Api< - ExtrinsicSigner, - JsonrpseeClient, - AssetTipExtrinsicParams, - Runtime, - >, + api: &substrate_api_client::Api, ) -> Option { let ledger_storage_key = api.metadata().storage_map_key("Staking", "Ledger", account).unwrap(); diff --git a/examples/examples/sudo.rs b/examples/examples/sudo.rs index 027264cbf..1f07336f7 100644 --- a/examples/examples/sudo.rs +++ b/examples/examples/sudo.rs @@ -17,23 +17,25 @@ //! module, whereas the desired module and call are supplied as a string. use codec::Compact; -use kitchensink_runtime::{AccountId, Runtime, Signature}; -use sp_core::sr25519::Pair; +use kitchensink_runtime::AccountId; use sp_keyring::AccountKeyring; use substrate_api_client::{ ac_compose_macros::{compose_call, compose_extrinsic}, ac_primitives::{ - AssetTipExtrinsicParams, ExtrinsicSigner as GenericExtrinsicSigner, SignExtrinsic, + ExtrinsicSigner as GenericExtrinsicSigner, SignExtrinsic, SubstrateKitchensinkConfig, UncheckedExtrinsicV4, }, rpc::JsonrpseeClient, Api, GetAccountInformation, SubmitAndWatch, XtStatus, }; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + // Define an extrinsic signer type which sets the generic types of the `GenericExtrinsicSigner`. // This way, the types don't have to be reassigned with every usage of this type and makes // the code better readable. -type ExtrinsicSigner = GenericExtrinsicSigner; +type ExtrinsicSigner = GenericExtrinsicSigner; // To access the ExtrinsicAddress type of the Signer, we need to do this via the trait `SignExtrinsic`. // For better code readability, we define a simple type here and, at the same time, assign the @@ -47,7 +49,7 @@ async fn main() { // Initialize api and set the signer (sender) that is used to sign the extrinsics. let sudoer = AccountKeyring::Alice.pair(); let client = JsonrpseeClient::with_default_url().unwrap(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); + let mut api = Api::::new(client).unwrap(); api.set_signer(ExtrinsicSigner::new(sudoer)); // Set the recipient of newly issued funds. diff --git a/examples/examples/transfer_with_tungstenite_client.rs b/examples/examples/transfer_with_tungstenite_client.rs index 706511a17..8d2fffbdd 100755 --- a/examples/examples/transfer_with_tungstenite_client.rs +++ b/examples/examples/transfer_with_tungstenite_client.rs @@ -15,19 +15,21 @@ //! Very simple example that shows how to use a predefined extrinsic from the extrinsic module. -use kitchensink_runtime::{Runtime, Signature}; use sp_core::{ crypto::{Pair, Ss58Codec}, sr25519, }; use sp_runtime::MultiAddress; use substrate_api_client::{ - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner}, + ac_primitives::{ExtrinsicSigner, SubstrateKitchensinkConfig}, extrinsic::BalancesExtrinsics, rpc::TungsteniteRpcClient, Api, GetAccountInformation, SubmitAndWatch, XtStatus, }; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + fn main() { env_logger::init(); @@ -41,8 +43,8 @@ fn main() { // Initialize api and set the signer (sender) that is used to sign the extrinsics. let client = TungsteniteRpcClient::with_default_url(100); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(alice.clone())); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::::new(alice.clone())); // Retrieve bobs current balance. let bob = sr25519::Public::from_ss58check("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty") diff --git a/examples/examples/transfer_with_ws_client.rs b/examples/examples/transfer_with_ws_client.rs index f2a291b97..5e96ca50a 100755 --- a/examples/examples/transfer_with_ws_client.rs +++ b/examples/examples/transfer_with_ws_client.rs @@ -15,19 +15,21 @@ //! Very simple example that shows how to use a predefined extrinsic from the extrinsic module. -use kitchensink_runtime::{Runtime, Signature}; use sp_core::{ crypto::{Pair, Ss58Codec}, sr25519, }; use sp_runtime::MultiAddress; use substrate_api_client::{ - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner}, + ac_primitives::{ExtrinsicSigner, SubstrateKitchensinkConfig}, extrinsic::BalancesExtrinsics, rpc::WsRpcClient, Api, GetAccountInformation, SubmitAndWatch, XtStatus, }; +// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the SubstrateKitchensinkConfig +// ! Careful: Most runtimes uses plain as tips, they need a polkadot config. + fn main() { env_logger::init(); @@ -41,8 +43,8 @@ fn main() { // Initialize api and set the signer (sender) that is used to sign the extrinsics. let client = WsRpcClient::with_default_url(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(alice.clone())); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::::new(alice.clone())); // Retrieve bobs current balance. let bob = sr25519::Public::from_ss58check("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty") diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 586278cdc..a05407915 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -20,6 +20,7 @@ serde_json = { version = "1.0", default-features = false, features = ["alloc"] } # substrate no_std sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "master" } +sp-core-hashing = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "master" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "master" } sp-runtime-interface = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "master" } sp-staking = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "master" } @@ -53,6 +54,7 @@ std = [ "serde_json/std", # substrate no_std "sp-core/std", + "sp-core-hashing/std", "sp-runtime/std", "sp-staking/std", "sp-version/std", diff --git a/primitives/src/config/mod.rs b/primitives/src/config/mod.rs new file mode 100644 index 000000000..0a959bf3e --- /dev/null +++ b/primitives/src/config/mod.rs @@ -0,0 +1,165 @@ +// This file was taken from subxt (Parity Technologies (UK)) +// https://github.com/paritytech/subxt/ +// And was adapted by Supercomputing Systems AG and Integritee AG. +// +// Copyright 2019-2022 Parity Technologies (UK) Ltd, Supercomputing Systems AG and Integritee AG. +// This file is licensed as Apache-2.0 +// see LICENSE for license details. + +//! The config used by the API. +//! +//! This file is mostly subxt: +//! https://github.com/paritytech/subxt/blob/ce0a82e3227efb0eae131f025da5f839d9623e15/subxt/src/config/mod.rs + +use core::{fmt::Debug, marker::PhantomData}; + +use codec::{Decode, Encode, FullCodec}; +use serde::{de::DeserializeOwned, Serialize}; +use sp_core::Pair; +use sp_runtime::traits::{AtLeast32Bit, AtLeast32BitUnsigned, MaybeSerializeDeserialize}; + +use crate::{extrinsic_params, Block, Hasher, Header, SignExtrinsic}; + +pub use polkadot::*; +pub use substrate_kitchensink::*; + +pub mod polkadot; +pub mod substrate_kitchensink; + +/// Runtime types. +pub trait Config { + /// Account index (aka nonce) type. This stores the number of previous + /// transactions associated with a sender account. + /// This type enforces the (de)serialization implementation + /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). + type Index: Debug + Copy + DeserializeOwned + AtLeast32Bit + Decode; + + /// The block number type used by the runtime. + type BlockNumber: Debug + + Copy + + Encode + + Default + + Serialize + + DeserializeOwned + + core::hash::Hash + + core::str::FromStr + + Into; + + /// The output of the `Hashing` function. + type Hash: Debug + + Copy + + Send + + Sync + + Decode + + Default + + AsRef<[u8]> + + Serialize + + DeserializeOwned + + Encode + + PartialEq; + + /// The account ID type. + type AccountId: Debug + + Clone + + Encode + + MaybeSerializeDeserialize + + From<::Public>; + + /// The address type. + type Address: Debug + Clone + Encode + From; //type Lookup: StaticLookup; + + /// The signature type. + type Signature: Debug + Encode + From<::Signature>; + + /// The hashing system (algorithm) being used in the runtime (e.g. Blake2). + type Hasher: Debug + Hasher; + + /// The block header. + type Header: Debug + + Header + + Send + + DeserializeOwned; + + /// The account data. + type AccountData: Debug + Clone + FullCodec; + + /// This type defines the extrinsic extra and additional parameters. + type ExtrinsicParams: extrinsic_params::ExtrinsicParams; + + /// The cryptographic PKI key pair type used to sign the extrinsic + type CryptoKey: Pair; + + /// This extrinsic signer. + type ExtrinsicSigner: SignExtrinsic; + + /// The block type. + type Block: Block + DeserializeOwned; + + /// The balance type. + type Balance: Debug + + Decode + + Encode + + AtLeast32BitUnsigned + + Default + + Copy + + Serialize + + DeserializeOwned; + + /// The currency type of the contract pallet. + type ContractCurrency: Debug + + Decode + + Encode + + AtLeast32BitUnsigned + + Default + + Copy + + Serialize + + DeserializeOwned; + + /// The balance type of the staking pallet. + type StakingBalance: Debug + + Decode + + Encode + + AtLeast32BitUnsigned + + Default + + Copy + + Serialize + + DeserializeOwned; +} + +/// Take a type implementing [`Config`] (eg [`SubstrateConfig`]), and some type which describes the +/// additional and extra parameters to pass to an extrinsic (see [`ExtrinsicParams`]), +/// and returns a type implementing [`Config`] with those new [`ExtrinsicParams`]. +/// +/// # Example +/// +/// ``` +/// use ac_primitives::{ SubstrateKitchensinkConfig, WithExtrinsicParams, PlainTipExtrinsicParams }; +/// +/// // This is how PolkadotConfig is implemented: +/// type PolkadotConfig = WithExtrinsicParams>; +/// ``` +#[derive(Decode, Encode, Clone, Eq, PartialEq, Debug)] +pub struct WithExtrinsicParams> { + _marker: PhantomData<(T, E)>, +} + +impl> Config + for WithExtrinsicParams +{ + type Index = T::Index; + type BlockNumber = T::BlockNumber; + type Hash = T::Hash; + type AccountId = T::AccountId; + type Address = T::Address; + type Signature = T::Signature; + type Hasher = T::Hasher; + type Header = T::Header; + type AccountData = T::AccountData; + type ExtrinsicParams = E; + type CryptoKey = T::CryptoKey; + type ExtrinsicSigner = T::ExtrinsicSigner; + type Block = T::Block; + type Balance = T::Balance; + type ContractCurrency = T::ContractCurrency; + type StakingBalance = T::StakingBalance; +} diff --git a/primitives/src/config/polkadot.rs b/primitives/src/config/polkadot.rs new file mode 100644 index 000000000..40fd47007 --- /dev/null +++ b/primitives/src/config/polkadot.rs @@ -0,0 +1,23 @@ +// Copyright 2019-2022 Parity Technologies (UK) Ltd. +// This file is dual-licensed as Apache-2.0 or GPL-3.0. +// see LICENSE for license details. + +//! Polkadot specific configuration +//! +//! This file is mostly subxt. +//! https://github.com/paritytech/subxt/blob/ce0a82e3227efb0eae131f025da5f839d9623e15/subxt/src/config/polkadot.rs + +use crate::{ + config::WithExtrinsicParams, Config, GenericExtrinsicParams, PlainTip, + SubstrateKitchensinkConfig, +}; + +/// Default set of commonly used types by Polkadot nodes. +pub type PolkadotConfig = WithExtrinsicParams< + SubstrateKitchensinkConfig, + PlainTipExtrinsicParams, +>; + +/// A struct representing the signed extra and additional parameters required +/// to construct a transaction and pay in token fees. +pub type PlainTipExtrinsicParams = GenericExtrinsicParams::Balance>>; diff --git a/primitives/src/config/substrate_kitchensink.rs b/primitives/src/config/substrate_kitchensink.rs new file mode 100644 index 000000000..f326fe14c --- /dev/null +++ b/primitives/src/config/substrate_kitchensink.rs @@ -0,0 +1,45 @@ +// Copyright 2019-2022 Parity Technologies (UK) Ltd. +// This file is dual-licensed as Apache-2.0 or GPL-3.0. +// see LICENSE for license details. + +//! Substrate specific configuration +//! +//! This file is mostly subxt. +//! https://github.com/paritytech/subxt/blob/ce0a82e3227efb0eae131f025da5f839d9623e15/subxt/src/config/substrate.rs + +use crate::{ + config::Config, types::AccountData, AssetTip, BlakeTwo256, ExtrinsicSigner, + GenericExtrinsicParams, SubstrateBlock, SubstrateHeader, SubstrateOpaqueExtrinsic, +}; +use codec::{Decode, Encode}; +use core::fmt::Debug; +pub use primitive_types::{H256, U256}; +use sp_core::sr25519; +use sp_runtime::{AccountId32, MultiAddress, MultiSignature}; + +/// Default set of commonly used types by Substrate kitchensink runtime. +#[derive(Decode, Encode, Clone, Eq, PartialEq, Debug)] +pub struct SubstrateKitchensinkConfig {} + +impl Config for SubstrateKitchensinkConfig { + type Index = u32; + type BlockNumber = u32; + type Hash = H256; + type AccountId = AccountId32; + type Address = MultiAddress; + type Signature = MultiSignature; + type Hasher = BlakeTwo256; + type Header = SubstrateHeader; + type AccountData = AccountData; + type ExtrinsicParams = AssetTipExtrinsicParams; + type CryptoKey = sr25519::Pair; + type ExtrinsicSigner = ExtrinsicSigner; + type Block = SubstrateBlock; + type Balance = u128; + type ContractCurrency = u128; + type StakingBalance = u128; +} + +/// A struct representing the signed extra and additional parameters required +/// to construct a transaction and pay in asset fees. +pub type AssetTipExtrinsicParams = GenericExtrinsicParams::Balance>>; diff --git a/primitives/src/extrinsics/extrinsic_params.rs b/primitives/src/extrinsics/extrinsic_params.rs index e043b8410..ea743637d 100644 --- a/primitives/src/extrinsics/extrinsic_params.rs +++ b/primitives/src/extrinsics/extrinsic_params.rs @@ -15,28 +15,13 @@ */ +use crate::config::Config; use codec::{Decode, Encode}; -use core::hash::Hash as HashTrait; use sp_runtime::{ generic::Era, traits::{BlakeTwo256, Hash}, }; -pub type BalanceFor = ::Balance; -pub type AssetBalanceFor = ::Balance; -pub type HashFor = ::Hash; -pub type IndexFor = ::Index; - -/// A struct representing the signed extra and additional parameters required -/// to construct a transaction and pay in asset fees. -pub type AssetTipExtrinsicParams = - GenericExtrinsicParams>, IndexFor, HashFor>; - -/// A struct representing the signed extra and additional parameters required -/// to construct a transaction and pay in token fees. -pub type PlainTipExtrinsicParams = - GenericExtrinsicParams>, IndexFor, HashFor>; - /// SignedExtra that is compatible with a default Substrate / Polkadot node. // Unlike the SignedExtra on the node side, which seemingly contains a lot more parameters // see: https://github.com/paritytech/substrate/blob/cbd8f1b56fd8ab9af0d9317432cc735264c89d70/bin/node/runtime/src/lib.rs#L1779-L1788 @@ -111,14 +96,14 @@ pub trait ExtrinsicParams { /// extrinsics that can be sent to a node with the same signed extra and additional /// parameters as a Polkadot/Substrate node. #[derive(Decode, Encode, Clone, Eq, PartialEq, Debug)] -pub struct GenericExtrinsicParams { +pub struct GenericExtrinsicParams { era: Era, - nonce: Index, + nonce: T::Index, tip: Tip, spec_version: u32, transaction_version: u32, - genesis_hash: Hash, - mortality_checkpoint: Hash, + genesis_hash: T::Hash, + mortality_checkpoint: T::Hash, } /// Representation of the default Substrate / Polkadot node additional params, @@ -161,23 +146,21 @@ impl Default for GenericAdditionalParams { } } -impl ExtrinsicParams for GenericExtrinsicParams +impl ExtrinsicParams for GenericExtrinsicParams where + T: Config, u128: From, Tip: Copy + Default + Encode, - Index: Copy + Default + Encode, - Hash: HashTrait + Encode + Copy, - GenericSignedExtra: Encode, { - type AdditionalParams = GenericAdditionalParams; - type SignedExtra = GenericSignedExtra; - type AdditionalSigned = GenericAdditionalSigned; + type AdditionalParams = GenericAdditionalParams; + type SignedExtra = GenericSignedExtra; + type AdditionalSigned = GenericAdditionalSigned; fn new( spec_version: u32, transaction_version: u32, - nonce: Index, - genesis_hash: Hash, + nonce: T::Index, + genesis_hash: T::Hash, additional_params: Self::AdditionalParams, ) -> Self { GenericExtrinsicParams { diff --git a/primitives/src/extrinsics/mod.rs b/primitives/src/extrinsics/mod.rs index 9cd28d2b6..bf59dfc27 100644 --- a/primitives/src/extrinsics/mod.rs +++ b/primitives/src/extrinsics/mod.rs @@ -17,14 +17,14 @@ //! Primitives for substrate extrinsics. -use alloc::vec::Vec; +use alloc::{format, vec::Vec}; use codec::{Decode, Encode, Error, Input}; use core::fmt; +use sp_runtime::traits::Extrinsic; pub use extrinsic_params::{ - AssetTip, AssetTipExtrinsicParams, ExtrinsicParams, GenericAdditionalParams, - GenericAdditionalSigned, GenericExtrinsicParams, GenericSignedExtra, PlainTip, - PlainTipExtrinsicParams, SignedPayload, + AssetTip, ExtrinsicParams, GenericAdditionalParams, GenericAdditionalSigned, + GenericExtrinsicParams, GenericSignedExtra, PlainTip, SignedPayload, }; pub use signer::{ExtrinsicSigner, SignExtrinsic}; @@ -65,6 +65,26 @@ impl } } +impl Extrinsic + for UncheckedExtrinsicV4 +{ + type Call = Call; + + type SignaturePayload = (Address, Signature, SignedExtra); + + fn is_signed(&self) -> Option { + Some(self.signature.is_some()) + } + + fn new(function: Call, signed_data: Option) -> Option { + Some(if let Some((address, signature, extra)) = signed_data { + Self::new_signed(function, address, signature, extra) + } else { + Self::new_unsigned(function) + }) + } +} + impl fmt::Debug for UncheckedExtrinsicV4 where @@ -137,6 +157,40 @@ where } } +impl serde::Serialize + for UncheckedExtrinsicV4 +where + Address: Encode, + Signature: Encode, + Call: Encode, + SignedExtra: Encode, +{ + fn serialize(&self, seq: S) -> Result + where + S: ::serde::Serializer, + { + self.using_encoded(|bytes| impl_serde::serialize::serialize(bytes, seq)) + } +} + +impl<'a, Address, Call, Signature, SignedExtra> serde::Deserialize<'a> + for UncheckedExtrinsicV4 +where + Address: Decode, + Signature: Decode, + Call: Decode, + SignedExtra: Decode, +{ + fn deserialize(de: D) -> Result + where + D: serde::Deserializer<'a>, + { + let r = impl_serde::serialize::deserialize(de)?; + Decode::decode(&mut &r[..]) + .map_err(|e| serde::de::Error::custom(format!("Decode error: {e}"))) + } +} + /// Same function as in primitives::generic. Needed to be copied as it is private there. fn encode_with_vec_prefix)>(encoder: F) -> Vec { let size = core::mem::size_of::(); @@ -163,11 +217,11 @@ fn encode_with_vec_prefix)>(encoder: F) -> Vec #[cfg(test)] mod tests { use super::*; - use extrinsic_params::{ - ExtrinsicParams, GenericAdditionalParams, GenericExtrinsicParams, PlainTip, - }; - use sp_core::{Pair, H256 as Hash}; - use sp_runtime::{generic::Era, testing::sr25519, AccountId32, MultiSignature}; + use crate::SubstrateKitchensinkConfig; + use extrinsic_params::{GenericAdditionalParams, GenericExtrinsicParams, PlainTip}; + use node_template_runtime::{BalancesCall, RuntimeCall, SignedExtra}; + use sp_core::{crypto::Ss58Codec, Pair, H256 as Hash}; + use sp_runtime::{generic::Era, testing::sr25519, AccountId32, MultiAddress, MultiSignature}; #[test] fn encode_decode_roundtrip_works() { @@ -180,7 +234,13 @@ mod tests { .era(Era::mortal(8, 0), Hash::from([0u8; 32])); let default_extra = - GenericExtrinsicParams::new(0, 0, 0u32, Hash::from([0u8; 32]), tx_params); + GenericExtrinsicParams::>::new( + 0, + 0, + 0u32, + Hash::from([0u8; 32]), + tx_params, + ); let xt = UncheckedExtrinsicV4::new_signed( vec![1, 1, 1], account, @@ -190,4 +250,34 @@ mod tests { let xt_enc = xt.encode(); assert_eq!(xt, Decode::decode(&mut xt_enc.as_slice()).unwrap()) } + + #[test] + fn serialize_deserialize_works() { + let bob: AccountId32 = + sr25519::Public::from_ss58check("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty") + .unwrap() + .into(); + let bob = MultiAddress::Id(bob); + + let call1 = RuntimeCall::Balances(BalancesCall::force_transfer { + source: bob.clone(), + dest: bob.clone(), + value: 10, + }); + let xt1 = UncheckedExtrinsicV4::< + MultiAddress, + RuntimeCall, + MultiSignature, + SignedExtra, + >::new_unsigned(call1.clone()); + let json = serde_json::to_string(&xt1).expect("serializing failed"); + let extrinsic: UncheckedExtrinsicV4< + MultiAddress, + RuntimeCall, + MultiSignature, + SignedExtra, + > = serde_json::from_str(&json).expect("deserializing failed"); + let call = extrinsic.function; + assert_eq!(call, call1); + } } diff --git a/primitives/src/extrinsics/signer.rs b/primitives/src/extrinsics/signer.rs index d69ab533f..3af74bf4b 100644 --- a/primitives/src/extrinsics/signer.rs +++ b/primitives/src/extrinsics/signer.rs @@ -17,11 +17,11 @@ //! Signer used to sign extrinsic. -use crate::FrameSystemConfig; +use crate::config::Config; use codec::{Decode, Encode}; use core::marker::PhantomData; use sp_core::{crypto::AccountId32, Pair}; -use sp_runtime::{traits::StaticLookup, MultiAddress}; +use sp_runtime::MultiAddress; pub trait SignExtrinsic { type Signature: Encode; @@ -40,49 +40,34 @@ pub trait SignExtrinsic { } #[derive(Encode, Decode, Clone, PartialEq)] -pub struct ExtrinsicSigner -where - Signer: Pair, - Runtime: FrameSystemConfig, -{ - signer: Signer, - account_id: Runtime::AccountId, - extrinsic_address: ::Source, - _phantom: PhantomData, +pub struct ExtrinsicSigner { + signer: T::CryptoKey, + account_id: T::AccountId, + extrinsic_address: T::Address, + _phantom: PhantomData, } -impl ExtrinsicSigner -where - Signer: Pair, - Runtime: FrameSystemConfig, - Runtime::AccountId: From, -{ - pub fn new(signer: Signer) -> Self { - let account_id: Runtime::AccountId = signer.public().into(); - let extrinsic_address = Runtime::Lookup::unlookup(account_id.clone()); +impl ExtrinsicSigner { + pub fn new(signer: T::CryptoKey) -> Self { + let account_id: T::AccountId = signer.public().into(); + let extrinsic_address: T::Address = account_id.clone().into(); Self { signer, account_id, extrinsic_address, _phantom: Default::default() } } - pub fn signer(&self) -> &Signer { + pub fn signer(&self) -> &T::CryptoKey { &self.signer } } -impl SignExtrinsic - for ExtrinsicSigner -where - Runtime: FrameSystemConfig, - Signer: Pair, - Signature: From + Encode, -{ - type Signature = Signature; - type ExtrinsicAddress = ::Source; +impl SignExtrinsic for ExtrinsicSigner { + type Signature = T::Signature; + type ExtrinsicAddress = T::Address; fn sign(&self, payload: &[u8]) -> Self::Signature { self.signer.sign(payload).into() } - fn public_account_id(&self) -> &Runtime::AccountId { + fn public_account_id(&self) -> &T::AccountId { &self.account_id } @@ -91,14 +76,13 @@ where } } -impl From for ExtrinsicSigner +impl From for ExtrinsicSigner where - Signer: Pair, - Runtime: FrameSystemConfig, - Runtime::AccountId: From, + T: Config, + Signer: Pair + Into, { fn from(value: Signer) -> Self { - ExtrinsicSigner::::new(value) + ExtrinsicSigner::::new(value.into()) } } @@ -154,35 +138,19 @@ where #[cfg(test)] mod tests { use super::*; - use node_template_runtime::{Runtime, Signature}; - use sp_core::{sr25519, Pair}; + use crate::SubstrateKitchensinkConfig; + use node_template_runtime::Signature; + use sp_core::sr25519; use sp_keyring::AccountKeyring; #[test] - fn test_extrinsic_signer_from_sr25519_pair() { - let alice: sr25519::Pair = Pair::from_string( - "0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a", - None, - ) - .unwrap(); - - let es_converted: ExtrinsicSigner<_, _, Runtime> = alice.clone().into(); - let es_new = - ExtrinsicSigner::::new(alice.clone()); + fn test_extrinsic_signer_clone() { + let pair = AccountKeyring::Alice.pair(); + let signer = ExtrinsicSigner::::new(pair); - assert_eq!(es_converted.signer.public(), es_new.signer.public()); + let _signer2 = signer.clone(); } - // This test does not work. See issue #504. - - // #[test] - // fn test_extrinsic_signer_clone() { - // let pair = AccountKeyring::Alice.pair(); - // let signer = ExtrinsicSigner::<_, Signature, Runtime>::new(pair); - // - // let signer2 = signer.clone(); - // } - #[test] fn test_static_extrinsic_signer_clone() { let pair = AccountKeyring::Alice.pair(); @@ -190,4 +158,18 @@ mod tests { let _signer2 = signer.clone(); } + + #[test] + fn test_extrinsic_signer_from_sr25519_pair() { + let alice: sr25519::Pair = Pair::from_string( + "0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a", + None, + ) + .unwrap(); + + let es_converted: ExtrinsicSigner = alice.clone().into(); + let es_new = ExtrinsicSigner::::new(alice.clone()); + + assert_eq!(es_converted.signer.public(), es_new.signer.public()); + } } diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 7baabba3d..7c4087afe 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -20,16 +20,18 @@ extern crate alloc; // Re-export everything. +pub use config::*; pub use extrinsics::*; -pub use pallet_traits::*; pub use rpc_numbers::*; pub use rpc_params::*; pub use serde_impls::*; +pub use traits::*; pub use types::*; +pub mod config; pub mod extrinsics; -pub mod pallet_traits; pub mod rpc_numbers; pub mod rpc_params; pub mod serde_impls; +pub mod traits; pub mod types; diff --git a/primitives/src/pallet_traits/frame_system_config.rs b/primitives/src/pallet_traits/frame_system_config.rs deleted file mode 100644 index 1b860a499..000000000 --- a/primitives/src/pallet_traits/frame_system_config.rs +++ /dev/null @@ -1,159 +0,0 @@ -/* - Copyright 2019 Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use codec::{Codec, Decode, EncodeLike, FullCodec, MaxEncodedLen}; -use core::fmt::Debug; -use scale_info::TypeInfo; -use serde::{de::DeserializeOwned, Serialize}; -use sp_runtime::traits::{ - self, AtLeast32Bit, AtLeast32BitUnsigned, Bounded, CheckEqual, Dispatchable, Get, Hash, Member, - SimpleBitOps, StaticLookup, -}; - -/// Simplified Frame system Config trait. Needed because substrate pallets compile to wasm -/// in no_std mode. -pub trait FrameSystemConfig { - type BaseCallFilter; - type BlockWeights; - type BlockLength; - type RuntimeOrigin: Clone; - type RuntimeCall: Codec - + EncodeLike - + Clone - + Eq - + Debug - + TypeInfo - + Dispatchable - + Debug; - /// This type enforces the (de)serialization implementation - /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). - type Index: Serialize - + DeserializeOwned - + Debug - + Default - + AtLeast32Bit - + Copy - + MaxEncodedLen - + Decode; - /// This type enforces the (de)serialization implementation - /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). - type BlockNumber: Codec - + EncodeLike - + Clone - + Eq - + Debug - + TypeInfo - + Serialize - + DeserializeOwned - + Debug - + AtLeast32BitUnsigned - + Default - + Bounded - + Copy - + core::hash::Hash - + core::str::FromStr - + MaxEncodedLen - + TypeInfo; - /// This type enforces the (de)serialization implementation - /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). - /// A type redefinition might be necessary in no-std. - /// See primitives/serde_impls for examples - type Hash: Codec - + EncodeLike - + Clone - + Eq - + Debug - + TypeInfo - + Serialize - + DeserializeOwned - + Debug - + SimpleBitOps - + Ord - + Default - + Copy - + CheckEqual - + core::hash::Hash - + AsRef<[u8]> - + AsMut<[u8]> - + MaxEncodedLen; - type Hashing: Hash + TypeInfo; - /// This type enforces the (de)serialization implementation - /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). - /// A type redefinition might be necessary in no-std. - /// See primitives/serde_impls for examples. - type AccountId: Codec - + EncodeLike - + Clone - + Eq - + Debug - + TypeInfo - + Member - + Serialize - + DeserializeOwned - + Debug - + Ord - + MaxEncodedLen; - type Lookup: StaticLookup; - type Header: Codec - + EncodeLike - + Clone - + Eq - + Debug - + TypeInfo - + traits::Header; - type RuntimeEvent: Codec + EncodeLike + Clone + Eq + TypeInfo + Member + Debug; - type BlockHashCount: Get; - type DbWeight; - type Version; - type AccountData: Member + FullCodec + Clone + Default + TypeInfo + MaxEncodedLen; - type OnNewAccount; - type OnKilledAccount; - type SystemWeightInfo; - type SS58Prefix: Get; - type OnSetCode; - type MaxConsumers; -} - -#[cfg(feature = "std")] -impl FrameSystemConfig for T -where - T: frame_system::Config, -{ - type BaseCallFilter = T::BaseCallFilter; - type BlockWeights = T::BlockWeights; - type BlockLength = T::BlockLength; - type RuntimeOrigin = T::RuntimeOrigin; - type RuntimeCall = T::RuntimeCall; - type Index = T::Index; - type BlockNumber = T::BlockNumber; - type Hash = T::Hash; - type Hashing = T::Hashing; - type AccountId = T::AccountId; - type Lookup = T::Lookup; - type Header = T::Header; - type RuntimeEvent = T::RuntimeEvent; - type BlockHashCount = T::BlockHashCount; - type DbWeight = T::DbWeight; - type Version = T::Version; - type AccountData = T::AccountData; - type OnNewAccount = T::OnNewAccount; - type OnKilledAccount = T::OnKilledAccount; - type SystemWeightInfo = T::SystemWeightInfo; - type SS58Prefix = T::SS58Prefix; - type OnSetCode = T::OnSetCode; - type MaxConsumers = T::MaxConsumers; -} diff --git a/primitives/src/pallet_traits/mod.rs b/primitives/src/pallet_traits/mod.rs deleted file mode 100644 index df276bfe6..000000000 --- a/primitives/src/pallet_traits/mod.rs +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright 2019 Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub use frame_system_config::FrameSystemConfig; -pub use pallet_assets_config::AssetsConfig; -pub use pallet_balances_config::BalancesConfig; -pub use pallet_contracts_config::ContractsConfig; -pub use pallet_staking_config::StakingConfig; - -pub mod frame_system_config; -pub mod pallet_assets_config; -pub mod pallet_balances_config; -pub mod pallet_contracts_config; -pub mod pallet_staking_config; diff --git a/primitives/src/pallet_traits/pallet_assets_config.rs b/primitives/src/pallet_traits/pallet_assets_config.rs deleted file mode 100644 index 849d51f2b..000000000 --- a/primitives/src/pallet_traits/pallet_assets_config.rs +++ /dev/null @@ -1,76 +0,0 @@ -/* - Copyright 2019 Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use codec::MaxEncodedLen; -use scale_info::TypeInfo; -use serde::{de::DeserializeOwned, Serialize}; -use sp_runtime::traits::{AtLeast32BitUnsigned, Get, Member}; - -/// Simplified pallet assets Config trait. Needed because substrate pallets compile to wasm -/// in no_std mode. -pub trait AssetsConfig: crate::FrameSystemConfig { - type RuntimeEvent; - /// This type enforces the (de)serialization implementation - /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). - type Balance: AtLeast32BitUnsigned - + Default - + Copy - + Serialize - + DeserializeOwned - + MaxEncodedLen - + TypeInfo; - type RemoveItemsLimit: Get; - /// This type enforces the (de)serialization implementation - /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). - type AssetId: Member + Copy + Serialize + DeserializeOwned + MaxEncodedLen; - type AssetIdParameter: Copy + From + Into + MaxEncodedLen; - type Currency; - type CreateOrigin; - type ForceOrigin; - type AssetDeposit; - type AssetAccountDeposit; - type MetadataDepositBase; - type MetadataDepositPerByte; - type ApprovalDeposit; - type StringLimit: Get; - type Freezer; - type Extra: Member + Default + MaxEncodedLen; - type WeightInfo; -} - -#[cfg(feature = "std")] -impl AssetsConfig for T -where - T: pallet_assets::Config, -{ - type RuntimeEvent = ::RuntimeEvent; - type Balance = T::Balance; - type RemoveItemsLimit = T::RemoveItemsLimit; - type AssetId = T::AssetId; - type AssetIdParameter = T::AssetIdParameter; - type Currency = T::Currency; - type CreateOrigin = T::CreateOrigin; - type ForceOrigin = T::ForceOrigin; - type AssetDeposit = T::AssetDeposit; - type AssetAccountDeposit = T::AssetAccountDeposit; - type MetadataDepositBase = T::MetadataDepositBase; - type MetadataDepositPerByte = T::MetadataDepositPerByte; - type ApprovalDeposit = T::ApprovalDeposit; - type StringLimit = T::StringLimit; - type Freezer = T::Freezer; - type Extra = T::Extra; - type WeightInfo = T::WeightInfo; -} diff --git a/primitives/src/pallet_traits/pallet_balances_config.rs b/primitives/src/pallet_traits/pallet_balances_config.rs deleted file mode 100644 index 107bc8392..000000000 --- a/primitives/src/pallet_traits/pallet_balances_config.rs +++ /dev/null @@ -1,74 +0,0 @@ -/* - Copyright 2019 Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use codec::{Codec, EncodeLike, MaxEncodedLen}; -use scale_info::TypeInfo; -use serde::{de::DeserializeOwned, Serialize}; -use sp_runtime::{ - traits::{AtLeast32BitUnsigned, Get, Member}, - FixedPointOperand, -}; - -/// Simplified pallet balances Config trait. Needed because substrate pallets compile to wasm -/// in no_std mode. -pub trait BalancesConfig: crate::FrameSystemConfig { - /// This type enforces the (de)serialization implementation - /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). - type Balance: Codec - + EncodeLike - + Member - + AtLeast32BitUnsigned - + Default - + Copy - + Serialize - + DeserializeOwned - + MaxEncodedLen - + TypeInfo - + FixedPointOperand; - type DustRemoval; - type RuntimeEvent; - type ExistentialDeposit: Get; - type AccountStore; - /// Use of reserves is deprecated in favour of holds. See `https://github.com/paritytech/substrate/pull/12951/` - type ReserveIdentifier: Codec + EncodeLike + TypeInfo + Member + MaxEncodedLen + Ord + Copy; - type HoldIdentifier: Codec + EncodeLike + TypeInfo + Member + MaxEncodedLen + Ord + Copy; - type FreezeIdentifier: Codec + EncodeLike + TypeInfo + Member + MaxEncodedLen + Ord + Copy; - type WeightInfo; - type MaxLocks: Get; - type MaxReserves: Get; - type MaxHolds: Get; - type MaxFreezes: Get; -} - -#[cfg(feature = "std")] -impl BalancesConfig for T -where - T: pallet_balances::Config, -{ - type Balance = T::Balance; - type DustRemoval = T::DustRemoval; - type RuntimeEvent = ::RuntimeEvent; - type ExistentialDeposit = T::ExistentialDeposit; - type AccountStore = T::AccountStore; - type WeightInfo = T::WeightInfo; - type MaxLocks = T::MaxLocks; - type MaxReserves = T::MaxReserves; - type ReserveIdentifier = T::ReserveIdentifier; - type HoldIdentifier = T::HoldIdentifier; - type FreezeIdentifier = T::FreezeIdentifier; - type MaxHolds = T::MaxHolds; - type MaxFreezes = T::MaxFreezes; -} diff --git a/primitives/src/pallet_traits/pallet_contracts_config.rs b/primitives/src/pallet_traits/pallet_contracts_config.rs deleted file mode 100644 index 55eb87cf6..000000000 --- a/primitives/src/pallet_traits/pallet_contracts_config.rs +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright 2019 Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use crate::FrameSystemConfig; -use sp_runtime::traits::Get; - -/// Simplified pallet contract Config trait. Needed because substrate pallets compile to wasm -/// in no_std mode. -pub trait ContractsConfig: FrameSystemConfig { - type Time; - type Randomness; - type Currency; - type RuntimeEvent; - type RuntimeCall: codec::Decode; - type CallFilter; - type WeightPrice; - type WeightInfo; - type ChainExtension: Default; - type Schedule; - type CallStack; - type DepositPerByte; - type DepositPerItem; - type AddressGenerator; - type MaxCodeLen: Get; - type MaxStorageKeyLen: Get; - type UnsafeUnstableInterface: Get; - type MaxDebugBufferLen: Get; -} - -#[cfg(feature = "contracts-xt")] -impl ContractsConfig for T -where - T: pallet_contracts::Config, -{ - type Time = T::Time; - type Randomness = T::Randomness; - type Currency = T::Currency; - type RuntimeEvent = ::RuntimeEvent; - type RuntimeCall = ::RuntimeCall; - type CallFilter = T::CallFilter; - type WeightPrice = T::WeightPrice; - type WeightInfo = T::WeightInfo; - type ChainExtension = T::ChainExtension; - type Schedule = T::Schedule; - type CallStack = T::CallStack; - type DepositPerByte = T::DepositPerByte; - type DepositPerItem = T::DepositPerItem; - type AddressGenerator = T::AddressGenerator; - type MaxCodeLen = T::MaxCodeLen; - type MaxStorageKeyLen = T::MaxStorageKeyLen; - type UnsafeUnstableInterface = T::UnsafeUnstableInterface; - type MaxDebugBufferLen = T::MaxDebugBufferLen; -} diff --git a/primitives/src/pallet_traits/pallet_staking_config.rs b/primitives/src/pallet_traits/pallet_staking_config.rs deleted file mode 100644 index b59b16882..000000000 --- a/primitives/src/pallet_traits/pallet_staking_config.rs +++ /dev/null @@ -1,103 +0,0 @@ -/* - Copyright 2019 Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use crate::FrameSystemConfig; -use codec::MaxEncodedLen; -use scale_info::TypeInfo; -use serde::{de::DeserializeOwned, Serialize}; -use sp_runtime::{ - traits::{AtLeast32BitUnsigned, Get}, - Perbill, -}; -use sp_staking::{EraIndex, SessionIndex}; - -/// The balance type of this pallet. -pub type BalanceOf = ::CurrencyBalance; - -/// Simplified pallet staking Config trait. Needed because substrate pallets compile to wasm -/// in no_std mode. -pub trait StakingConfig: FrameSystemConfig { - type Currency; - /// This type enforces the (de)serialization implementation - /// also in no-std mode (unlike substrates MaybeSerializeDeserialize). - type CurrencyBalance: AtLeast32BitUnsigned - + codec::FullCodec - + Copy - + Serialize - + DeserializeOwned - + core::fmt::Debug - + Default - + From - + TypeInfo - + MaxEncodedLen; - type UnixTime; - type CurrencyToVote; - type ElectionProvider; - type GenesisElectionProvider; - type MaxNominations: Get; - type HistoryDepth: Get; - type RewardRemainder; - type RuntimeEvent; - type Slash; - type Reward; - type SessionsPerEra: Get; - type BondingDuration: Get; - type SlashDeferDuration: Get; - type AdminOrigin; - type SessionInterface; - type EraPayout; - type NextNewSession; - type MaxNominatorRewardedPerValidator: Get; - type OffendingValidatorsThreshold: Get; - type VoterList; - type TargetList; - type MaxUnlockingChunks: Get; - type OnStakerSlash: sp_staking::OnStakerSlash>; - type WeightInfo; -} - -#[cfg(feature = "staking-xt")] -impl StakingConfig for T -where - T: pallet_staking::Config, -{ - type Currency = T::Currency; - type CurrencyBalance = T::CurrencyBalance; - type UnixTime = T::UnixTime; - type CurrencyToVote = T::CurrencyToVote; - type ElectionProvider = T::ElectionProvider; - type GenesisElectionProvider = T::GenesisElectionProvider; - type MaxNominations = T::MaxNominations; - type HistoryDepth = T::HistoryDepth; - type RewardRemainder = T::RewardRemainder; - type RuntimeEvent = ::RuntimeEvent; - type Slash = T::Slash; - type Reward = T::Reward; - type SessionsPerEra = T::SessionsPerEra; - type BondingDuration = T::BondingDuration; - type SlashDeferDuration = T::SlashDeferDuration; - type AdminOrigin = T::AdminOrigin; - type SessionInterface = T::SessionInterface; - type EraPayout = T::EraPayout; - type NextNewSession = T::NextNewSession; - type MaxNominatorRewardedPerValidator = T::MaxNominatorRewardedPerValidator; - type OffendingValidatorsThreshold = T::OffendingValidatorsThreshold; - type VoterList = T::VoterList; - type TargetList = T::TargetList; - type MaxUnlockingChunks = T::MaxUnlockingChunks; - type OnStakerSlash = T::OnStakerSlash; - type WeightInfo = T::WeightInfo; -} diff --git a/primitives/src/serde_impls.rs b/primitives/src/serde_impls.rs index 615b9486b..acb8b39aa 100644 --- a/primitives/src/serde_impls.rs +++ b/primitives/src/serde_impls.rs @@ -20,13 +20,15 @@ //! the original substrate types with From / Into. //! This may be omitted, if substrate allows serde impls also in no_std: https://github.com/paritytech/substrate/issues/12994 -use alloc::{string::String, vec::Vec}; +use crate::{Block, Hasher, Header}; +use alloc::{format, string::String, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use impl_serde::serialize::{from_hex, FromHexError}; +use primitive_types::{H256, U256}; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_core::RuntimeDebug; -use sp_runtime::Justification; +use sp_runtime::{traits::Extrinsic, Justification}; use sp_version::{ApiId, ApisVec}; /// Hex-serialized shim for `Vec`. @@ -458,12 +460,285 @@ mod apis_serialize { } } +#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone)] +pub struct SubstrateOpaqueExtrinsic(Vec); + +impl SubstrateOpaqueExtrinsic { + /// Convert an encoded extrinsic to an `SubstrateOpaqueExtrinsic`. + pub fn from_bytes(mut bytes: &[u8]) -> Result { + Self::decode(&mut bytes) + } +} + +impl ::serde::Serialize for SubstrateOpaqueExtrinsic { + fn serialize(&self, seq: S) -> Result + where + S: ::serde::Serializer, + { + self.using_encoded(|bytes| ::impl_serde::serialize::serialize(bytes, seq)) + } +} + +impl<'a> ::serde::Deserialize<'a> for SubstrateOpaqueExtrinsic { + fn deserialize(de: D) -> Result + where + D: ::serde::Deserializer<'a>, + { + let r = impl_serde::serialize::deserialize(de)?; + Decode::decode(&mut &r[..]) + .map_err(|e| ::serde::de::Error::custom(format!("Decode error: {}", e))) + } +} + +impl Extrinsic for SubstrateOpaqueExtrinsic { + type Call = (); + type SignaturePayload = (); +} + +/// A generic Substrate block type, adapted from `sp_runtime::generic::Block`. +#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SubstrateBlock { + /// The block header. + pub header: H, + /// The accompanying extrinsics. + pub extrinsics: Vec, +} + +impl Block for SubstrateBlock +where + H: Header, + E: Extrinsic + Encode + Serialize, +{ + type Extrinsic = E; + type Header = H; + type Hasher = ::Hasher; + + fn header(&self) -> &Self::Header { + &self.header + } + fn extrinsics(&self) -> &[Self::Extrinsic] { + &self.extrinsics[..] + } + fn deconstruct(self) -> (Self::Header, Vec) { + (self.header, self.extrinsics) + } + fn new(header: Self::Header, extrinsics: Vec) -> Self { + SubstrateBlock { header, extrinsics } + } + fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec { + (header, extrinsics).encode() + } +} + +// Copied from subxt. +// https://github.com/paritytech/subxt/blob/ce0a82e3227efb0eae131f025da5f839d9623e15/subxt/src/config/substrate.rs +/// A type that can hash values using the blaks2_256 algorithm. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode)] +pub struct BlakeTwo256; + +impl Hasher for BlakeTwo256 { + type Output = H256; + fn hash(s: &[u8]) -> Self::Output { + sp_core_hashing::blake2_256(s).into() + } +} + +/// A generic Substrate header type, adapted from `sp_runtime::generic::Header`. +/// The block number and hasher can be configured to adapt this for other nodes. +#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SubstrateHeader + TryFrom, H: Hasher> { + /// The parent hash. + pub parent_hash: H::Output, + /// The block number. + #[serde(serialize_with = "serialize_number", deserialize_with = "deserialize_number")] + #[codec(compact)] + pub number: N, + /// The state trie merkle root + pub state_root: H::Output, + /// The merkle root of the extrinsics. + pub extrinsics_root: H::Output, + /// A chain-specific digest of data useful for light clients or referencing auxiliary data. + pub digest: Digest, +} + +impl Header for SubstrateHeader +where + N: Copy + Into + Into + TryFrom + Encode, + H: Hasher + Encode, + SubstrateHeader: Encode, +{ + type Number = N; + type Hasher = H; + fn number(&self) -> Self::Number { + self.number + } +} + +/// Generic header digest. From `sp_runtime::generic::digest`. +#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Default)] +pub struct Digest { + /// A list of digest items. + pub logs: Vec, +} + +/// Digest item that is able to encode/decode 'system' digest items and +/// provide opaque access to other items. From `sp_runtime::generic::digest`. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum DigestItem { + /// A pre-runtime digest. + /// + /// These are messages from the consensus engine to the runtime, although + /// the consensus engine can (and should) read them itself to avoid + /// code and state duplication. It is erroneous for a runtime to produce + /// these, but this is not (yet) checked. + /// + /// NOTE: the runtime is not allowed to panic or fail in an `on_initialize` + /// call if an expected `PreRuntime` digest is not present. It is the + /// responsibility of a external block verifier to check this. Runtime API calls + /// will initialize the block without pre-runtime digests, so initialization + /// cannot fail when they are missing. + PreRuntime(ConsensusEngineId, Vec), + + /// A message from the runtime to the consensus engine. This should *never* + /// be generated by the native code of any consensus engine, but this is not + /// checked (yet). + Consensus(ConsensusEngineId, Vec), + + /// Put a Seal on it. This is only used by native code, and is never seen + /// by runtimes. + Seal(ConsensusEngineId, Vec), + + /// Some other thing. Unsupported and experimental. + Other(Vec), + + /// An indication for the light clients that the runtime execution + /// environment is updated. + /// + /// Currently this is triggered when: + /// 1. Runtime code blob is changed or + /// 2. `heap_pages` value is changed. + RuntimeEnvironmentUpdated, +} + +// From sp_runtime::generic, DigestItem enum indexes are encoded using this: +#[repr(u32)] +#[derive(Encode, Decode)] +enum DigestItemType { + Other = 0u32, + Consensus = 4u32, + Seal = 5u32, + PreRuntime = 6u32, + RuntimeEnvironmentUpdated = 8u32, +} +impl Encode for DigestItem { + fn encode(&self) -> Vec { + let mut v = Vec::new(); + + match self { + Self::Consensus(val, data) => { + DigestItemType::Consensus.encode_to(&mut v); + (val, data).encode_to(&mut v); + }, + Self::Seal(val, sig) => { + DigestItemType::Seal.encode_to(&mut v); + (val, sig).encode_to(&mut v); + }, + Self::PreRuntime(val, data) => { + DigestItemType::PreRuntime.encode_to(&mut v); + (val, data).encode_to(&mut v); + }, + Self::Other(val) => { + DigestItemType::Other.encode_to(&mut v); + val.encode_to(&mut v); + }, + Self::RuntimeEnvironmentUpdated => { + DigestItemType::RuntimeEnvironmentUpdated.encode_to(&mut v); + }, + } + + v + } +} +impl Decode for DigestItem { + fn decode(input: &mut I) -> Result { + let item_type: DigestItemType = Decode::decode(input)?; + match item_type { + DigestItemType::PreRuntime => { + let vals: (ConsensusEngineId, Vec) = Decode::decode(input)?; + Ok(Self::PreRuntime(vals.0, vals.1)) + }, + DigestItemType::Consensus => { + let vals: (ConsensusEngineId, Vec) = Decode::decode(input)?; + Ok(Self::Consensus(vals.0, vals.1)) + }, + DigestItemType::Seal => { + let vals: (ConsensusEngineId, Vec) = Decode::decode(input)?; + Ok(Self::Seal(vals.0, vals.1)) + }, + DigestItemType::Other => Ok(Self::Other(Decode::decode(input)?)), + DigestItemType::RuntimeEnvironmentUpdated => Ok(Self::RuntimeEnvironmentUpdated), + } + } +} + +/// Consensus engine unique ID. From `sp_runtime::ConsensusEngineId`. +pub type ConsensusEngineId = [u8; 4]; + +impl serde::Serialize for DigestItem { + fn serialize(&self, seq: S) -> Result + where + S: serde::Serializer, + { + self.using_encoded(|bytes| impl_serde::serialize::serialize(bytes, seq)) + } +} + +impl<'a> serde::Deserialize<'a> for DigestItem { + fn deserialize(de: D) -> Result + where + D: serde::Deserializer<'a>, + { + let r = impl_serde::serialize::deserialize(de)?; + Decode::decode(&mut &r[..]) + .map_err(|e| serde::de::Error::custom(format!("Decode error: {e}"))) + } +} + +fn serialize_number + TryFrom>( + val: &T, + s: S, +) -> Result +where + S: serde::Serializer, +{ + let u256: U256 = (*val).into(); + serde::Serialize::serialize(&u256, s) +} + +fn deserialize_number<'a, D, T: Copy + Into + TryFrom>(d: D) -> Result +where + D: serde::Deserializer<'a>, +{ + // At the time of writing, Smoldot gives back block numbers in numeric rather + // than hex format. So let's support deserializing from both here: + use crate::rpc_numbers::NumberOrHex; + let number_or_hex = NumberOrHex::deserialize(d)?; + let u256 = number_or_hex.into_u256(); + TryFrom::try_from(u256).map_err(|_| serde::de::Error::custom("Try from failed")) +} + #[cfg(test)] mod tests { use super::*; + use crate::UncheckedExtrinsicV4; use codec::Encode; use core::str::FromStr; + use node_template_runtime::{BalancesCall, RuntimeCall, SignedExtra}; use primitive_types::H256; + use sp_core::crypto::Ss58Codec; + use sp_runtime::{testing::sr25519, AccountId32, MultiAddress, MultiSignature}; #[test] fn from_substrate_bytes_to_bytes_works() { @@ -542,4 +817,73 @@ mod tests { assert_eq!(original_signed_block, signed_block); } + + #[test] + fn deserialize_header_works() { + let header_json = r#" + { + "digest": { + "logs": [] + }, + "extrinsicsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000", + "number": 4, + "parentHash": "0xcb2690b2c85ceab55be03fc7f7f5f3857e7efeb7a020600ebd4331e10be2f7a5", + "stateRoot": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + "#; + + let header: SubstrateHeader = + serde_json::from_str(header_json).expect("valid block header"); + assert_eq!(header.number(), 4); + } + #[test] + fn deserialize_block_works() { + //header + let header = SubstrateHeader:: { + parent_hash: BlakeTwo256::hash(b"1000"), + number: 2000, + state_root: BlakeTwo256::hash(b"3000"), + extrinsics_root: BlakeTwo256::hash(b"4000"), + digest: Digest { logs: vec![] }, + }; + + //extrinsic + let bob: AccountId32 = + sr25519::Public::from_ss58check("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty") + .unwrap() + .into(); + let bob = MultiAddress::Id(bob); + + let call1 = RuntimeCall::Balances(BalancesCall::force_transfer { + source: bob.clone(), + dest: bob.clone(), + value: 10, + }); + let xt1 = UncheckedExtrinsicV4::< + MultiAddress, + RuntimeCall, + MultiSignature, + SignedExtra, + >::new_unsigned(call1.clone()); + + //Block + let extrinsics = vec![xt1]; + let block = SubstrateBlock::new(header.clone(), extrinsics.clone()); + + //serialize + let json = serde_json::to_string(&block).expect("serializing failed"); + let block_des: SubstrateBlock< + SubstrateHeader, + UncheckedExtrinsicV4< + MultiAddress, + RuntimeCall, + MultiSignature, + SignedExtra, + >, + > = serde_json::from_str(&json).expect("deserializing failed"); + let header_des = block_des.header; + assert_eq!(header, header_des); + let extrinsics_des = block_des.extrinsics; + assert_eq!(extrinsics_des, extrinsics); + } } diff --git a/primitives/src/traits.rs b/primitives/src/traits.rs new file mode 100644 index 000000000..9194bd538 --- /dev/null +++ b/primitives/src/traits.rs @@ -0,0 +1,83 @@ +/* + Copyright 2019 Supercomputing Systems AG + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +//! Re-definition of substrate trait +//! Needed to become independent of sp_runtime + +use alloc::vec::Vec; +use codec::Encode; +use sp_runtime::traits::Extrinsic; + +/// This represents the hasher used by a node to hash things like block headers +/// and extrinsics. +// https://github.com/paritytech/subxt/blob/ce0a82e3227efb0eae131f025da5f839d9623e15/subxt/src/config/mod.rs#L71 +pub trait Hasher { + /// The type given back from the hash operation + type Output; + + /// Hash some bytes to the given output type. + fn hash(s: &[u8]) -> Self::Output; + + /// Hash some SCALE encodable type to the given output type. + fn hash_of(s: &S) -> Self::Output { + let out = s.encode(); + Self::hash(&out) + } +} +/// This represents the block header type used by a node. +// https://github.com/paritytech/subxt/blob/ce0a82e3227efb0eae131f025da5f839d9623e15/subxt/src/config/mod.rs#L85 +pub trait Header: Sized + Encode { + /// The block number type for this header. + type Number: Into; + /// The hasher used to hash this header. + type Hasher: Hasher; //Header::Hash; type Hashing: Hash; + + /// Return the block number of this header. + fn number(&self) -> Self::Number; + + /// Hash this header. + fn hash(&self) -> ::Output { + Self::Hasher::hash_of(self) + } +} + +/// This represents the block header type used by a node. +// https://github.com/paritytech/substrate/blob/master/primitives/runtime/src/traits.rs +pub trait Block: Sized + Encode { + /// Type for extrinsics. + type Extrinsic: Extrinsic + Encode; + /// Header type. + type Header: Header; + /// Block hash type. + type Hasher: Hasher; + + /// Returns a reference to the header. + fn header(&self) -> &Self::Header; + /// Returns a reference to the list of extrinsics. + fn extrinsics(&self) -> &[Self::Extrinsic]; + /// Split the block into header and list of extrinsics. + fn deconstruct(self) -> (Self::Header, Vec); + /// Creates new block from header and extrinsics. + fn new(header: Self::Header, extrinsics: Vec) -> Self; + /// Returns the hash of the block. + fn hash(&self) -> ::Output { + <::Hasher>::hash_of(self.header()) + } + /// Creates an encoded block from the given `header` and `extrinsics` without requiring the + /// creation of an instance. + fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec; +} diff --git a/primitives/src/types.rs b/primitives/src/types.rs index 77b2d78c8..a2785b942 100644 --- a/primitives/src/types.rs +++ b/primitives/src/types.rs @@ -27,6 +27,50 @@ use sp_runtime::traits::{AtLeast32BitUnsigned, Zero}; /// Type used to encode the number of references an account has. pub type RefCount = u32; + +/// All balance information for an account. +//https://github.com/paritytech/substrate/blob/d6f278b9685ac871c79e45551b66111b77cb1b71/frame/balances/src/types.rs#L95 +#[derive(Encode, Decode, Clone, PartialEq, Eq, Default, RuntimeDebug, MaxEncodedLen, TypeInfo)] +pub struct AccountData { + /// Non-reserved part of the balance which the account holder may be able to control. + /// + /// This is the only balance that matters in terms of most operations on tokens. + pub free: Balance, + /// Balance which is has active holds on it and may not be used at all. + /// + /// This is the sum of all individual holds together with any sums still under the (deprecated) + /// reserves API. + pub reserved: Balance, + /// The amount that `free` may not drop below when reducing the balance, except for actions + /// where the account owner cannot reasonably benefit from thr balance reduction, such as + /// slashing. + pub frozen: Balance, + /// Extra information about this account. The MSB is a flag indicating whether the new ref- + /// counting logic is in place for this account. + pub flags: ExtraFlags, +} + +const IS_NEW_LOGIC: u128 = 0x80000000_00000000_00000000_00000000u128; + +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)] +pub struct ExtraFlags(u128); +impl Default for ExtraFlags { + fn default() -> Self { + Self(IS_NEW_LOGIC) + } +} +impl ExtraFlags { + pub fn old_logic() -> Self { + Self(0) + } + pub fn set_new_logic(&mut self) { + self.0 |= IS_NEW_LOGIC + } + pub fn is_new_logic(&self) -> bool { + (self.0 & IS_NEW_LOGIC) == IS_NEW_LOGIC + } +} + /// Information of an account. // https://github.com/paritytech/substrate/blob/416a331399452521f3e9cf7e1394d020373a95c5/frame/system/src/lib.rs#L735-L753 #[derive(Clone, Eq, PartialEq, Default, Encode, Decode, TypeInfo, MaxEncodedLen)] diff --git a/src/api/api_client.rs b/src/api/api_client.rs index 24a2348e9..0481cd531 100644 --- a/src/api/api_client.rs +++ b/src/api/api_client.rs @@ -18,7 +18,7 @@ use crate::{ }; use ac_compose_macros::rpc_params; use ac_node_api::metadata::Metadata; -use ac_primitives::{Bytes, ExtrinsicParams, FrameSystemConfig, RuntimeVersion, SignExtrinsic}; +use ac_primitives::{Bytes, Config, ExtrinsicParams, RuntimeVersion, SignExtrinsic}; use codec::Decode; use core::convert::TryFrom; use frame_metadata::RuntimeMetadataPrefixed; @@ -32,13 +32,13 @@ use log::{debug, info}; /// /// ```no_run /// use substrate_api_client::{ -/// Api, rpc::Request, rpc::Error as RpcClientError, XtStatus, ac_primitives::PlainTipExtrinsicParams, rpc::Result as RpcResult +/// Api, rpc::Request, rpc::Error as RpcClientError, XtStatus, rpc::Result as RpcResult, ac_primitives::SubstrateKitchensinkConfig /// }; /// use serde::de::DeserializeOwned; /// use ac_primitives::RpcParams; /// use serde_json::{Value, json}; -/// use kitchensink_runtime::Runtime; -/// +/// ; +/// /// /// struct MyClient { /// // pick any request crate, such as ureq::Agent /// _inner: (), @@ -76,31 +76,24 @@ use log::{debug, info}; /// } /// /// let client = MyClient::new(); -/// let _api = Api::<(), _, PlainTipExtrinsicParams, Runtime>::new(client); +/// let _api = Api::::new(client); /// /// ``` #[derive(Clone)] -pub struct Api -where - Runtime: FrameSystemConfig, - Params: ExtrinsicParams, -{ - signer: Option, - genesis_hash: Runtime::Hash, +pub struct Api { + signer: Option, + genesis_hash: T::Hash, metadata: Metadata, runtime_version: RuntimeVersion, client: Client, - additional_extrinsic_params: Option, + additional_extrinsic_params: + Option<>::AdditionalParams>, } -impl Api -where - Runtime: FrameSystemConfig, - Params: ExtrinsicParams, -{ +impl Api { /// Create a new api instance without any node interaction. pub fn new_offline( - genesis_hash: Runtime::Hash, + genesis_hash: T::Hash, metadata: Metadata, runtime_version: RuntimeVersion, client: Client, @@ -116,17 +109,17 @@ where } /// Set the api signer account. - pub fn set_signer(&mut self, signer: Signer) { + pub fn set_signer(&mut self, signer: T::ExtrinsicSigner) { self.signer = Some(signer); } /// Get the private key pair of the api signer. - pub fn signer(&self) -> Option<&Signer> { + pub fn signer(&self) -> Option<&T::ExtrinsicSigner> { self.signer.as_ref() } /// Get the cached genesis hash of the substrate node. - pub fn genesis_hash(&self) -> Runtime::Hash { + pub fn genesis_hash(&self) -> T::Hash { self.genesis_hash } @@ -151,16 +144,19 @@ where } /// Set the additional params. - pub fn set_additional_params(&mut self, extrinsic_params: Params::AdditionalParams) { - self.additional_extrinsic_params = Some(extrinsic_params); + pub fn set_additional_params( + &mut self, + add_params: >::AdditionalParams, + ) { + self.additional_extrinsic_params = Some(add_params); } /// Get the extrinsic params with the set additional params. If no additional params are set, /// the default is taken. - pub fn extrinsic_params(&self, nonce: Runtime::Index) -> Params { + pub fn extrinsic_params(&self, nonce: T::Index) -> T::ExtrinsicParams { let additional_extrinsic_params = self.additional_extrinsic_params.clone().unwrap_or_default(); - >::new( + T::ExtrinsicParams::new( self.runtime_version.spec_version, self.runtime_version.transaction_version, nonce, @@ -170,11 +166,10 @@ where } } -impl Api +impl Api where + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, { /// Create a new Api client with call to the node to retrieve metadata. #[maybe_async::async_impl] @@ -244,22 +239,20 @@ where } } -impl Api +impl Api where - Signer: SignExtrinsic, + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, { /// Get the public part of the api signer account. - pub fn signer_account(&self) -> Option<&Runtime::AccountId> { + pub fn signer_account(&self) -> Option<&T::AccountId> { let pair = self.signer.as_ref()?; Some(pair.public_account_id()) } /// Get nonce of self signer account. #[maybe_async::maybe_async(?Send)] - pub async fn get_nonce(&self) -> Result { + pub async fn get_nonce(&self) -> Result { let account = self.signer_account().ok_or(Error::NoSigner)?; self.get_account_nonce(account).await } @@ -267,16 +260,15 @@ where /// Private node query methods. They should be used internally only, because the user should retrieve the data from the struct cache. /// If an up-to-date query is necessary, cache should be updated beforehand. -impl Api +impl Api where + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, { /// Get the genesis hash from node via websocket query. #[maybe_async::maybe_async(?Send)] - async fn get_genesis_hash(client: &Client) -> Result { - let genesis: Option = + async fn get_genesis_hash(client: &Client) -> Result { + let genesis: Option = client.request("chain_getBlockHash", rpc_params![Some(0)]).await?; genesis.ok_or(Error::FetchGenesisHash) } @@ -301,12 +293,12 @@ where #[cfg(test)] mod tests { use super::*; - use crate::{ - ac_primitives::{GenericAdditionalParams, PlainTipExtrinsicParams}, - rpc::mocks::RpcClientMock, + use crate::rpc::mocks::RpcClientMock; + use ac_primitives::{ + GenericAdditionalParams, GenericExtrinsicParams, PlainTip, PolkadotConfig, + SubstrateKitchensinkConfig, }; - use kitchensink_runtime::Runtime; - use sp_core::{sr25519::Pair, H256}; + use sp_core::H256; use std::{ collections::{BTreeMap, HashMap}, fs, @@ -317,7 +309,7 @@ mod tests { runtime_version: RuntimeVersion, metadata: Metadata, data: HashMap, - ) -> Api, Runtime> { + ) -> Api { let client = RpcClientMock::new(data); Api::new_offline(genesis_hash, metadata, runtime_version, client) } @@ -342,13 +334,14 @@ mod tests { let nonce = 6; let retrieved_params = api.extrinsic_params(nonce); - let expected_params = PlainTipExtrinsicParams::::new( - runtime_version.spec_version, - runtime_version.transaction_version, - nonce, - genesis_hash, - Default::default(), - ); + let expected_params = + GenericExtrinsicParams::>::new( + runtime_version.spec_version, + runtime_version.transaction_version, + nonce, + genesis_hash, + Default::default(), + ); assert_eq!(expected_params, retrieved_params) } diff --git a/src/api/rpc_api/author.rs b/src/api/rpc_api/author.rs index 917655fdb..2af9dda7e 100644 --- a/src/api/rpc_api/author.rs +++ b/src/api/rpc_api/author.rs @@ -19,11 +19,10 @@ use crate::{ Api, ExtrinsicReport, TransactionStatus, XtStatus, }; use ac_compose_macros::rpc_params; -use ac_primitives::{Bytes, ExtrinsicParams, FrameSystemConfig, UncheckedExtrinsicV4}; +use ac_primitives::{config::Config, Bytes, Hasher, UncheckedExtrinsicV4}; use codec::Encode; use log::*; use serde::de::DeserializeOwned; -use sp_runtime::traits::{Block as BlockTrait, GetRuntimeBlockType, Hash as HashTrait}; pub type TransactionSubscriptionFor = ::Subscription>; @@ -51,13 +50,12 @@ pub trait SubmitExtrinsic { } #[maybe_async::maybe_async(?Send)] -impl SubmitExtrinsic for Api +impl SubmitExtrinsic for Api where + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, { - type Hash = Runtime::Hash; + type Hash = T::Hash; async fn submit_extrinsic( &self, @@ -182,15 +180,13 @@ pub trait SubmitAndWatchUntilSuccess { } #[maybe_async::maybe_async(?Send)] -impl SubmitAndWatch for Api +impl SubmitAndWatch for Api where + T: Config, Client: Subscribe, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, - Runtime::Hashing: HashTrait, { type Client = Client; - type Hash = Runtime::Hash; + type Hash = T::Hash; async fn submit_and_watch_extrinsic( &self, @@ -238,7 +234,7 @@ where encoded_extrinsic: Bytes, watch_until: XtStatus, ) -> Result> { - let tx_hash = Runtime::Hashing::hash_of(&encoded_extrinsic.0); + let tx_hash = T::Hasher::hash_of(&encoded_extrinsic.0); let mut subscription: TransactionSubscriptionFor = self.submit_and_watch_opaque_extrinsic(encoded_extrinsic).await?; @@ -267,18 +263,13 @@ where } #[maybe_async::maybe_async(?Send)] -impl SubmitAndWatchUntilSuccess - for Api +impl SubmitAndWatchUntilSuccess for Api where + T: Config, Client: Subscribe + Request, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig + GetRuntimeBlockType, - Runtime::RuntimeBlock: BlockTrait + DeserializeOwned, - Runtime::Hashing: HashTrait, - Runtime::Header: DeserializeOwned, { type Client = Client; - type Hash = Runtime::Hash; + type Hash = T::Hash; async fn submit_and_watch_extrinsic_until_success( &self, diff --git a/src/api/rpc_api/chain.rs b/src/api/rpc_api/chain.rs index dccfef174..86706bcbc 100644 --- a/src/api/rpc_api/chain.rs +++ b/src/api/rpc_api/chain.rs @@ -17,11 +17,10 @@ use crate::{ Error, }; use ac_compose_macros::rpc_params; -use ac_primitives::{ExtrinsicParams, FrameSystemConfig, SignedBlock}; +use ac_primitives::{config::Config, SignedBlock}; use alloc::vec::Vec; use log::*; use serde::de::DeserializeOwned; -use sp_runtime::traits::GetRuntimeBlockType; #[maybe_async::maybe_async(?Send)] pub trait GetChainInfo { @@ -73,18 +72,15 @@ pub trait GetChainInfo { } #[maybe_async::maybe_async(?Send)] -impl GetChainInfo for Api +impl GetChainInfo for Api where + T: Config, Client: Request, - Runtime: FrameSystemConfig + GetRuntimeBlockType, - Params: ExtrinsicParams, - Runtime::RuntimeBlock: DeserializeOwned, - Runtime::Header: DeserializeOwned, { - type BlockNumber = Runtime::BlockNumber; - type Hash = Runtime::Hash; - type Header = Runtime::Header; - type Block = Runtime::RuntimeBlock; + type BlockNumber = T::BlockNumber; + type Hash = T::Hash; + type Header = T::Header; + type Block = T::Block; async fn get_finalized_head(&self) -> Result> { let finalized_block_hash = @@ -168,15 +164,13 @@ pub trait SubscribeChain { ) -> Result<::Subscription>; } -impl SubscribeChain for Api +impl SubscribeChain for Api where + T: Config, Client: Subscribe, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, - Runtime::Header: DeserializeOwned, { type Client = Client; - type Header = Runtime::Header; + type Header = T::Header; fn subscribe_finalized_heads( &self, diff --git a/src/api/rpc_api/events.rs b/src/api/rpc_api/events.rs index 19193e56a..f0a0dee44 100644 --- a/src/api/rpc_api/events.rs +++ b/src/api/rpc_api/events.rs @@ -18,13 +18,12 @@ use crate::{ }; use ac_compose_macros::rpc_params; use ac_node_api::{metadata::Metadata, EventDetails, EventRecord, Events, Phase}; -use ac_primitives::{ExtrinsicParams, FrameSystemConfig, StorageChangeSet}; +use ac_primitives::{config::Config, Block, Hasher, StorageChangeSet}; use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; use core::marker::PhantomData; use log::*; use serde::de::DeserializeOwned; -use sp_runtime::traits::{Block as BlockTrait, GetRuntimeBlockType, Hash as HashTrait}; pub type EventSubscriptionFor = EventSubscription<::Subscription>, Hash>; @@ -45,16 +44,12 @@ pub trait FetchEvents { } #[maybe_async::maybe_async(?Send)] -impl FetchEvents for Api +impl FetchEvents for Api where + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig + GetRuntimeBlockType, - Runtime::RuntimeBlock: BlockTrait + DeserializeOwned, - Runtime::Hashing: HashTrait, - Runtime::Header: DeserializeOwned, { - type Hash = Runtime::Hash; + type Hash = T::Hash; async fn fetch_events_from_block(&self, block_hash: Self::Hash) -> Result> { let key = crate::storage_key("System", "Events"); @@ -156,14 +151,13 @@ pub trait SubscribeEvents { fn subscribe_events(&self) -> Result>; } -impl SubscribeEvents for Api +impl SubscribeEvents for Api where + T: Config, Client: Subscribe, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, { type Client = Client; - type Hash = Runtime::Hash; + type Hash = T::Hash; fn subscribe_events(&self) -> Result> { let key = crate::storage_key("System", "Events"); @@ -175,28 +169,24 @@ where } } -impl Api +impl Api where + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig + GetRuntimeBlockType, - Runtime::RuntimeBlock: BlockTrait + DeserializeOwned, - Runtime::Hashing: HashTrait, - Runtime::Header: DeserializeOwned, { /// Retrieve block details from node and search for the position of the given extrinsic. #[maybe_async::maybe_async(?Send)] async fn retrieve_extrinsic_index_from_block( &self, - block_hash: Runtime::Hash, - extrinsic_hash: Runtime::Hash, + block_hash: T::Hash, + extrinsic_hash: T::Hash, ) -> Result { let block = self.get_block(Some(block_hash)).await?.ok_or(Error::BlockNotFound)?; let xt_index = block .extrinsics() .iter() .position(|xt| { - let xt_hash = Runtime::Hashing::hash_of(&xt.encode()); + let xt_hash = T::Hasher::hash_of(&xt.encode()); trace!("Looking for: {:?}, got xt_hash {:?}", extrinsic_hash, xt_hash); extrinsic_hash == xt_hash }) @@ -207,7 +197,7 @@ where /// Filter events and return the ones associated to the given extrinsic index. fn filter_extrinsic_events( &self, - events: Events, + events: Events, extrinsic_index: u32, ) -> Result> { let extrinsic_event_results = events.iter().filter(|ev| { @@ -233,14 +223,12 @@ mod tests { use super::*; use crate::rpc::mocks::RpcClientMock; use ac_node_api::{metadata::Metadata, test_utils::*}; - use ac_primitives::{ - AssetTipExtrinsicParams, Bytes, FrameSystemConfig, RuntimeVersion, SignedBlock, StorageData, - }; + use ac_primitives::{Bytes, PolkadotConfig, RuntimeVersion, SignedBlock, StorageData}; use codec::{Decode, Encode}; use frame_metadata::RuntimeMetadataPrefixed; - use kitchensink_runtime::{BalancesCall, Runtime, RuntimeCall, UncheckedExtrinsic}; + use kitchensink_runtime::{BalancesCall, RuntimeCall, UncheckedExtrinsic}; use scale_info::TypeInfo; - use sp_core::{crypto::Ss58Codec, sr25519, sr25519::Pair, H256}; + use sp_core::{crypto::Ss58Codec, sr25519, H256}; use sp_runtime::{generic::Block, AccountId32, MultiAddress}; use std::{collections::HashMap, fs}; @@ -253,7 +241,7 @@ mod tests { fn create_mock_api( metadata: Metadata, data: HashMap, - ) -> Api, Runtime> { + ) -> Api { // Create new api. let genesis_hash = H256::random(); let runtime_version = RuntimeVersion::default(); @@ -376,9 +364,9 @@ mod tests { let xt2: Bytes = UncheckedExtrinsic::new_unsigned(call2).encode().into(); let xt3: Bytes = UncheckedExtrinsic::new_unsigned(call3).encode().into(); - let xt_hash1 = ::Hashing::hash_of(&xt1.0); - let xt_hash2 = ::Hashing::hash_of(&xt2.0); - let xt_hash3 = ::Hashing::hash_of(&xt3.0); + let xt_hash1 = ::Hasher::hash_of(&xt1.0); + let xt_hash2 = ::Hasher::hash_of(&xt2.0); + let xt_hash3 = ::Hasher::hash_of(&xt3.0); let block = Block { header: default_header(), extrinsics: vec![xt1, xt2, xt3] }; let signed_block = SignedBlock { block, justifications: None }; diff --git a/src/api/rpc_api/frame_system.rs b/src/api/rpc_api/frame_system.rs index de7c7e963..59998b26e 100644 --- a/src/api/rpc_api/frame_system.rs +++ b/src/api/rpc_api/frame_system.rs @@ -18,7 +18,7 @@ use crate::{ rpc::Request, }; use ac_compose_macros::rpc_params; -use ac_primitives::{AccountInfo, ExtrinsicParams, FrameSystemConfig, StorageKey}; +use ac_primitives::{config::Config, AccountInfo, StorageKey}; use alloc::{string::String, vec::Vec}; use log::*; @@ -43,15 +43,14 @@ pub trait GetAccountInformation { } #[maybe_async::maybe_async(?Send)] -impl GetAccountInformation for Api +impl GetAccountInformation for Api where + T: Config, Client: Request, - Runtime: FrameSystemConfig, - Params: ExtrinsicParams, { - type AccountId = Runtime::AccountId; - type Index = Runtime::Index; - type AccountData = Runtime::AccountData; + type AccountId = T::AccountId; + type Index = T::Index; + type AccountData = T::AccountData; async fn get_account_info( &self, @@ -121,11 +120,10 @@ pub trait SystemApi { } #[maybe_async::maybe_async(?Send)] -impl SystemApi for Api +impl SystemApi for Api where + T: Config, Client: Request, - Runtime: FrameSystemConfig, - Params: ExtrinsicParams, { type ChainType = ac_primitives::ChainType; type Properties = ac_primitives::Properties; diff --git a/src/api/rpc_api/pallet_balances.rs b/src/api/rpc_api/pallet_balances.rs index c902f48a8..af3b88a8d 100644 --- a/src/api/rpc_api/pallet_balances.rs +++ b/src/api/rpc_api/pallet_balances.rs @@ -14,7 +14,7 @@ use crate::{ api::{Api, GetStorage, Result}, rpc::Request, }; -use ac_primitives::{BalancesConfig, ExtrinsicParams}; +use ac_primitives::config::Config; /// Interface to common calls of the substrate balances pallet. #[maybe_async::maybe_async(?Send)] @@ -25,13 +25,12 @@ pub trait GetBalance { } #[maybe_async::maybe_async(?Send)] -impl GetBalance for Api +impl GetBalance for Api where + T: Config, Client: Request, - Runtime: BalancesConfig, - Params: ExtrinsicParams, { - type Balance = Runtime::Balance; + type Balance = T::Balance; async fn get_existential_deposit(&self) -> Result { self.get_constant("Balances", "ExistentialDeposit").await diff --git a/src/api/rpc_api/pallet_transaction_payment.rs b/src/api/rpc_api/pallet_transaction_payment.rs index 25a2b57ee..251508a9e 100644 --- a/src/api/rpc_api/pallet_transaction_payment.rs +++ b/src/api/rpc_api/pallet_transaction_payment.rs @@ -16,8 +16,7 @@ use crate::{ }; use ac_compose_macros::rpc_params; use ac_primitives::{ - BalancesConfig, Bytes, ExtrinsicParams, FeeDetails, InclusionFee, NumberOrHex, - RuntimeDispatchInfo, + config::Config, Bytes, FeeDetails, InclusionFee, NumberOrHex, RuntimeDispatchInfo, }; use core::str::FromStr; @@ -41,15 +40,14 @@ pub trait GetTransactionPayment { } #[maybe_async::maybe_async(?Send)] -impl GetTransactionPayment for Api +impl GetTransactionPayment for Api where + T: Config, Client: Request, - Runtime: BalancesConfig, - Params: ExtrinsicParams, - Runtime::Balance: TryFrom + FromStr, + T::Balance: TryFrom + FromStr, { - type Hash = Runtime::Hash; - type Balance = Runtime::Balance; + type Hash = T::Hash; + type Balance = T::Balance; async fn get_fee_details( &self, diff --git a/src/api/rpc_api/state.rs b/src/api/rpc_api/state.rs index 449e56a3f..a2820104c 100644 --- a/src/api/rpc_api/state.rs +++ b/src/api/rpc_api/state.rs @@ -17,9 +17,7 @@ use crate::{ }; use ac_compose_macros::rpc_params; use ac_node_api::MetadataError; -use ac_primitives::{ - ExtrinsicParams, FrameSystemConfig, StorageChangeSet, StorageData, StorageKey, -}; +use ac_primitives::{config::Config, StorageChangeSet, StorageData, StorageKey}; use alloc::{string::String, vec, vec::Vec}; use codec::{Decode, Encode}; use log::*; @@ -159,13 +157,12 @@ pub trait GetStorage { } #[maybe_async::maybe_async(?Send)] -impl GetStorage for Api +impl GetStorage for Api where + T: Config, Client: Request, - Runtime: FrameSystemConfig, - Params: ExtrinsicParams, { - type Hash = Runtime::Hash; + type Hash = T::Hash; async fn get_storage( &self, @@ -350,14 +347,13 @@ pub trait SubscribeState { ) -> Result>; } -impl SubscribeState for Api +impl SubscribeState for Api where + T: Config, Client: Subscribe, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, { type Client = Client; - type Hash = Runtime::Hash; + type Hash = T::Hash; fn subscribe_state( &self, diff --git a/src/extrinsic/balances.rs b/src/extrinsic/balances.rs index 6c7230aa7..3ce2a3c98 100644 --- a/src/extrinsic/balances.rs +++ b/src/extrinsic/balances.rs @@ -21,7 +21,8 @@ use crate::{api::Api, rpc::Request}; use ac_compose_macros::compose_extrinsic; use ac_primitives::{ - BalancesConfig, CallIndex, ExtrinsicParams, SignExtrinsic, UncheckedExtrinsicV4, + config::Config, extrinsic_params::ExtrinsicParams, extrinsics::CallIndex, SignExtrinsic, + UncheckedExtrinsicV4, }; use alloc::borrow::ToOwned; use codec::{Compact, Encode}; @@ -58,18 +59,20 @@ pub trait BalancesExtrinsics { } #[maybe_async::maybe_async(?Send)] -impl BalancesExtrinsics for Api +impl BalancesExtrinsics for Api where - Signer: SignExtrinsic, + T: Config, Client: Request, - Runtime: BalancesConfig, - Params: ExtrinsicParams, - Compact: Encode, + Compact: Encode, { - type Balance = Runtime::Balance; - type Address = Signer::ExtrinsicAddress; - type Extrinsic = - UncheckedExtrinsicV4; + type Balance = T::Balance; + type Address = >::ExtrinsicAddress; + type Extrinsic = UncheckedExtrinsicV4< + Self::Address, + Call, + >::Signature, + >::SignedExtra, + >; async fn balance_transfer_allow_death( &self, diff --git a/src/extrinsic/contracts.rs b/src/extrinsic/contracts.rs index f3fcac77c..e4cb6ea4b 100644 --- a/src/extrinsic/contracts.rs +++ b/src/extrinsic/contracts.rs @@ -24,7 +24,7 @@ use crate::{api::Api, rpc::Request}; use ac_compose_macros::compose_extrinsic; use ac_primitives::{ - CallIndex, ContractsConfig, ExtrinsicParams, FrameSystemConfig, SignExtrinsic, + config::Config, extrinsic_params::ExtrinsicParams, extrinsics::CallIndex, SignExtrinsic, UncheckedExtrinsicV4, }; use alloc::vec::Vec; @@ -102,31 +102,27 @@ pub trait ContractsExtrinsics { ) -> Self::Extrinsic>; } -#[cfg(feature = "std")] -type BalanceOf = <::Currency as frame_support::traits::Currency< - ::AccountId, ->>::Balance; - #[cfg(feature = "std")] #[maybe_async::maybe_async(?Send)] -impl ContractsExtrinsics for Api +impl ContractsExtrinsics for Api where - Signer: SignExtrinsic, + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: ContractsConfig, - Compact>: Encode + Clone, - Runtime::Currency: frame_support::traits::Currency, + Compact: Encode + Clone, { type Gas = u64; - type Currency = BalanceOf; - type Hash = Runtime::Hash; + type Currency = T::ContractCurrency; + type Hash = T::Hash; type Code = Vec; type Data = Vec; type Salt = Vec; - type Address = Signer::ExtrinsicAddress; - type Extrinsic = - UncheckedExtrinsicV4; + type Address = >::ExtrinsicAddress; + type Extrinsic = UncheckedExtrinsicV4< + Self::Address, + Call, + >::Signature, + >::SignedExtra, + >; async fn contract_put_code( &self, diff --git a/src/extrinsic/offline_extrinsic.rs b/src/extrinsic/offline_extrinsic.rs index 7ef57e8a2..f9e5e2163 100644 --- a/src/extrinsic/offline_extrinsic.rs +++ b/src/extrinsic/offline_extrinsic.rs @@ -19,22 +19,27 @@ use crate::Api; use ac_compose_macros::compose_extrinsic_offline; -use ac_primitives::{ExtrinsicParams, FrameSystemConfig, SignExtrinsic, UncheckedExtrinsicV4}; +use ac_primitives::{ + config::Config, extrinsic_params::ExtrinsicParams, SignExtrinsic, UncheckedExtrinsicV4, +}; use codec::Encode; -impl Api -where - Signer: SignExtrinsic, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, -{ +type ExtrinsicAddress = + <::ExtrinsicSigner as SignExtrinsic<::AccountId>>::ExtrinsicAddress; +type Signature = + <::ExtrinsicSigner as SignExtrinsic<::AccountId>>::Signature; +type SignedExtra = <::ExtrinsicParams as ExtrinsicParams< + ::Index, + ::Hash, +>>::SignedExtra; + +impl Api { /// Wrapper around the `compose_extrinsic_offline!` macro to be less verbose. pub fn compose_extrinsic_offline( &self, call: Call, - nonce: Runtime::Index, - ) -> UncheckedExtrinsicV4 - { + nonce: T::Index, + ) -> UncheckedExtrinsicV4, Call, Signature, SignedExtra> { match self.signer() { Some(signer) => compose_extrinsic_offline!(signer, call, self.extrinsic_params(nonce)), None => UncheckedExtrinsicV4 { signature: None, function: call }, diff --git a/src/extrinsic/staking.rs b/src/extrinsic/staking.rs index ce23f6dcb..e23285716 100644 --- a/src/extrinsic/staking.rs +++ b/src/extrinsic/staking.rs @@ -21,7 +21,7 @@ use crate::{rpc::Request, Api}; use ac_compose_macros::compose_extrinsic; use ac_primitives::{ - CallIndex, ExtrinsicParams, RewardDestination, SignExtrinsic, StakingConfig, + config::Config, CallIndex, ExtrinsicParams, RewardDestination, SignExtrinsic, UncheckedExtrinsicV4, }; use codec::{Compact, Decode, Encode}; @@ -151,20 +151,22 @@ pub trait StakingExtrinsics { } #[maybe_async::maybe_async(?Send)] -impl StakingExtrinsics for Api +impl StakingExtrinsics for Api where - Signer: SignExtrinsic, + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: StakingConfig, - Compact: Encode, + Compact: Encode, { - type Balance = Runtime::CurrencyBalance; + type Balance = T::StakingBalance; type RewardDestination = RewardDestination; - type AccountId = Runtime::AccountId; - type Address = Signer::ExtrinsicAddress; - type Extrinsic = - UncheckedExtrinsicV4; + type AccountId = T::AccountId; + type Address = >::ExtrinsicAddress; + type Extrinsic = UncheckedExtrinsicV4< + Self::Address, + Call, + >::Signature, + >::SignedExtra, + >; async fn staking_bond( &self, diff --git a/src/extrinsic/utility.rs b/src/extrinsic/utility.rs index 967d609dc..2a3168dfd 100644 --- a/src/extrinsic/utility.rs +++ b/src/extrinsic/utility.rs @@ -21,7 +21,8 @@ use crate::{rpc::Request, Api}; use ac_compose_macros::compose_extrinsic; use ac_primitives::{ - CallIndex, ExtrinsicParams, FrameSystemConfig, SignExtrinsic, UncheckedExtrinsicV4, + config::Config, extrinsic_params::ExtrinsicParams, extrinsics::CallIndex, SignExtrinsic, + UncheckedExtrinsicV4, }; use alloc::{borrow::ToOwned, vec::Vec}; use codec::{Decode, Encode}; @@ -55,18 +56,16 @@ pub trait UtilityExtrinsics { } #[maybe_async::maybe_async(?Send)] -impl UtilityExtrinsics for Api +impl UtilityExtrinsics for Api where - Signer: SignExtrinsic, + T: Config, Client: Request, - Params: ExtrinsicParams, - Runtime: FrameSystemConfig, { type Extrinsic = UncheckedExtrinsicV4< - Signer::ExtrinsicAddress, + >::ExtrinsicAddress, Call, - Signer::Signature, - Params::SignedExtra, + >::Signature, + >::SignedExtra, >; async fn batch( diff --git a/testing/examples/author_tests.rs b/testing/examples/author_tests.rs index b844cfb4e..2a014dd2d 100644 --- a/testing/examples/author_tests.rs +++ b/testing/examples/author_tests.rs @@ -15,21 +15,20 @@ //! Tests for the author rpc interface functions. -use kitchensink_runtime::{AccountId, Runtime, Signature}; -use sp_core::sr25519::Pair; +use kitchensink_runtime::AccountId; use sp_keyring::AccountKeyring; use std::{thread, time::Duration}; use substrate_api_client::{ ac_node_api::EventDetails, ac_primitives::{ - AssetTipExtrinsicParams, ExtrinsicSigner as GenericExtrinsicSigner, SignExtrinsic, + ExtrinsicSigner as GenericExtrinsicSigner, SignExtrinsic, SubstrateKitchensinkConfig, }, extrinsic::BalancesExtrinsics, rpc::{HandleSubscription, JsonrpseeClient}, Api, SubmitAndWatch, SubmitAndWatchUntilSuccess, SubmitExtrinsic, TransactionStatus, XtStatus, }; -type ExtrinsicSigner = GenericExtrinsicSigner; +type ExtrinsicSigner = GenericExtrinsicSigner; type ExtrinsicAddressOf = >::ExtrinsicAddress; #[tokio::main] @@ -37,7 +36,8 @@ async fn main() { // Setup let client = JsonrpseeClient::with_default_url().unwrap(); let alice_pair = AccountKeyring::Alice.pair(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::new(alice_pair)); let bob: ExtrinsicAddressOf = AccountKeyring::Bob.to_account_id().into(); diff --git a/testing/examples/chain_tests.rs b/testing/examples/chain_tests.rs index 02bebaa6d..c612a7972 100644 --- a/testing/examples/chain_tests.rs +++ b/testing/examples/chain_tests.rs @@ -15,10 +15,8 @@ //! Tests for the chain rpc interface functions. -use kitchensink_runtime::Runtime; -use sp_keyring::AccountKeyring; use substrate_api_client::{ - ac_primitives::AssetTipExtrinsicParams, + ac_primitives::SubstrateKitchensinkConfig, rpc::{HandleSubscription, JsonrpseeClient}, Api, GetChainInfo, SubscribeChain, }; @@ -27,9 +25,7 @@ use substrate_api_client::{ async fn main() { // Setup let client = JsonrpseeClient::with_default_url().unwrap(); - let alice_pair = AccountKeyring::Alice.pair(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(alice_pair); + let api = Api::::new(client).unwrap(); // GetChainInfo let finalized_header_hash = api.get_finalized_head().unwrap().unwrap(); diff --git a/testing/examples/events_tests.rs b/testing/examples/events_tests.rs index 1eea28cad..66454ece0 100644 --- a/testing/examples/events_tests.rs +++ b/testing/examples/events_tests.rs @@ -17,11 +17,11 @@ use codec::Decode; use frame_support::dispatch::DispatchInfo; -use kitchensink_runtime::{Runtime, RuntimeEvent, Signature}; +use kitchensink_runtime::RuntimeEvent; use sp_keyring::AccountKeyring; use substrate_api_client::{ ac_node_api::{EventDetails, StaticEvent}, - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner, FrameSystemConfig}, + ac_primitives::{Config, ExtrinsicSigner, SubstrateKitchensinkConfig}, extrinsic::BalancesExtrinsics, rpc::JsonrpseeClient, Api, FetchEvents, GetChainInfo, SubmitAndWatch, SubscribeEvents, XtStatus, @@ -43,8 +43,8 @@ async fn main() { // Setup let client = JsonrpseeClient::with_default_url().unwrap(); let alice_pair = AccountKeyring::Alice.pair(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(alice_pair)); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::::new(alice_pair)); let bob = AccountKeyring::Bob.to_account_id(); @@ -70,7 +70,7 @@ async fn main() { // Wait for event callbacks from the node, which are received via subscription. for _ in 0..5 { let event_records = event_subscription - .next_events::::Hash>() + .next_events::::Hash>() .unwrap() .unwrap(); for event_record in &event_records { diff --git a/testing/examples/frame_system_tests.rs b/testing/examples/frame_system_tests.rs index 8cc2543fa..25cfa7626 100644 --- a/testing/examples/frame_system_tests.rs +++ b/testing/examples/frame_system_tests.rs @@ -17,11 +17,10 @@ use codec::Decode; use frame_support::dispatch::DispatchInfo; -use kitchensink_runtime::{Runtime, Signature}; use sp_keyring::AccountKeyring; use substrate_api_client::{ ac_node_api::StaticEvent, - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner}, + ac_primitives::{ExtrinsicSigner, SubstrateKitchensinkConfig}, rpc::JsonrpseeClient, Api, GetAccountInformation, SystemApi, }; @@ -42,8 +41,8 @@ async fn main() { // Setup let client = JsonrpseeClient::with_default_url().unwrap(); let alice_pair = AccountKeyring::Alice.pair(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(alice_pair)); + let mut api = Api::::new(client).unwrap(); + api.set_signer(ExtrinsicSigner::new(alice_pair)); let alice = AccountKeyring::Alice.to_account_id(); diff --git a/testing/examples/pallet_balances_tests.rs b/testing/examples/pallet_balances_tests.rs index e94486f25..4946ceca1 100644 --- a/testing/examples/pallet_balances_tests.rs +++ b/testing/examples/pallet_balances_tests.rs @@ -15,19 +15,15 @@ //! Tests for the pallet balances interface functions. -use kitchensink_runtime::Runtime; -use sp_keyring::AccountKeyring; use substrate_api_client::{ - ac_primitives::AssetTipExtrinsicParams, rpc::JsonrpseeClient, Api, GetBalance, + ac_primitives::SubstrateKitchensinkConfig, rpc::JsonrpseeClient, Api, GetBalance, }; #[tokio::main] async fn main() { // Setup let client = JsonrpseeClient::with_default_url().unwrap(); - let alice_pair = AccountKeyring::Alice.pair(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(alice_pair); + let api = Api::::new(client).unwrap(); let _ed = api.get_existential_deposit().unwrap(); } diff --git a/testing/examples/pallet_transaction_payment_tests.rs b/testing/examples/pallet_transaction_payment_tests.rs index faea9c8e6..99c8d1c2f 100644 --- a/testing/examples/pallet_transaction_payment_tests.rs +++ b/testing/examples/pallet_transaction_payment_tests.rs @@ -16,12 +16,9 @@ //! Tests for the pallet transaction payment interface functions. use codec::Encode; -use kitchensink_runtime::{Runtime, Signature}; use sp_keyring::AccountKeyring; use substrate_api_client::{ - ac_primitives::{AssetTipExtrinsicParams, ExtrinsicSigner}, - extrinsic::BalancesExtrinsics, - rpc::JsonrpseeClient, + ac_primitives::SubstrateKitchensinkConfig, extrinsic::BalancesExtrinsics, rpc::JsonrpseeClient, Api, GetChainInfo, GetTransactionPayment, }; @@ -30,8 +27,8 @@ async fn main() { // Setup let client = JsonrpseeClient::with_default_url().unwrap(); let alice_pair = AccountKeyring::Alice.pair(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(ExtrinsicSigner::<_, Signature, Runtime>::new(alice_pair)); + let mut api = Api::::new(client).unwrap(); + api.set_signer(alice_pair.into()); let bob = AccountKeyring::Bob.to_account_id(); diff --git a/testing/examples/state_tests.rs b/testing/examples/state_tests.rs index cf46fe6a0..73090186c 100644 --- a/testing/examples/state_tests.rs +++ b/testing/examples/state_tests.rs @@ -16,30 +16,30 @@ //! Tests for the state rpc interface functions. use codec::Decode; -use kitchensink_runtime::Runtime; use pallet_balances::AccountData as GenericAccountData; use pallet_staking::Exposure; use sp_core::{crypto::Ss58Codec, sr25519}; use sp_keyring::AccountKeyring; use sp_staking::EraIndex; use substrate_api_client::{ - ac_primitives::AssetTipExtrinsicParams, rpc::JsonrpseeClient, Api, GetChainInfo, GetStorage, + ac_primitives::{Config, SubstrateKitchensinkConfig}, + rpc::JsonrpseeClient, + Api, GetChainInfo, GetStorage, }; -type Balance = ::Balance; +type KitchensinkConfig = SubstrateKitchensinkConfig; +type Balance = ::Balance; type AccountData = GenericAccountData; type ErasStakers = Exposure< - ::AccountId, - ::CurrencyBalance, + ::AccountId, + ::StakingBalance, >; #[tokio::main] async fn main() { // Setup let client = JsonrpseeClient::with_default_url().unwrap(); - let alice_pair = AccountKeyring::Alice.pair(); - let mut api = Api::<_, _, AssetTipExtrinsicParams, Runtime>::new(client).unwrap(); - api.set_signer(alice_pair); + let api = Api::::new(client).unwrap(); let alice = AccountKeyring::Alice.to_account_id(); let block_hash = api.get_block_hash(None).unwrap().unwrap();