Merge pull request #8 from OpenZeppelin/plain-cumulus-fmt

cargo fmt on plain-cumulus template
This commit is contained in:
Özgün Özerk
2023-11-15 17:43:47 +03:00
committed by GitHub
18 changed files with 1712 additions and 1697 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() { fn main() {
generate_cargo_keys(); generate_cargo_keys();
rerun_if_git_head_changed(); rerun_if_git_head_changed();
} }
+177 -175
View File
@@ -8,224 +8,226 @@ use sp_runtime::traits::{IdentifyAccount, Verify};
/// Specialized `ChainSpec` for the normal parachain runtime. /// Specialized `ChainSpec` for the normal parachain runtime.
pub type ChainSpec = pub type ChainSpec =
sc_service::GenericChainSpec<parachain_template_runtime::RuntimeGenesisConfig, Extensions>; sc_service::GenericChainSpec<parachain_template_runtime::RuntimeGenesisConfig, Extensions>;
/// The default XCM version to set in genesis config. /// The default XCM version to set in genesis config.
const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION;
/// Helper function to generate a crypto pair from seed /// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public { pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None) TPublic::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed") .expect("static values are valid; qed")
.public() .public()
} }
/// The extensions for the [`ChainSpec`]. /// The extensions for the [`ChainSpec`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct Extensions { pub struct Extensions {
/// The relay chain of the Parachain. /// The relay chain of the Parachain.
pub relay_chain: String, pub relay_chain: String,
/// The id of the Parachain. /// The id of the Parachain.
pub para_id: u32, pub para_id: u32,
} }
impl Extensions { impl Extensions {
/// Try to get the extension from the given `ChainSpec`. /// Try to get the extension from the given `ChainSpec`.
pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> { pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {
sc_chain_spec::get_extension(chain_spec.extensions()) sc_chain_spec::get_extension(chain_spec.extensions())
} }
} }
type AccountPublic = <Signature as Verify>::Signer; type AccountPublic = <Signature as Verify>::Signer;
/// Generate collator keys from seed. /// Generate collator keys from seed.
/// ///
/// This function's return type must always match the session keys of the chain in tuple format. /// This function's return type must always match the session keys of the chain
/// in tuple format.
pub fn get_collator_keys_from_seed(seed: &str) -> AuraId { pub fn get_collator_keys_from_seed(seed: &str) -> AuraId {
get_from_seed::<AuraId>(seed) get_from_seed::<AuraId>(seed)
} }
/// Helper function to generate an account ID from seed /// Helper function to generate an account ID from seed
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where where
AccountPublic: From<<TPublic::Pair as Pair>::Public>, AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{ {
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account() AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
} }
/// Generate the session keys from individual elements. /// Generate the session keys from individual elements.
/// ///
/// The input must be a tuple of individual keys (a single arg for now since we have just one key). /// The input must be a tuple of individual keys (a single arg for now since we
/// have just one key).
pub fn template_session_keys(keys: AuraId) -> parachain_template_runtime::SessionKeys { pub fn template_session_keys(keys: AuraId) -> parachain_template_runtime::SessionKeys {
parachain_template_runtime::SessionKeys { aura: keys } parachain_template_runtime::SessionKeys { aura: keys }
} }
pub fn development_config() -> ChainSpec { pub fn development_config() -> ChainSpec {
// Give your base currency a unit name and decimal places // Give your base currency a unit name and decimal places
let mut properties = sc_chain_spec::Properties::new(); let mut properties = sc_chain_spec::Properties::new();
properties.insert("tokenSymbol".into(), "UNIT".into()); properties.insert("tokenSymbol".into(), "UNIT".into());
properties.insert("tokenDecimals".into(), 12.into()); properties.insert("tokenDecimals".into(), 12.into());
properties.insert("ss58Format".into(), 42.into()); properties.insert("ss58Format".into(), 42.into());
ChainSpec::from_genesis( ChainSpec::from_genesis(
// Name // Name
"Development", "Development",
// ID // ID
"dev", "dev",
ChainType::Development, ChainType::Development,
move || { move || {
testnet_genesis( testnet_genesis(
// initial collators. // initial collators.
vec![ vec![
( (
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
get_collator_keys_from_seed("Alice"), get_collator_keys_from_seed("Alice"),
), ),
( (
get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Bob"),
get_collator_keys_from_seed("Bob"), get_collator_keys_from_seed("Bob"),
), ),
], ],
vec![ vec![
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Charlie"), get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Dave"), get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Eve"), get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Ferdie"), get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"), get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"), get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
], ],
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
1000.into(), 1000.into(),
) )
}, },
Vec::new(), Vec::new(),
None, None,
None, None,
None, None,
None, None,
Extensions { Extensions {
relay_chain: "rococo-local".into(), // You MUST set this to the correct network! relay_chain: "rococo-local".into(), // You MUST set this to the correct network!
para_id: 1000, para_id: 1000,
}, },
) )
} }
pub fn local_testnet_config() -> ChainSpec { pub fn local_testnet_config() -> ChainSpec {
// Give your base currency a unit name and decimal places // Give your base currency a unit name and decimal places
let mut properties = sc_chain_spec::Properties::new(); let mut properties = sc_chain_spec::Properties::new();
properties.insert("tokenSymbol".into(), "UNIT".into()); properties.insert("tokenSymbol".into(), "UNIT".into());
properties.insert("tokenDecimals".into(), 12.into()); properties.insert("tokenDecimals".into(), 12.into());
properties.insert("ss58Format".into(), 42.into()); properties.insert("ss58Format".into(), 42.into());
ChainSpec::from_genesis( ChainSpec::from_genesis(
// Name // Name
"Local Testnet", "Local Testnet",
// ID // ID
"local_testnet", "local_testnet",
ChainType::Local, ChainType::Local,
move || { move || {
testnet_genesis( testnet_genesis(
// initial collators. // initial collators.
vec![ vec![
( (
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
get_collator_keys_from_seed("Alice"), get_collator_keys_from_seed("Alice"),
), ),
( (
get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Bob"),
get_collator_keys_from_seed("Bob"), get_collator_keys_from_seed("Bob"),
), ),
], ],
vec![ vec![
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Charlie"), get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Dave"), get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Eve"), get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Ferdie"), get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"), get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"), get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
], ],
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
1000.into(), 1000.into(),
) )
}, },
// Bootnodes // Bootnodes
Vec::new(), Vec::new(),
// Telemetry // Telemetry
None, None,
// Protocol ID // Protocol ID
Some("template-local"), Some("template-local"),
// Fork ID // Fork ID
None, None,
// Properties // Properties
Some(properties), Some(properties),
// Extensions // Extensions
Extensions { Extensions {
relay_chain: "rococo-local".into(), // You MUST set this to the correct network! relay_chain: "rococo-local".into(), // You MUST set this to the correct network!
para_id: 1000, para_id: 1000,
}, },
) )
} }
fn testnet_genesis( fn testnet_genesis(
invulnerables: Vec<(AccountId, AuraId)>, invulnerables: Vec<(AccountId, AuraId)>,
endowed_accounts: Vec<AccountId>, endowed_accounts: Vec<AccountId>,
root: AccountId, root: AccountId,
id: ParaId, id: ParaId,
) -> parachain_template_runtime::RuntimeGenesisConfig { ) -> parachain_template_runtime::RuntimeGenesisConfig {
parachain_template_runtime::RuntimeGenesisConfig { parachain_template_runtime::RuntimeGenesisConfig {
system: parachain_template_runtime::SystemConfig { system: parachain_template_runtime::SystemConfig {
code: parachain_template_runtime::WASM_BINARY code: parachain_template_runtime::WASM_BINARY
.expect("WASM binary was not build, please build it!") .expect("WASM binary was not build, please build it!")
.to_vec(), .to_vec(),
..Default::default() ..Default::default()
}, },
balances: parachain_template_runtime::BalancesConfig { balances: parachain_template_runtime::BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(), balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(),
}, },
parachain_info: parachain_template_runtime::ParachainInfoConfig { parachain_info: parachain_template_runtime::ParachainInfoConfig {
parachain_id: id, parachain_id: id,
..Default::default() ..Default::default()
}, },
collator_selection: parachain_template_runtime::CollatorSelectionConfig { collator_selection: parachain_template_runtime::CollatorSelectionConfig {
invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(),
candidacy_bond: EXISTENTIAL_DEPOSIT * 16, candidacy_bond: EXISTENTIAL_DEPOSIT * 16,
..Default::default() ..Default::default()
}, },
session: parachain_template_runtime::SessionConfig { session: parachain_template_runtime::SessionConfig {
keys: invulnerables keys: invulnerables
.into_iter() .into_iter()
.map(|(acc, aura)| { .map(|(acc, aura)| {
( (
acc.clone(), // account id acc.clone(), // account id
acc, // validator id acc, // validator id
template_session_keys(aura), // session keys template_session_keys(aura), // session keys
) )
}) })
.collect(), .collect(),
}, },
// no need to pass anything to aura, in fact it will panic if we do. Session will take care // no need to pass anything to aura, in fact it will panic if we do. Session will take care
// of this. // of this.
aura: Default::default(), aura: Default::default(),
aura_ext: Default::default(), aura_ext: Default::default(),
parachain_system: Default::default(), parachain_system: Default::default(),
polkadot_xcm: parachain_template_runtime::PolkadotXcmConfig { polkadot_xcm: parachain_template_runtime::PolkadotXcmConfig {
safe_xcm_version: Some(SAFE_XCM_VERSION), safe_xcm_version: Some(SAFE_XCM_VERSION),
..Default::default() ..Default::default()
}, },
transaction_payment: Default::default(), transaction_payment: Default::default(),
sudo: parachain_template_runtime::SudoConfig { key: Some(root) }, sudo: parachain_template_runtime::SudoConfig { key: Some(root) },
} }
} }
+68 -66
View File
@@ -3,46 +3,47 @@ use std::path::PathBuf;
/// Sub-commands supported by the collator. /// Sub-commands supported by the collator.
#[derive(Debug, clap::Subcommand)] #[derive(Debug, clap::Subcommand)]
pub enum Subcommand { pub enum Subcommand {
/// Build a chain specification. /// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd), BuildSpec(sc_cli::BuildSpecCmd),
/// Validate blocks. /// Validate blocks.
CheckBlock(sc_cli::CheckBlockCmd), CheckBlock(sc_cli::CheckBlockCmd),
/// Export blocks. /// Export blocks.
ExportBlocks(sc_cli::ExportBlocksCmd), ExportBlocks(sc_cli::ExportBlocksCmd),
/// Export the state of a given block into a chain spec. /// Export the state of a given block into a chain spec.
ExportState(sc_cli::ExportStateCmd), ExportState(sc_cli::ExportStateCmd),
/// Import blocks. /// Import blocks.
ImportBlocks(sc_cli::ImportBlocksCmd), ImportBlocks(sc_cli::ImportBlocksCmd),
/// Revert the chain to a previous state. /// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd), Revert(sc_cli::RevertCmd),
/// Remove the whole chain. /// Remove the whole chain.
PurgeChain(cumulus_client_cli::PurgeChainCmd), PurgeChain(cumulus_client_cli::PurgeChainCmd),
/// Export the genesis state of the parachain. /// Export the genesis state of the parachain.
ExportGenesisState(cumulus_client_cli::ExportGenesisStateCommand), ExportGenesisState(cumulus_client_cli::ExportGenesisStateCommand),
/// Export the genesis wasm of the parachain. /// Export the genesis wasm of the parachain.
ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand),
/// Sub-commands concerned with benchmarking. /// Sub-commands concerned with benchmarking.
/// The pallet benchmarking moved to the `pallet` sub-command. /// The pallet benchmarking moved to the `pallet` sub-command.
#[command(subcommand)] #[command(subcommand)]
Benchmark(frame_benchmarking_cli::BenchmarkCmd), Benchmark(frame_benchmarking_cli::BenchmarkCmd),
/// Try-runtime has migrated to a standalone /// Try-runtime has migrated to a standalone
/// [CLI](<https://github.com/paritytech/try-runtime-cli>). The subcommand exists as a stub and /// [CLI](<https://github.com/paritytech/try-runtime-cli>). The subcommand exists as a stub and
/// deprecation notice. It will be removed entirely some time after Janurary 2024. /// deprecation notice. It will be removed entirely some time after Janurary
TryRuntime, /// 2024.
TryRuntime,
} }
const AFTER_HELP_EXAMPLE: &str = color_print::cstr!( const AFTER_HELP_EXAMPLE: &str = color_print::cstr!(
r#"<bold><underline>Examples:</></> r#"<bold><underline>Examples:</></>
<bold>parachain-template-node build-spec --disable-default-bootnode > plain-parachain-chainspec.json</> <bold>parachain-template-node build-spec --disable-default-bootnode > plain-parachain-chainspec.json</>
Export a chainspec for a local testnet in json format. Export a chainspec for a local testnet in json format.
<bold>parachain-template-node --chain plain-parachain-chainspec.json --tmp -- --chain rococo-local</> <bold>parachain-template-node --chain plain-parachain-chainspec.json --tmp -- --chain rococo-local</>
@@ -55,58 +56,59 @@ const AFTER_HELP_EXAMPLE: &str = color_print::cstr!(
); );
#[derive(Debug, clap::Parser)] #[derive(Debug, clap::Parser)]
#[command( #[command(
propagate_version = true, propagate_version = true,
args_conflicts_with_subcommands = true, args_conflicts_with_subcommands = true,
subcommand_negates_reqs = true subcommand_negates_reqs = true
)] )]
#[clap(after_help = AFTER_HELP_EXAMPLE)] #[clap(after_help = AFTER_HELP_EXAMPLE)]
pub struct Cli { pub struct Cli {
#[command(subcommand)] #[command(subcommand)]
pub subcommand: Option<Subcommand>, pub subcommand: Option<Subcommand>,
#[command(flatten)] #[command(flatten)]
pub run: cumulus_client_cli::RunCmd, pub run: cumulus_client_cli::RunCmd,
/// Disable automatic hardware benchmarks. /// Disable automatic hardware benchmarks.
/// ///
/// By default these benchmarks are automatically ran at startup and measure /// By default these benchmarks are automatically ran at startup and measure
/// the CPU speed, the memory bandwidth and the disk speed. /// the CPU speed, the memory bandwidth and the disk speed.
/// ///
/// The results are then printed out in the logs, and also sent as part of /// The results are then printed out in the logs, and also sent as part of
/// telemetry, if telemetry is enabled. /// telemetry, if telemetry is enabled.
#[arg(long)] #[arg(long)]
pub no_hardware_benchmarks: bool, pub no_hardware_benchmarks: bool,
/// Relay chain arguments /// Relay chain arguments
#[arg(raw = true)] #[arg(raw = true)]
pub relay_chain_args: Vec<String>, pub relay_chain_args: Vec<String>,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct RelayChainCli { pub struct RelayChainCli {
/// The actual relay chain cli object. /// The actual relay chain cli object.
pub base: polkadot_cli::RunCmd, pub base: polkadot_cli::RunCmd,
/// Optional chain id that should be passed to the relay chain. /// Optional chain id that should be passed to the relay chain.
pub chain_id: Option<String>, pub chain_id: Option<String>,
/// The base path that should be used by the relay chain. /// The base path that should be used by the relay chain.
pub base_path: Option<PathBuf>, pub base_path: Option<PathBuf>,
} }
impl RelayChainCli { impl RelayChainCli {
/// Parse the relay chain CLI parameters using the para chain `Configuration`. /// Parse the relay chain CLI parameters using the para chain
pub fn new<'a>( /// `Configuration`.
para_config: &sc_service::Configuration, pub fn new<'a>(
relay_chain_args: impl Iterator<Item = &'a String>, para_config: &sc_service::Configuration,
) -> Self { relay_chain_args: impl Iterator<Item = &'a String>,
let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec); ) -> Self {
let chain_id = extension.map(|e| e.relay_chain.clone()); let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec);
let base_path = para_config.base_path.path().join("polkadot"); let chain_id = extension.map(|e| e.relay_chain.clone());
Self { let base_path = para_config.base_path.path().join("polkadot");
base_path: Some(base_path), Self {
chain_id, base_path: Some(base_path),
base: clap::Parser::parse_from(relay_chain_args), chain_id,
} base: clap::Parser::parse_from(relay_chain_args),
} }
}
} }
+157 -162
View File
@@ -5,97 +5,95 @@ use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
use log::info; use log::info;
use parachain_template_runtime::Block; use parachain_template_runtime::Block;
use sc_cli::{ use sc_cli::{
ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,
NetworkParams, Result, SharedParams, SubstrateCli, NetworkParams, Result, SharedParams, SubstrateCli,
}; };
use sc_service::config::{BasePath, PrometheusConfig}; use sc_service::config::{BasePath, PrometheusConfig};
use sp_runtime::traits::AccountIdConversion; use sp_runtime::traits::AccountIdConversion;
use crate::{ use crate::{
chain_spec, chain_spec,
cli::{Cli, RelayChainCli, Subcommand}, cli::{Cli, RelayChainCli, Subcommand},
service::new_partial, service::new_partial,
}; };
fn load_spec(id: &str) -> std::result::Result<Box<dyn ChainSpec>, String> { fn load_spec(id: &str) -> std::result::Result<Box<dyn ChainSpec>, String> {
Ok(match id { Ok(match id {
"dev" => Box::new(chain_spec::development_config()), "dev" => Box::new(chain_spec::development_config()),
"template-rococo" => Box::new(chain_spec::local_testnet_config()), "template-rococo" => Box::new(chain_spec::local_testnet_config()),
"" | "local" => Box::new(chain_spec::local_testnet_config()), "" | "local" => Box::new(chain_spec::local_testnet_config()),
path => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), path => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?),
}) })
} }
impl SubstrateCli for Cli { impl SubstrateCli for Cli {
fn impl_name() -> String { fn impl_name() -> String {
"Parachain Collator Template".into() "Parachain Collator Template".into()
} }
fn impl_version() -> String { fn impl_version() -> String {
env!("SUBSTRATE_CLI_IMPL_VERSION").into() env!("SUBSTRATE_CLI_IMPL_VERSION").into()
} }
fn description() -> String { fn description() -> String {
format!( format!(
"Parachain Collator Template\n\nThe command-line arguments provided first will be \ "Parachain Collator Template\n\nThe command-line arguments provided first will be \
passed to the parachain node, while the arguments provided after -- will be passed \ passed to the parachain node, while the arguments provided after -- will be passed \
to the relay chain node.\n\n\ to the relay chain node.\n\n{} <parachain-args> -- <relay-chain-args>",
{} <parachain-args> -- <relay-chain-args>", Self::executable_name()
Self::executable_name() )
) }
}
fn author() -> String { fn author() -> String {
env!("CARGO_PKG_AUTHORS").into() env!("CARGO_PKG_AUTHORS").into()
} }
fn support_url() -> String { fn support_url() -> String {
"https://github.com/paritytech/polkadot-sdk/issues/new".into() "https://github.com/paritytech/polkadot-sdk/issues/new".into()
} }
fn copyright_start_year() -> i32 { fn copyright_start_year() -> i32 {
2020 2020
} }
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> { fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
load_spec(id) load_spec(id)
} }
} }
impl SubstrateCli for RelayChainCli { impl SubstrateCli for RelayChainCli {
fn impl_name() -> String { fn impl_name() -> String {
"Parachain Collator Template".into() "Parachain Collator Template".into()
} }
fn impl_version() -> String { fn impl_version() -> String {
env!("SUBSTRATE_CLI_IMPL_VERSION").into() env!("SUBSTRATE_CLI_IMPL_VERSION").into()
} }
fn description() -> String { fn description() -> String {
format!( format!(
"Parachain Collator Template\n\nThe command-line arguments provided first will be \ "Parachain Collator Template\n\nThe command-line arguments provided first will be \
passed to the parachain node, while the arguments provided after -- will be passed \ passed to the parachain node, while the arguments provided after -- will be passed \
to the relay chain node.\n\n\ to the relay chain node.\n\n{} <parachain-args> -- <relay-chain-args>",
{} <parachain-args> -- <relay-chain-args>", Self::executable_name()
Self::executable_name() )
) }
}
fn author() -> String { fn author() -> String {
env!("CARGO_PKG_AUTHORS").into() env!("CARGO_PKG_AUTHORS").into()
} }
fn support_url() -> String { fn support_url() -> String {
"https://github.com/paritytech/polkadot-sdk/issues/new".into() "https://github.com/paritytech/polkadot-sdk/issues/new".into()
} }
fn copyright_start_year() -> i32 { fn copyright_start_year() -> i32 {
2020 2020
} }
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> { fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id) polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)
} }
} }
macro_rules! construct_async_run { macro_rules! construct_async_run {
@@ -111,9 +109,9 @@ macro_rules! construct_async_run {
/// Parse command line arguments into service configuration. /// Parse command line arguments into service configuration.
pub fn run() -> Result<()> { pub fn run() -> Result<()> {
let cli = Cli::from_args(); let cli = Cli::from_args();
match &cli.subcommand { match &cli.subcommand {
Some(Subcommand::BuildSpec(cmd)) => { Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
@@ -269,126 +267,123 @@ pub fn run() -> Result<()> {
} }
impl DefaultConfigurationValues for RelayChainCli { impl DefaultConfigurationValues for RelayChainCli {
fn p2p_listen_port() -> u16 { fn p2p_listen_port() -> u16 {
30334 30334
} }
fn rpc_listen_port() -> u16 { fn rpc_listen_port() -> u16 {
9945 9945
} }
fn prometheus_listen_port() -> u16 { fn prometheus_listen_port() -> u16 {
9616 9616
} }
} }
impl CliConfiguration<Self> for RelayChainCli { impl CliConfiguration<Self> for RelayChainCli {
fn shared_params(&self) -> &SharedParams { fn shared_params(&self) -> &SharedParams {
self.base.base.shared_params() self.base.base.shared_params()
} }
fn import_params(&self) -> Option<&ImportParams> { fn import_params(&self) -> Option<&ImportParams> {
self.base.base.import_params() self.base.base.import_params()
} }
fn network_params(&self) -> Option<&NetworkParams> { fn network_params(&self) -> Option<&NetworkParams> {
self.base.base.network_params() self.base.base.network_params()
} }
fn keystore_params(&self) -> Option<&KeystoreParams> { fn keystore_params(&self) -> Option<&KeystoreParams> {
self.base.base.keystore_params() self.base.base.keystore_params()
} }
fn base_path(&self) -> Result<Option<BasePath>> { fn base_path(&self) -> Result<Option<BasePath>> {
Ok(self Ok(self.shared_params().base_path()?.or_else(|| self.base_path.clone().map(Into::into)))
.shared_params() }
.base_path()?
.or_else(|| self.base_path.clone().map(Into::into)))
}
fn rpc_addr(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> { fn rpc_addr(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {
self.base.base.rpc_addr(default_listen_port) self.base.base.rpc_addr(default_listen_port)
} }
fn prometheus_config( fn prometheus_config(
&self, &self,
default_listen_port: u16, default_listen_port: u16,
chain_spec: &Box<dyn ChainSpec>, chain_spec: &Box<dyn ChainSpec>,
) -> Result<Option<PrometheusConfig>> { ) -> Result<Option<PrometheusConfig>> {
self.base.base.prometheus_config(default_listen_port, chain_spec) self.base.base.prometheus_config(default_listen_port, chain_spec)
} }
fn init<F>( fn init<F>(
&self, &self,
_support_url: &String, _support_url: &String,
_impl_version: &String, _impl_version: &String,
_logger_hook: F, _logger_hook: F,
_config: &sc_service::Configuration, _config: &sc_service::Configuration,
) -> Result<()> ) -> Result<()>
where where
F: FnOnce(&mut sc_cli::LoggerBuilder, &sc_service::Configuration), F: FnOnce(&mut sc_cli::LoggerBuilder, &sc_service::Configuration),
{ {
unreachable!("PolkadotCli is never initialized; qed"); unreachable!("PolkadotCli is never initialized; qed");
} }
fn chain_id(&self, is_dev: bool) -> Result<String> { fn chain_id(&self, is_dev: bool) -> Result<String> {
let chain_id = self.base.base.chain_id(is_dev)?; let chain_id = self.base.base.chain_id(is_dev)?;
Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id }) Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id })
} }
fn role(&self, is_dev: bool) -> Result<sc_service::Role> { fn role(&self, is_dev: bool) -> Result<sc_service::Role> {
self.base.base.role(is_dev) self.base.base.role(is_dev)
} }
fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> { fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {
self.base.base.transaction_pool(is_dev) self.base.base.transaction_pool(is_dev)
} }
fn trie_cache_maximum_size(&self) -> Result<Option<usize>> { fn trie_cache_maximum_size(&self) -> Result<Option<usize>> {
self.base.base.trie_cache_maximum_size() self.base.base.trie_cache_maximum_size()
} }
fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> { fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {
self.base.base.rpc_methods() self.base.base.rpc_methods()
} }
fn rpc_max_connections(&self) -> Result<u32> { fn rpc_max_connections(&self) -> Result<u32> {
self.base.base.rpc_max_connections() self.base.base.rpc_max_connections()
} }
fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> { fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {
self.base.base.rpc_cors(is_dev) self.base.base.rpc_cors(is_dev)
} }
fn default_heap_pages(&self) -> Result<Option<u64>> { fn default_heap_pages(&self) -> Result<Option<u64>> {
self.base.base.default_heap_pages() self.base.base.default_heap_pages()
} }
fn force_authoring(&self) -> Result<bool> { fn force_authoring(&self) -> Result<bool> {
self.base.base.force_authoring() self.base.base.force_authoring()
} }
fn disable_grandpa(&self) -> Result<bool> { fn disable_grandpa(&self) -> Result<bool> {
self.base.base.disable_grandpa() self.base.base.disable_grandpa()
} }
fn max_runtime_instances(&self) -> Result<Option<usize>> { fn max_runtime_instances(&self) -> Result<Option<usize>> {
self.base.base.max_runtime_instances() self.base.base.max_runtime_instances()
} }
fn announce_block(&self) -> Result<bool> { fn announce_block(&self) -> Result<bool> {
self.base.base.announce_block() self.base.base.announce_block()
} }
fn telemetry_endpoints( fn telemetry_endpoints(
&self, &self,
chain_spec: &Box<dyn ChainSpec>, chain_spec: &Box<dyn ChainSpec>,
) -> Result<Option<sc_telemetry::TelemetryEndpoints>> { ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {
self.base.base.telemetry_endpoints(chain_spec) self.base.base.telemetry_endpoints(chain_spec)
} }
fn node_name(&self) -> Result<String> { fn node_name(&self) -> Result<String> {
self.base.base.node_name() self.base.base.node_name()
} }
} }
+1 -1
View File
@@ -10,5 +10,5 @@ mod command;
mod rpc; mod rpc;
fn main() -> sc_cli::Result<()> { fn main() -> sc_cli::Result<()> {
command::run() command::run()
} }
+26 -27
View File
@@ -8,9 +8,8 @@
use std::sync::Arc; use std::sync::Arc;
use parachain_template_runtime::{opaque::Block, AccountId, Balance, Nonce}; use parachain_template_runtime::{opaque::Block, AccountId, Balance, Nonce};
use sc_client_api::AuxStore; use sc_client_api::AuxStore;
pub use sc_rpc::{DenyUnsafe}; pub use sc_rpc::DenyUnsafe;
use sc_transaction_pool_api::TransactionPool; use sc_transaction_pool_api::TransactionPool;
use sp_api::ProvideRuntimeApi; use sp_api::ProvideRuntimeApi;
use sp_block_builder::BlockBuilder; use sp_block_builder::BlockBuilder;
@@ -21,38 +20,38 @@ pub type RpcExtension = jsonrpsee::RpcModule<()>;
/// Full client dependencies /// Full client dependencies
pub struct FullDeps<C, P> { pub struct FullDeps<C, P> {
/// The client instance to use. /// The client instance to use.
pub client: Arc<C>, pub client: Arc<C>,
/// Transaction pool instance. /// Transaction pool instance.
pub pool: Arc<P>, pub pool: Arc<P>,
/// Whether to deny unsafe calls /// Whether to deny unsafe calls
pub deny_unsafe: DenyUnsafe, pub deny_unsafe: DenyUnsafe,
} }
/// Instantiate all RPC extensions. /// Instantiate all RPC extensions.
pub fn create_full<C, P>( pub fn create_full<C, P>(
deps: FullDeps<C, P>, deps: FullDeps<C, P>,
) -> Result<RpcExtension, Box<dyn std::error::Error + Send + Sync>> ) -> Result<RpcExtension, Box<dyn std::error::Error + Send + Sync>>
where where
C: ProvideRuntimeApi<Block> C: ProvideRuntimeApi<Block>
+ HeaderBackend<Block> + HeaderBackend<Block>
+ AuxStore + AuxStore
+ HeaderMetadata<Block, Error = BlockChainError> + HeaderMetadata<Block, Error = BlockChainError>
+ Send + Send
+ Sync + Sync
+ 'static, + 'static,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>, C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>,
C::Api: BlockBuilder<Block>, C::Api: BlockBuilder<Block>,
P: TransactionPool + Sync + Send + 'static, P: TransactionPool + Sync + Send + 'static,
{ {
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use substrate_frame_rpc_system::{System, SystemApiServer}; use substrate_frame_rpc_system::{System, SystemApiServer};
let mut module = RpcExtension::new(()); let mut module = RpcExtension::new(());
let FullDeps { client, pool, deny_unsafe } = deps; let FullDeps { client, pool, deny_unsafe } = deps;
module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
module.merge(TransactionPayment::new(client).into_rpc())?; module.merge(TransactionPayment::new(client).into_rpc())?;
Ok(module) Ok(module)
} }
+329 -327
View File
@@ -1,32 +1,31 @@
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service. //! Service and ServiceFactory implementation. Specialized wrapper over
//! substrate service.
// std // std
use std::{sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
use cumulus_client_cli::CollatorOptions; use cumulus_client_cli::CollatorOptions;
// Local Runtime Types
use parachain_template_runtime::{
opaque::{Block, Hash},
RuntimeApi,
};
// Cumulus Imports // Cumulus Imports
use cumulus_client_collator::service::CollatorService; use cumulus_client_collator::service::CollatorService;
use cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport; use cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport;
use cumulus_client_consensus_proposer::Proposer; use cumulus_client_consensus_proposer::Proposer;
use cumulus_client_service::{ use cumulus_client_service::{
build_network, build_relay_chain_interface, prepare_node_config, start_relay_chain_tasks, build_network, build_relay_chain_interface, prepare_node_config, start_relay_chain_tasks,
BuildNetworkParams, CollatorSybilResistance, DARecoveryProfile, StartRelayChainTasksParams, BuildNetworkParams, CollatorSybilResistance, DARecoveryProfile, StartRelayChainTasksParams,
}; };
use cumulus_primitives_core::{relay_chain::CollatorPair, ParaId}; use cumulus_primitives_core::{relay_chain::CollatorPair, ParaId};
use cumulus_relay_chain_interface::{OverseerHandle, RelayChainInterface}; use cumulus_relay_chain_interface::{OverseerHandle, RelayChainInterface};
// Substrate Imports // Substrate Imports
use frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE; use frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE;
// Local Runtime Types
use parachain_template_runtime::{
opaque::{Block, Hash},
RuntimeApi,
};
use sc_client_api::Backend; use sc_client_api::Backend;
use sc_consensus::ImportQueue; use sc_consensus::ImportQueue;
use sc_executor::{ use sc_executor::{
HeapAllocStrategy, NativeElseWasmExecutor, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY, HeapAllocStrategy, NativeElseWasmExecutor, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY,
}; };
use sc_network::NetworkBlock; use sc_network::NetworkBlock;
use sc_network_sync::SyncingService; use sc_network_sync::SyncingService;
@@ -40,15 +39,15 @@ use substrate_prometheus_endpoint::Registry;
pub struct ParachainNativeExecutor; pub struct ParachainNativeExecutor;
impl sc_executor::NativeExecutionDispatch for ParachainNativeExecutor { impl sc_executor::NativeExecutionDispatch for ParachainNativeExecutor {
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> { fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
parachain_template_runtime::api::dispatch(method, data) parachain_template_runtime::api::dispatch(method, data)
} }
fn native_version() -> sc_executor::NativeVersion { fn native_version() -> sc_executor::NativeVersion {
parachain_template_runtime::native_version() parachain_template_runtime::native_version()
} }
} }
type ParachainExecutor = NativeElseWasmExecutor<ParachainNativeExecutor>; type ParachainExecutor = NativeElseWasmExecutor<ParachainNativeExecutor>;
@@ -61,375 +60,378 @@ type ParachainBlockImport = TParachainBlockImport<Block, Arc<ParachainClient>, P
/// Starts a `ServiceBuilder` for a full service. /// Starts a `ServiceBuilder` for a full service.
/// ///
/// Use this macro if you don't actually need the full service, but just the builder in order to /// Use this macro if you don't actually need the full service, but just the
/// be able to perform chain operations. /// builder in order to be able to perform chain operations.
pub fn new_partial( pub fn new_partial(
config: &Configuration, config: &Configuration,
) -> Result< ) -> Result<
PartialComponents< PartialComponents<
ParachainClient, ParachainClient,
ParachainBackend, ParachainBackend,
(), (),
sc_consensus::DefaultImportQueue<Block>, sc_consensus::DefaultImportQueue<Block>,
sc_transaction_pool::FullPool<Block, ParachainClient>, sc_transaction_pool::FullPool<Block, ParachainClient>,
(ParachainBlockImport, Option<Telemetry>, Option<TelemetryWorkerHandle>), (ParachainBlockImport, Option<Telemetry>, Option<TelemetryWorkerHandle>),
>, >,
sc_service::Error, sc_service::Error,
> { > {
let telemetry = config let telemetry = config
.telemetry_endpoints .telemetry_endpoints
.clone() .clone()
.filter(|x| !x.is_empty()) .filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> { .map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?; let worker = TelemetryWorker::new(16)?;
let telemetry = worker.handle().new_telemetry(endpoints); let telemetry = worker.handle().new_telemetry(endpoints);
Ok((worker, telemetry)) Ok((worker, telemetry))
}) })
.transpose()?; .transpose()?;
let heap_pages = config let heap_pages = config
.default_heap_pages .default_heap_pages
.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ }); .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ });
let wasm = WasmExecutor::builder() let wasm = WasmExecutor::builder()
.with_execution_method(config.wasm_method) .with_execution_method(config.wasm_method)
.with_onchain_heap_alloc_strategy(heap_pages) .with_onchain_heap_alloc_strategy(heap_pages)
.with_offchain_heap_alloc_strategy(heap_pages) .with_offchain_heap_alloc_strategy(heap_pages)
.with_max_runtime_instances(config.max_runtime_instances) .with_max_runtime_instances(config.max_runtime_instances)
.with_runtime_cache_size(config.runtime_cache_size) .with_runtime_cache_size(config.runtime_cache_size)
.build(); .build();
let executor = ParachainExecutor::new_with_wasm_executor(wasm); let executor = ParachainExecutor::new_with_wasm_executor(wasm);
let (client, backend, keystore_container, task_manager) = let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, _>( sc_service::new_full_parts::<Block, RuntimeApi, _>(
config, config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
executor, executor,
)?; )?;
let client = Arc::new(client); let client = Arc::new(client);
let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle()); let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
let telemetry = telemetry.map(|(worker, telemetry)| { let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", None, worker.run()); task_manager.spawn_handle().spawn("telemetry", None, worker.run());
telemetry telemetry
}); });
let transaction_pool = sc_transaction_pool::BasicPool::new_full( let transaction_pool = sc_transaction_pool::BasicPool::new_full(
config.transaction_pool.clone(), config.transaction_pool.clone(),
config.role.is_authority().into(), config.role.is_authority().into(),
config.prometheus_registry(), config.prometheus_registry(),
task_manager.spawn_essential_handle(), task_manager.spawn_essential_handle(),
client.clone(), client.clone(),
); );
let block_import = ParachainBlockImport::new(client.clone(), backend.clone()); let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
let import_queue = build_import_queue( let import_queue = build_import_queue(
client.clone(), client.clone(),
block_import.clone(), block_import.clone(),
config, config,
telemetry.as_ref().map(|telemetry| telemetry.handle()), telemetry.as_ref().map(|telemetry| telemetry.handle()),
&task_manager, &task_manager,
)?; )?;
Ok(PartialComponents { Ok(PartialComponents {
backend, backend,
client, client,
import_queue, import_queue,
keystore_container, keystore_container,
task_manager, task_manager,
transaction_pool, transaction_pool,
select_chain: (), select_chain: (),
other: (block_import, telemetry, telemetry_worker_handle), other: (block_import, telemetry, telemetry_worker_handle),
}) })
} }
/// Start a node with the given parachain `Configuration` and relay chain `Configuration`. /// Start a node with the given parachain `Configuration` and relay chain
/// `Configuration`.
/// ///
/// This is the actual implementation that is abstract over the executor and the runtime api. /// This is the actual implementation that is abstract over the executor and the
/// runtime api.
#[sc_tracing::logging::prefix_logs_with("Parachain")] #[sc_tracing::logging::prefix_logs_with("Parachain")]
async fn start_node_impl( async fn start_node_impl(
parachain_config: Configuration, parachain_config: Configuration,
polkadot_config: Configuration, polkadot_config: Configuration,
collator_options: CollatorOptions, collator_options: CollatorOptions,
para_id: ParaId, para_id: ParaId,
hwbench: Option<sc_sysinfo::HwBench>, hwbench: Option<sc_sysinfo::HwBench>,
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)> { ) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)> {
let parachain_config = prepare_node_config(parachain_config); let parachain_config = prepare_node_config(parachain_config);
let params = new_partial(&parachain_config)?; let params = new_partial(&parachain_config)?;
let (block_import, mut telemetry, telemetry_worker_handle) = params.other; let (block_import, mut telemetry, telemetry_worker_handle) = params.other;
let net_config = sc_network::config::FullNetworkConfiguration::new(&parachain_config.network); let net_config = sc_network::config::FullNetworkConfiguration::new(&parachain_config.network);
let client = params.client.clone(); let client = params.client.clone();
let backend = params.backend.clone(); let backend = params.backend.clone();
let mut task_manager = params.task_manager; let mut task_manager = params.task_manager;
let (relay_chain_interface, collator_key) = build_relay_chain_interface( let (relay_chain_interface, collator_key) = build_relay_chain_interface(
polkadot_config, polkadot_config,
&parachain_config, &parachain_config,
telemetry_worker_handle, telemetry_worker_handle,
&mut task_manager, &mut task_manager,
collator_options.clone(), collator_options.clone(),
hwbench.clone(), hwbench.clone(),
) )
.await .await
.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?; .map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
let validator = parachain_config.role.is_authority(); let validator = parachain_config.role.is_authority();
let prometheus_registry = parachain_config.prometheus_registry().cloned(); let prometheus_registry = parachain_config.prometheus_registry().cloned();
let transaction_pool = params.transaction_pool.clone(); let transaction_pool = params.transaction_pool.clone();
let import_queue_service = params.import_queue.service(); let import_queue_service = params.import_queue.service();
let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =
build_network(BuildNetworkParams { build_network(BuildNetworkParams {
parachain_config: &parachain_config, parachain_config: &parachain_config,
net_config, net_config,
client: client.clone(), client: client.clone(),
transaction_pool: transaction_pool.clone(), transaction_pool: transaction_pool.clone(),
para_id, para_id,
spawn_handle: task_manager.spawn_handle(), spawn_handle: task_manager.spawn_handle(),
relay_chain_interface: relay_chain_interface.clone(), relay_chain_interface: relay_chain_interface.clone(),
import_queue: params.import_queue, import_queue: params.import_queue,
sybil_resistance_level: CollatorSybilResistance::Resistant, // because of Aura sybil_resistance_level: CollatorSybilResistance::Resistant, // because of Aura
}) })
.await?; .await?;
if parachain_config.offchain_worker.enabled { if parachain_config.offchain_worker.enabled {
use futures::FutureExt; use futures::FutureExt;
task_manager.spawn_handle().spawn( task_manager.spawn_handle().spawn(
"offchain-workers-runner", "offchain-workers-runner",
"offchain-work", "offchain-work",
sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions { sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
runtime_api_provider: client.clone(), runtime_api_provider: client.clone(),
keystore: Some(params.keystore_container.keystore()), keystore: Some(params.keystore_container.keystore()),
offchain_db: backend.offchain_storage(), offchain_db: backend.offchain_storage(),
transaction_pool: Some(OffchainTransactionPoolFactory::new( transaction_pool: Some(OffchainTransactionPoolFactory::new(
transaction_pool.clone(), transaction_pool.clone(),
)), )),
network_provider: network.clone(), network_provider: network.clone(),
is_validator: parachain_config.role.is_authority(), is_validator: parachain_config.role.is_authority(),
enable_http_requests: false, enable_http_requests: false,
custom_extensions: move |_| vec![], custom_extensions: move |_| vec![],
}) })
.run(client.clone(), task_manager.spawn_handle()) .run(client.clone(), task_manager.spawn_handle())
.boxed(), .boxed(),
); );
} }
let rpc_builder = { let rpc_builder = {
let client = client.clone(); let client = client.clone();
let transaction_pool = transaction_pool.clone(); let transaction_pool = transaction_pool.clone();
Box::new(move |deny_unsafe, _| { Box::new(move |deny_unsafe, _| {
let deps = crate::rpc::FullDeps { let deps = crate::rpc::FullDeps {
client: client.clone(), client: client.clone(),
pool: transaction_pool.clone(), pool: transaction_pool.clone(),
deny_unsafe, deny_unsafe,
}; };
crate::rpc::create_full(deps).map_err(Into::into) crate::rpc::create_full(deps).map_err(Into::into)
}) })
}; };
sc_service::spawn_tasks(sc_service::SpawnTasksParams { sc_service::spawn_tasks(sc_service::SpawnTasksParams {
rpc_builder, rpc_builder,
client: client.clone(), client: client.clone(),
transaction_pool: transaction_pool.clone(), transaction_pool: transaction_pool.clone(),
task_manager: &mut task_manager, task_manager: &mut task_manager,
config: parachain_config, config: parachain_config,
keystore: params.keystore_container.keystore(), keystore: params.keystore_container.keystore(),
backend, backend,
network: network.clone(), network: network.clone(),
sync_service: sync_service.clone(), sync_service: sync_service.clone(),
system_rpc_tx, system_rpc_tx,
tx_handler_controller, tx_handler_controller,
telemetry: telemetry.as_mut(), telemetry: telemetry.as_mut(),
})?; })?;
if let Some(hwbench) = hwbench { if let Some(hwbench) = hwbench {
sc_sysinfo::print_hwbench(&hwbench); sc_sysinfo::print_hwbench(&hwbench);
// Here you can check whether the hardware meets your chains' requirements. Putting a link // Here you can check whether the hardware meets your chains' requirements.
// in there and swapping out the requirements for your own are probably a good idea. The // Putting a link in there and swapping out the requirements for your
// requirements for a para-chain are dictated by its relay-chain. // own are probably a good idea. The requirements for a para-chain are
if !SUBSTRATE_REFERENCE_HARDWARE.check_hardware(&hwbench) && validator { // dictated by its relay-chain.
log::warn!( if !SUBSTRATE_REFERENCE_HARDWARE.check_hardware(&hwbench) && validator {
"⚠️ The hardware does not meet the minimal requirements for role 'Authority'." log::warn!(
); "⚠️ The hardware does not meet the minimal requirements for role 'Authority'."
} );
}
if let Some(ref mut telemetry) = telemetry { if let Some(ref mut telemetry) = telemetry {
let telemetry_handle = telemetry.handle(); let telemetry_handle = telemetry.handle();
task_manager.spawn_handle().spawn( task_manager.spawn_handle().spawn(
"telemetry_hwbench", "telemetry_hwbench",
None, None,
sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench), sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
); );
} }
} }
let announce_block = { let announce_block = {
let sync_service = sync_service.clone(); let sync_service = sync_service.clone();
Arc::new(move |hash, data| sync_service.announce_block(hash, data)) Arc::new(move |hash, data| sync_service.announce_block(hash, data))
}; };
let relay_chain_slot_duration = Duration::from_secs(6); let relay_chain_slot_duration = Duration::from_secs(6);
let overseer_handle = relay_chain_interface let overseer_handle = relay_chain_interface
.overseer_handle() .overseer_handle()
.map_err(|e| sc_service::Error::Application(Box::new(e)))?; .map_err(|e| sc_service::Error::Application(Box::new(e)))?;
start_relay_chain_tasks(StartRelayChainTasksParams { start_relay_chain_tasks(StartRelayChainTasksParams {
client: client.clone(), client: client.clone(),
announce_block: announce_block.clone(), announce_block: announce_block.clone(),
para_id, para_id,
relay_chain_interface: relay_chain_interface.clone(), relay_chain_interface: relay_chain_interface.clone(),
task_manager: &mut task_manager, task_manager: &mut task_manager,
da_recovery_profile: if validator { da_recovery_profile: if validator {
DARecoveryProfile::Collator DARecoveryProfile::Collator
} else { } else {
DARecoveryProfile::FullNode DARecoveryProfile::FullNode
}, },
import_queue: import_queue_service, import_queue: import_queue_service,
relay_chain_slot_duration, relay_chain_slot_duration,
recovery_handle: Box::new(overseer_handle.clone()), recovery_handle: Box::new(overseer_handle.clone()),
sync_service: sync_service.clone(), sync_service: sync_service.clone(),
})?; })?;
if validator { if validator {
start_consensus( start_consensus(
client.clone(), client.clone(),
block_import, block_import,
prometheus_registry.as_ref(), prometheus_registry.as_ref(),
telemetry.as_ref().map(|t| t.handle()), telemetry.as_ref().map(|t| t.handle()),
&task_manager, &task_manager,
relay_chain_interface.clone(), relay_chain_interface.clone(),
transaction_pool, transaction_pool,
sync_service.clone(), sync_service.clone(),
params.keystore_container.keystore(), params.keystore_container.keystore(),
relay_chain_slot_duration, relay_chain_slot_duration,
para_id, para_id,
collator_key.expect("Command line arguments do not allow this. qed"), collator_key.expect("Command line arguments do not allow this. qed"),
overseer_handle, overseer_handle,
announce_block, announce_block,
)?; )?;
} }
start_network.start_network(); start_network.start_network();
Ok((task_manager, client)) Ok((task_manager, client))
} }
/// Build the import queue for the parachain runtime. /// Build the import queue for the parachain runtime.
fn build_import_queue( fn build_import_queue(
client: Arc<ParachainClient>, client: Arc<ParachainClient>,
block_import: ParachainBlockImport, block_import: ParachainBlockImport,
config: &Configuration, config: &Configuration,
telemetry: Option<TelemetryHandle>, telemetry: Option<TelemetryHandle>,
task_manager: &TaskManager, task_manager: &TaskManager,
) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error> { ) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error> {
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
Ok(cumulus_client_consensus_aura::equivocation_import_queue::fully_verifying_import_queue::< Ok(cumulus_client_consensus_aura::equivocation_import_queue::fully_verifying_import_queue::<
sp_consensus_aura::sr25519::AuthorityPair, sp_consensus_aura::sr25519::AuthorityPair,
_, _,
_, _,
_, _,
_, _,
>( >(
client, client,
block_import, block_import,
move |_, _| async move { move |_, _| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
Ok(timestamp) Ok(timestamp)
}, },
slot_duration, slot_duration,
&task_manager.spawn_essential_handle(), &task_manager.spawn_essential_handle(),
config.prometheus_registry(), config.prometheus_registry(),
telemetry, telemetry,
)) ))
} }
fn start_consensus( fn start_consensus(
client: Arc<ParachainClient>, client: Arc<ParachainClient>,
block_import: ParachainBlockImport, block_import: ParachainBlockImport,
prometheus_registry: Option<&Registry>, prometheus_registry: Option<&Registry>,
telemetry: Option<TelemetryHandle>, telemetry: Option<TelemetryHandle>,
task_manager: &TaskManager, task_manager: &TaskManager,
relay_chain_interface: Arc<dyn RelayChainInterface>, relay_chain_interface: Arc<dyn RelayChainInterface>,
transaction_pool: Arc<sc_transaction_pool::FullPool<Block, ParachainClient>>, transaction_pool: Arc<sc_transaction_pool::FullPool<Block, ParachainClient>>,
sync_oracle: Arc<SyncingService<Block>>, sync_oracle: Arc<SyncingService<Block>>,
keystore: KeystorePtr, keystore: KeystorePtr,
relay_chain_slot_duration: Duration, relay_chain_slot_duration: Duration,
para_id: ParaId, para_id: ParaId,
collator_key: CollatorPair, collator_key: CollatorPair,
overseer_handle: OverseerHandle, overseer_handle: OverseerHandle,
announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>, announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
) -> Result<(), sc_service::Error> { ) -> Result<(), sc_service::Error> {
use cumulus_client_consensus_aura::collators::basic::{ use cumulus_client_consensus_aura::collators::basic::{
self as basic_aura, Params as BasicAuraParams, self as basic_aura, Params as BasicAuraParams,
}; };
// NOTE: because we use Aura here explicitly, we can use `CollatorSybilResistance::Resistant` // NOTE: because we use Aura here explicitly, we can use
// when starting the network. // `CollatorSybilResistance::Resistant` when starting the network.
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
task_manager.spawn_handle(), task_manager.spawn_handle(),
client.clone(), client.clone(),
transaction_pool, transaction_pool,
prometheus_registry, prometheus_registry,
telemetry.clone(), telemetry.clone(),
); );
let proposer = Proposer::new(proposer_factory); let proposer = Proposer::new(proposer_factory);
let collator_service = CollatorService::new( let collator_service = CollatorService::new(
client.clone(), client.clone(),
Arc::new(task_manager.spawn_handle()), Arc::new(task_manager.spawn_handle()),
announce_block, announce_block,
client.clone(), client.clone(),
); );
let params = BasicAuraParams { let params = BasicAuraParams {
create_inherent_data_providers: move |_, ()| async move { Ok(()) }, create_inherent_data_providers: move |_, ()| async move { Ok(()) },
block_import, block_import,
para_client: client, para_client: client,
relay_client: relay_chain_interface, relay_client: relay_chain_interface,
sync_oracle, sync_oracle,
keystore, keystore,
collator_key, collator_key,
para_id, para_id,
overseer_handle, overseer_handle,
slot_duration, slot_duration,
relay_chain_slot_duration, relay_chain_slot_duration,
proposer, proposer,
collator_service, collator_service,
// Very limited proposal time. // Very limited proposal time.
authoring_duration: Duration::from_millis(500), authoring_duration: Duration::from_millis(500),
collation_request_receiver: None, collation_request_receiver: None,
}; };
let fut = let fut =
basic_aura::run::<Block, sp_consensus_aura::sr25519::AuthorityPair, _, _, _, _, _, _, _>( basic_aura::run::<Block, sp_consensus_aura::sr25519::AuthorityPair, _, _, _, _, _, _, _>(
params, params,
); );
task_manager.spawn_essential_handle().spawn("aura", None, fut); task_manager.spawn_essential_handle().spawn("aura", None, fut);
Ok(()) Ok(())
} }
/// Start a parachain node. /// Start a parachain node.
pub async fn start_parachain_node( pub async fn start_parachain_node(
parachain_config: Configuration, parachain_config: Configuration,
polkadot_config: Configuration, polkadot_config: Configuration,
collator_options: CollatorOptions, collator_options: CollatorOptions,
para_id: ParaId, para_id: ParaId,
hwbench: Option<sc_sysinfo::HwBench>, hwbench: Option<sc_sysinfo::HwBench>,
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)> { ) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)> {
start_node_impl(parachain_config, polkadot_config, collator_options, para_id, hwbench).await start_node_impl(parachain_config, polkadot_config, collator_options, para_id, hwbench).await
} }
+11 -11
View File
@@ -1,20 +1,20 @@
//! Benchmarking setup for pallet-parachain-template //! Benchmarking setup for pallet-parachain-template
use super::*;
#[allow(unused)]
use crate::Pallet as Template;
use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller};
use frame_system::RawOrigin; use frame_system::RawOrigin;
use super::*;
#[allow(unused)]
use crate::Pallet as Template;
benchmarks! { benchmarks! {
do_something { do_something {
let s in 0 .. 100; let s in 0 .. 100;
let caller: T::AccountId = whitelisted_caller(); let caller: T::AccountId = whitelisted_caller();
}: _(RawOrigin::Signed(caller), s) }: _(RawOrigin::Signed(caller), s)
verify { verify {
assert_eq!(Something::<T>::get(), Some(s)); assert_eq!(Something::<T>::get(), Some(s));
} }
} }
impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,); impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,);
+80 -76
View File
@@ -16,91 +16,95 @@ mod benchmarking;
#[frame_support::pallet] #[frame_support::pallet]
pub mod pallet { pub mod pallet {
use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*};
use frame_system::pallet_prelude::*; use frame_system::pallet_prelude::*;
/// Configure the pallet by specifying the parameters and types on which it depends. /// Configure the pallet by specifying the parameters and types on which it
#[pallet::config] /// depends.
pub trait Config: frame_system::Config { #[pallet::config]
/// Because this pallet emits events, it depends on the runtime's definition of an event. pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>; /// Because this pallet emits events, it depends on the runtime's
} /// definition of an event.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
}
#[pallet::pallet] #[pallet::pallet]
pub struct Pallet<T>(_); pub struct Pallet<T>(_);
// The pallet's runtime storage items. // The pallet's runtime storage items.
// https://docs.substrate.io/v3/runtime/storage // https://docs.substrate.io/v3/runtime/storage
#[pallet::storage] #[pallet::storage]
#[pallet::getter(fn something)] #[pallet::getter(fn something)]
// Learn more about declaring storage items: // Learn more about declaring storage items:
// https://docs.substrate.io/v3/runtime/storage#declaring-storage-items // https://docs.substrate.io/v3/runtime/storage#declaring-storage-items
pub type Something<T> = StorageValue<_, u32>; pub type Something<T> = StorageValue<_, u32>;
// Pallets use events to inform users when important changes are made. // Pallets use events to inform users when important changes are made.
// https://docs.substrate.io/v3/runtime/events-and-errors // https://docs.substrate.io/v3/runtime/events-and-errors
#[pallet::event] #[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> { pub enum Event<T: Config> {
/// Event documentation should end with an array that provides descriptive names for event /// Event documentation should end with an array that provides
/// parameters. [something, who] /// descriptive names for event parameters. [something, who]
SomethingStored(u32, T::AccountId), SomethingStored(u32, T::AccountId),
} }
// Errors inform users that something went wrong. // Errors inform users that something went wrong.
#[pallet::error] #[pallet::error]
pub enum Error<T> { pub enum Error<T> {
/// Error names should be descriptive. /// Error names should be descriptive.
NoneValue, NoneValue,
/// Errors should have helpful documentation associated with them. /// Errors should have helpful documentation associated with them.
StorageOverflow, StorageOverflow,
} }
#[pallet::hooks] #[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {} impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
// Dispatchable functions allows users to interact with the pallet and invoke state changes. // Dispatchable functions allows users to interact with the pallet and invoke
// These functions materialize as "extrinsics", which are often compared to transactions. // state changes. These functions materialize as "extrinsics", which are
// Dispatchable functions must be annotated with a weight and must return a DispatchResult. // often compared to transactions. Dispatchable functions must be annotated
#[pallet::call] // with a weight and must return a DispatchResult.
impl<T: Config> Pallet<T> { #[pallet::call]
/// An example dispatchable that takes a singles value as a parameter, writes the value to impl<T: Config> Pallet<T> {
/// storage and emits an event. This function must be dispatched by a signed extrinsic. /// An example dispatchable that takes a singles value as a parameter,
#[pallet::call_index(0)] /// writes the value to storage and emits an event. This
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))] /// function must be dispatched by a signed extrinsic.
pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResultWithPostInfo { #[pallet::call_index(0)]
// Check that the extrinsic was signed and get the signer. #[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
// This function will return an error if the extrinsic is not signed. pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResultWithPostInfo {
// https://docs.substrate.io/v3/runtime/origins // Check that the extrinsic was signed and get the signer.
let who = ensure_signed(origin)?; // This function will return an error if the extrinsic is not signed.
// https://docs.substrate.io/v3/runtime/origins
let who = ensure_signed(origin)?;
// Update storage. // Update storage.
<Something<T>>::put(something); <Something<T>>::put(something);
// Emit an event. // Emit an event.
Self::deposit_event(Event::SomethingStored(something, who)); Self::deposit_event(Event::SomethingStored(something, who));
// Return a successful DispatchResultWithPostInfo // Return a successful DispatchResultWithPostInfo
Ok(().into()) Ok(().into())
} }
/// An example dispatchable that may throw a custom error. /// An example dispatchable that may throw a custom error.
#[pallet::call_index(1)] #[pallet::call_index(1)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().reads_writes(1,1))] #[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().reads_writes(1,1))]
pub fn cause_error(origin: OriginFor<T>) -> DispatchResultWithPostInfo { pub fn cause_error(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
let _who = ensure_signed(origin)?; let _who = ensure_signed(origin)?;
// Read a value from storage. // Read a value from storage.
match <Something<T>>::get() { match <Something<T>>::get() {
// Return an error if the value has not been set. // Return an error if the value has not been set.
None => Err(Error::<T>::NoneValue)?, None => Err(Error::<T>::NoneValue)?,
Some(old) => { Some(old) => {
// Increment the value read from storage; will error in the event of overflow. // Increment the value read from storage; will error in the event of overflow.
let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?; let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?;
// Update the value in storage with the incremented result. // Update the value in storage with the incremented result.
<Something<T>>::put(new); <Something<T>>::put(new);
Ok(().into()) Ok(().into())
}, }
} }
} }
} }
} }
+34 -34
View File
@@ -2,57 +2,57 @@ use frame_support::{parameter_types, traits::Everything};
use frame_system as system; use frame_system as system;
use sp_core::H256; use sp_core::H256;
use sp_runtime::{ use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup}, traits::{BlakeTwo256, IdentityLookup},
BuildStorage, BuildStorage,
}; };
type Block = frame_system::mocking::MockBlock<Test>; type Block = frame_system::mocking::MockBlock<Test>;
// Configure a mock runtime to test the pallet. // Configure a mock runtime to test the pallet.
frame_support::construct_runtime!( frame_support::construct_runtime!(
pub enum Test pub enum Test
{ {
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>}, System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
TemplateModule: crate::{Pallet, Call, Storage, Event<T>}, TemplateModule: crate::{Pallet, Call, Storage, Event<T>},
} }
); );
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub const SS58Prefix: u8 = 42; pub const SS58Prefix: u8 = 42;
} }
impl system::Config for Test { impl system::Config for Test {
type BaseCallFilter = Everything; type AccountData = ();
type BlockWeights = (); type AccountId = u64;
type BlockLength = (); type BaseCallFilter = Everything;
type DbWeight = (); type Block = Block;
type RuntimeOrigin = RuntimeOrigin; type BlockHashCount = BlockHashCount;
type RuntimeCall = RuntimeCall; type BlockLength = ();
type Nonce = u64; type BlockWeights = ();
type Hash = H256; type DbWeight = ();
type Hashing = BlakeTwo256; type Hash = H256;
type AccountId = u64; type Hashing = BlakeTwo256;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Block = Block; type MaxConsumers = frame_support::traits::ConstU32<16>;
type RuntimeEvent = RuntimeEvent; type Nonce = u64;
type BlockHashCount = BlockHashCount; type OnKilledAccount = ();
type Version = (); type OnNewAccount = ();
type PalletInfo = PalletInfo; type OnSetCode = ();
type AccountData = (); type PalletInfo = PalletInfo;
type OnNewAccount = (); type RuntimeCall = RuntimeCall;
type OnKilledAccount = (); type RuntimeEvent = RuntimeEvent;
type SystemWeightInfo = (); type RuntimeOrigin = RuntimeOrigin;
type SS58Prefix = SS58Prefix; type SS58Prefix = SS58Prefix;
type OnSetCode = (); type SystemWeightInfo = ();
type MaxConsumers = frame_support::traits::ConstU32<16>; type Version = ();
} }
impl crate::Config for Test { impl crate::Config for Test {
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
} }
// Build genesis storage according to the mock runtime. // Build genesis storage according to the mock runtime.
pub fn new_test_ext() -> sp_io::TestExternalities { pub fn new_test_ext() -> sp_io::TestExternalities {
system::GenesisConfig::<Test>::default().build_storage().unwrap().into() system::GenesisConfig::<Test>::default().build_storage().unwrap().into()
} }
+15 -14
View File
@@ -1,23 +1,24 @@
use crate::{mock::*, Error};
use frame_support::{assert_noop, assert_ok}; use frame_support::{assert_noop, assert_ok};
use crate::{mock::*, Error};
#[test] #[test]
fn it_works_for_default_value() { fn it_works_for_default_value() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
// Dispatch a signed extrinsic. // Dispatch a signed extrinsic.
assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42)); assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42));
// Read pallet storage and assert an expected result. // Read pallet storage and assert an expected result.
assert_eq!(TemplateModule::something(), Some(42)); assert_eq!(TemplateModule::something(), Some(42));
}); });
} }
#[test] #[test]
fn correct_error_for_none_value() { fn correct_error_for_none_value() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
// Ensure the expected error is thrown when no value is present. // Ensure the expected error is thrown when no value is present.
assert_noop!( assert_noop!(
TemplateModule::cause_error(RuntimeOrigin::signed(1)), TemplateModule::cause_error(RuntimeOrigin::signed(1)),
Error::<Test>::NoneValue Error::<Test>::NoneValue
); );
}); });
} }
+5 -5
View File
@@ -1,10 +1,10 @@
#[cfg(feature = "std")] #[cfg(feature = "std")]
fn main() { fn main() {
substrate_wasm_builder::WasmBuilder::new() substrate_wasm_builder::WasmBuilder::new()
.with_current_project() .with_current_project()
.export_heap_base() .export_heap_base()
.import_memory() .import_memory()
.build() .build()
} }
/// The wasm builder is deactivated when compiling /// The wasm builder is deactivated when compiling
+519 -515
View File
File diff suppressed because it is too large Load Diff
+30 -30
View File
@@ -16,38 +16,38 @@
// limitations under the License. // limitations under the License.
pub mod constants { pub mod constants {
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
weights::{constants, Weight}, weights::{constants, Weight},
}; };
parameter_types! { parameter_types! {
/// Importing a block with 0 Extrinsics. /// Importing a block with 0 Extrinsics.
pub const BlockExecutionWeight: Weight = pub const BlockExecutionWeight: Weight =
Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0);
} }
#[cfg(test)] #[cfg(test)]
mod test_weights { mod test_weights {
use frame_support::weights::constants; use frame_support::weights::constants;
/// Checks that the weight exists and is sane. /// Checks that the weight exists and is sane.
// NOTE: If this test fails but you are sure that the generated values are fine, // NOTE: If this test fails but you are sure that the generated values are fine,
// you can delete it. // you can delete it.
#[test] #[test]
fn sane() { fn sane() {
let w = super::constants::BlockExecutionWeight::get(); let w = super::constants::BlockExecutionWeight::get();
// At least 100 µs. // At least 100 µs.
assert!( assert!(
w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS,
"Weight should be at least 100 µs." "Weight should be at least 100 µs."
); );
// At most 50 ms. // At most 50 ms.
assert!( assert!(
w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS,
"Weight should be at most 50 ms." "Weight should be at most 50 ms."
); );
} }
} }
} }
+30 -30
View File
@@ -16,38 +16,38 @@
// limitations under the License. // limitations under the License.
pub mod constants { pub mod constants {
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
weights::{constants, Weight}, weights::{constants, Weight},
}; };
parameter_types! { parameter_types! {
/// Executing a NO-OP `System::remarks` Extrinsic. /// Executing a NO-OP `System::remarks` Extrinsic.
pub const ExtrinsicBaseWeight: Weight = pub const ExtrinsicBaseWeight: Weight =
Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0);
} }
#[cfg(test)] #[cfg(test)]
mod test_weights { mod test_weights {
use frame_support::weights::constants; use frame_support::weights::constants;
/// Checks that the weight exists and is sane. /// Checks that the weight exists and is sane.
// NOTE: If this test fails but you are sure that the generated values are fine, // NOTE: If this test fails but you are sure that the generated values are fine,
// you can delete it. // you can delete it.
#[test] #[test]
fn sane() { fn sane() {
let w = super::constants::ExtrinsicBaseWeight::get(); let w = super::constants::ExtrinsicBaseWeight::get();
// At least 10 µs. // At least 10 µs.
assert!( assert!(
w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS,
"Weight should be at least 10 µs." "Weight should be at least 10 µs."
); );
// At most 1 ms. // At most 1 ms.
assert!( assert!(
w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
"Weight should be at most 1 ms." "Weight should be at most 1 ms."
); );
} }
} }
} }
+42 -41
View File
@@ -16,48 +16,49 @@
// limitations under the License. // limitations under the License.
pub mod constants { pub mod constants {
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
weights::{constants, RuntimeDbWeight}, weights::{constants, RuntimeDbWeight},
}; };
parameter_types! { parameter_types! {
/// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights
/// are available for brave runtime engineers who may want to try this out as default. /// are available for brave runtime engineers who may want to try this out as default.
pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight {
read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
}; };
} }
#[cfg(test)] #[cfg(test)]
mod test_db_weights { mod test_db_weights {
use super::constants::ParityDbWeight as W; use frame_support::weights::constants;
use frame_support::weights::constants;
/// Checks that all weights exist and have sane values. use super::constants::ParityDbWeight as W;
// NOTE: If this test fails but you are sure that the generated values are fine,
// you can delete it. /// Checks that all weights exist and have sane values.
#[test] // NOTE: If this test fails but you are sure that the generated values are fine,
fn sane() { // you can delete it.
// At least 1 µs. #[test]
assert!( fn sane() {
W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, // At least 1 µs.
"Read weight should be at least 1 µs." assert!(
); W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
assert!( "Read weight should be at least 1 µs."
W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, );
"Write weight should be at least 1 µs." assert!(
); W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
// At most 1 ms. "Write weight should be at least 1 µs."
assert!( );
W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, // At most 1 ms.
"Read weight should be at most 1 ms." assert!(
); W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
assert!( "Read weight should be at most 1 ms."
W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, );
"Write weight should be at most 1 ms." assert!(
); W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
} "Write weight should be at most 1 ms."
} );
}
}
} }
+42 -41
View File
@@ -16,48 +16,49 @@
// limitations under the License. // limitations under the License.
pub mod constants { pub mod constants {
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
weights::{constants, RuntimeDbWeight}, weights::{constants, RuntimeDbWeight},
}; };
parameter_types! { parameter_types! {
/// By default, Substrate uses `RocksDB`, so this will be the weight used throughout /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout
/// the runtime. /// the runtime.
pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight {
read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
}; };
} }
#[cfg(test)] #[cfg(test)]
mod test_db_weights { mod test_db_weights {
use super::constants::RocksDbWeight as W; use frame_support::weights::constants;
use frame_support::weights::constants;
/// Checks that all weights exist and have sane values. use super::constants::RocksDbWeight as W;
// NOTE: If this test fails but you are sure that the generated values are fine,
// you can delete it. /// Checks that all weights exist and have sane values.
#[test] // NOTE: If this test fails but you are sure that the generated values are fine,
fn sane() { // you can delete it.
// At least 1 µs. #[test]
assert!( fn sane() {
W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, // At least 1 µs.
"Read weight should be at least 1 µs." assert!(
); W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
assert!( "Read weight should be at least 1 µs."
W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, );
"Write weight should be at least 1 µs." assert!(
); W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
// At most 1 ms. "Write weight should be at least 1 µs."
assert!( );
W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, // At most 1 ms.
"Read weight should be at most 1 ms." assert!(
); W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
assert!( "Read weight should be at most 1 ms."
W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, );
"Write weight should be at most 1 ms." assert!(
); W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
} "Write weight should be at most 1 ms."
} );
}
}
} }
+144 -140
View File
@@ -1,11 +1,7 @@
use super::{
AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm,
Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue,
};
use frame_support::{ use frame_support::{
match_types, parameter_types, match_types, parameter_types,
traits::{ConstU32, Everything, Nothing}, traits::{ConstU32, Everything, Nothing},
weights::Weight, weights::Weight,
}; };
use frame_system::EnsureRoot; use frame_system::EnsureRoot;
use pallet_xcm::XcmPassthrough; use pallet_xcm::XcmPassthrough;
@@ -13,181 +9,189 @@ use polkadot_parachain_primitives::primitives::Sibling;
use polkadot_runtime_common::impls::ToAuthor; use polkadot_runtime_common::impls::ToAuthor;
use xcm::latest::prelude::*; use xcm::latest::prelude::*;
use xcm_builder::{ use xcm_builder::{
AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom,
CurrencyAdapter, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, CurrencyAdapter, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin,
FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset, RelayChainAsNative, FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset, RelayChainAsNative,
SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
UsingComponents, WithComputedOrigin, WithUniqueTopic, UsingComponents, WithComputedOrigin, WithUniqueTopic,
}; };
use xcm_executor::XcmExecutor; use xcm_executor::XcmExecutor;
use super::{
AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm,
Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue,
};
parameter_types! { parameter_types! {
pub const RelayLocation: MultiLocation = MultiLocation::parent(); pub const RelayLocation: MultiLocation = MultiLocation::parent();
pub const RelayNetwork: Option<NetworkId> = None; pub const RelayNetwork: Option<NetworkId> = None;
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); pub UniversalLocation: InteriorMultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
} }
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used /// Type for specifying how a `MultiLocation` can be converted into an
/// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `AccountId`. This is used when determining ownership of accounts for asset
/// `Transact` in order to determine the dispatch Origin. /// transacting and when attempting to use XCM `Transact` in order to determine
/// the dispatch Origin.
pub type LocationToAccountId = ( pub type LocationToAccountId = (
// The parent (Relay-chain) origin converts to the parent `AccountId`. // The parent (Relay-chain) origin converts to the parent `AccountId`.
ParentIsPreset<AccountId>, ParentIsPreset<AccountId>,
// Sibling parachain origins convert to AccountId via the `ParaId::into`. // Sibling parachain origins convert to AccountId via the `ParaId::into`.
SiblingParachainConvertsVia<Sibling, AccountId>, SiblingParachainConvertsVia<Sibling, AccountId>,
// Straight up local `AccountId32` origins just alias directly to `AccountId`. // Straight up local `AccountId32` origins just alias directly to `AccountId`.
AccountId32Aliases<RelayNetwork, AccountId>, AccountId32Aliases<RelayNetwork, AccountId>,
); );
/// Means for transacting assets on this chain. /// Means for transacting assets on this chain.
pub type LocalAssetTransactor = CurrencyAdapter< pub type LocalAssetTransactor = CurrencyAdapter<
// Use this currency: // Use this currency:
Balances, Balances,
// Use this currency when it is a fungible asset matching the given location or name: // Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RelayLocation>, IsConcrete<RelayLocation>,
// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
LocationToAccountId, LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly): // Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId, AccountId,
// We don't track any teleports. // We don't track any teleports.
(), (),
>; >;
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, /// This is the type we use to convert an (incoming) XCM origin into a local
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can /// `Origin` instance, ready for dispatching a transaction with Xcm's
/// biases the kind of local `Origin` it will become. /// `Transact`. There is an `OriginKind` which can biases the kind of local
/// `Origin` it will become.
pub type XcmOriginToTransactDispatchOrigin = ( pub type XcmOriginToTransactDispatchOrigin = (
// Sovereign account converter; this attempts to derive an `AccountId` from the origin location // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
// foreign chains who want to have a local sovereign account on this chain which they control. // foreign chains who want to have a local sovereign account on this chain which they control.
SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>, SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
// Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
// recognized. // recognized.
RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>, RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
// recognized. // recognized.
SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>, SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
// Native signed account converter; this just converts an `AccountId32` origin into a normal // Native signed account converter; this just converts an `AccountId32` origin into a normal
// `RuntimeOrigin::Signed` origin of the same 32-byte value. // `RuntimeOrigin::Signed` origin of the same 32-byte value.
SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>, SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
// Xcm origins can be represented natively under the Xcm pallet's Xcm origin. // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
XcmPassthrough<RuntimeOrigin>, XcmPassthrough<RuntimeOrigin>,
); );
parameter_types! { parameter_types! {
// One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024); pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
pub const MaxInstructions: u32 = 100; pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64; pub const MaxAssetsIntoHolding: u32 = 64;
} }
match_types! { match_types! {
pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = { pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } | MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }
}; };
} }
pub type Barrier = TrailingSetTopicAsId< pub type Barrier = TrailingSetTopicAsId<
DenyThenTry< DenyThenTry<
DenyReserveTransferToRelayChain, DenyReserveTransferToRelayChain,
( (
TakeWeightCredit, TakeWeightCredit,
WithComputedOrigin< WithComputedOrigin<
( (
AllowTopLevelPaidExecutionFrom<Everything>, AllowTopLevelPaidExecutionFrom<Everything>,
AllowExplicitUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>, AllowExplicitUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
// ^^^ Parent and its exec plurality get free execution // ^^^ Parent and its exec plurality get free execution
), ),
UniversalLocation, UniversalLocation,
ConstU32<8>, ConstU32<8>,
>, >,
), ),
>, >,
>; >;
pub struct XcmConfig; pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig { impl xcm_executor::Config for XcmConfig {
type RuntimeCall = RuntimeCall; type Aliasers = Nothing;
type XcmSender = XcmRouter; type AssetClaims = PolkadotXcm;
// How to withdraw and deposit an asset. type AssetExchanger = ();
type AssetTransactor = LocalAssetTransactor; type AssetLocker = ();
type OriginConverter = XcmOriginToTransactDispatchOrigin; // How to withdraw and deposit an asset.
type IsReserve = NativeAsset; type AssetTransactor = LocalAssetTransactor;
type IsTeleporter = (); // Teleporting is disabled. type AssetTrap = PolkadotXcm;
type UniversalLocation = UniversalLocation; type Barrier = Barrier;
type Barrier = Barrier; type CallDispatcher = RuntimeCall;
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>; type FeeManager = ();
type Trader = type IsReserve = NativeAsset;
UsingComponents<WeightToFee, RelayLocation, AccountId, Balances, ToAuthor<Runtime>>; type IsTeleporter = ();
type ResponseHandler = PolkadotXcm; type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type AssetTrap = PolkadotXcm; type MessageExporter = ();
type AssetClaims = PolkadotXcm; type OriginConverter = XcmOriginToTransactDispatchOrigin;
type SubscriptionService = PolkadotXcm; type PalletInstancesInfo = AllPalletsWithSystem;
type PalletInstancesInfo = AllPalletsWithSystem; type ResponseHandler = PolkadotXcm;
type MaxAssetsIntoHolding = MaxAssetsIntoHolding; type RuntimeCall = RuntimeCall;
type AssetLocker = (); type SafeCallFilter = Everything;
type AssetExchanger = (); type SubscriptionService = PolkadotXcm;
type FeeManager = (); type Trader =
type MessageExporter = (); UsingComponents<WeightToFee, RelayLocation, AccountId, Balances, ToAuthor<Runtime>>;
type UniversalAliases = Nothing; type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall; // Teleporting is disabled.
type SafeCallFilter = Everything; type UniversalLocation = UniversalLocation;
type Aliasers = Nothing; type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type XcmSender = XcmRouter;
} }
/// No local origins on this chain are allowed to dispatch XCM sends/executions. /// No local origins on this chain are allowed to dispatch XCM sends/executions.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>; pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
/// The means for routing XCM messages which are not for local execution into the right message /// The means for routing XCM messages which are not for local execution into
/// queues. /// the right message queues.
pub type XcmRouter = WithUniqueTopic<( pub type XcmRouter = WithUniqueTopic<(
// Two routers - use UMP to communicate with the relay chain: // Two routers - use UMP to communicate with the relay chain:
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, (), ()>, cumulus_primitives_utility::ParentAsUmp<ParachainSystem, (), ()>,
// ..and XCMP to communicate with the sibling chains. // ..and XCMP to communicate with the sibling chains.
XcmpQueue, XcmpQueue,
)>; )>;
#[cfg(feature = "runtime-benchmarks")] #[cfg(feature = "runtime-benchmarks")]
parameter_types! { parameter_types! {
pub ReachableDest: Option<MultiLocation> = Some(Parent.into()); pub ReachableDest: Option<MultiLocation> = Some(Parent.into());
} }
impl pallet_xcm::Config for Runtime { impl pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent; type AdminOrigin = EnsureRoot<AccountId>;
type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>; // ^ Override for AdvertisedXcmVersion default
type XcmRouter = XcmRouter; type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>; type Currency = Balances;
type XcmExecuteFilter = Nothing; type CurrencyMatcher = ();
// ^ Disable dispatchable execute on the XCM pallet. type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
// Needs to be `Everything` for local testing. type MaxLockers = ConstU32<8>;
type XcmExecutor = XcmExecutor<XcmConfig>; type MaxRemoteLockConsumers = ConstU32<0>;
type XcmTeleportFilter = Everything; #[cfg(feature = "runtime-benchmarks")]
type XcmReserveTransferFilter = Nothing; type ReachableDest = ReachableDest;
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>; type RemoteLockConsumerIdentifier = ();
type UniversalLocation = UniversalLocation; type RuntimeCall = RuntimeCall;
type RuntimeOrigin = RuntimeOrigin; type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall; type RuntimeOrigin = RuntimeOrigin;
type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type SovereignAccountOf = LocationToAccountId;
type TrustedLockers = ();
type UniversalLocation = UniversalLocation;
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type WeightInfo = pallet_xcm::TestWeightInfo;
type XcmExecuteFilter = Nothing;
// ^ Disable dispatchable execute on the XCM pallet.
// Needs to be `Everything` for local testing.
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmReserveTransferFilter = Nothing;
type XcmRouter = XcmRouter;
type XcmTeleportFilter = Everything;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
// ^ Override for AdvertisedXcmVersion default
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type TrustedLockers = ();
type SovereignAccountOf = LocationToAccountId;
type MaxLockers = ConstU32<8>;
type WeightInfo = pallet_xcm::TestWeightInfo;
#[cfg(feature = "runtime-benchmarks")]
type ReachableDest = ReachableDest;
type AdminOrigin = EnsureRoot<AccountId>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
} }
impl cumulus_pallet_xcm::Config for Runtime { impl cumulus_pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>; type XcmExecutor = XcmExecutor<XcmConfig>;
} }