mirror of
https://github.com/pezkuwichain/pezkuwi-runtime-templates.git
synced 2026-04-22 02:07:55 +00:00
base for testing new pallets
This commit is contained in:
Generated
+14800
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,8 @@
|
||||
[workspace]
|
||||
members = ["node", "pallets/template", "runtime"]
|
||||
package.edition = "2021"
|
||||
package.repository = "https://github.com/paritytech/polkadot-sdk"
|
||||
resolver = "2"
|
||||
|
||||
[profile.release]
|
||||
panic = "unwind"
|
||||
@@ -0,0 +1,93 @@
|
||||
[package]
|
||||
name = "parachain-template-node"
|
||||
version = "0.1.0"
|
||||
authors = ["Anonymous"]
|
||||
description = "A new Cumulus FRAME-based Substrate Node, ready for hacking together a parachain."
|
||||
license = "Unlicense"
|
||||
homepage = "https://substrate.io"
|
||||
repository.workspace = true
|
||||
edition.workspace = true
|
||||
build = "build.rs"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.4.6", features = ["derive"] }
|
||||
log = "0.4.20"
|
||||
codec = { package = "parity-scale-codec", version = "3.0.0" }
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
jsonrpsee = { version = "0.16.2", features = ["server"] }
|
||||
futures = "0.3.28"
|
||||
|
||||
# Local
|
||||
parachain-template-runtime = { path = "../runtime" }
|
||||
|
||||
# Substrate
|
||||
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-chain-spec = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-sysinfo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-tracing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
substrate-prometheus-endpoint = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
|
||||
# Polkadot
|
||||
polkadot-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", features = [
|
||||
"rococo-native",
|
||||
] }
|
||||
polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
|
||||
# Cumulus
|
||||
cumulus-client-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-client-collator = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-client-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-client-consensus-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-client-consensus-proposer = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-client-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-relay-chain-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
color-print = "0.3.4"
|
||||
|
||||
[build-dependencies]
|
||||
substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
runtime-benchmarks = [
|
||||
"frame-benchmarking-cli/runtime-benchmarks",
|
||||
"frame-benchmarking/runtime-benchmarks",
|
||||
"parachain-template-runtime/runtime-benchmarks",
|
||||
"polkadot-cli/runtime-benchmarks",
|
||||
"polkadot-primitives/runtime-benchmarks",
|
||||
"sc-service/runtime-benchmarks",
|
||||
"sp-runtime/runtime-benchmarks",
|
||||
]
|
||||
try-runtime = [
|
||||
"parachain-template-runtime/try-runtime",
|
||||
"polkadot-cli/try-runtime",
|
||||
"sp-runtime/try-runtime",
|
||||
]
|
||||
@@ -0,0 +1,7 @@
|
||||
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
|
||||
|
||||
fn main() {
|
||||
generate_cargo_keys();
|
||||
|
||||
rerun_if_git_head_changed();
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use cumulus_primitives_core::ParaId;
|
||||
use parachain_template_runtime::{AccountId, AuraId, Signature, EXISTENTIAL_DEPOSIT};
|
||||
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
|
||||
use sc_service::ChainType;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sp_core::{sr25519, Pair, Public};
|
||||
use sp_runtime::traits::{IdentifyAccount, Verify};
|
||||
|
||||
/// Specialized `ChainSpec` for the normal parachain runtime.
|
||||
pub type ChainSpec =
|
||||
sc_service::GenericChainSpec<parachain_template_runtime::RuntimeGenesisConfig, Extensions>;
|
||||
|
||||
/// The default XCM version to set in genesis config.
|
||||
const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION;
|
||||
|
||||
/// Helper function to generate a crypto pair from seed
|
||||
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
|
||||
TPublic::Pair::from_string(&format!("//{}", seed), None)
|
||||
.expect("static values are valid; qed")
|
||||
.public()
|
||||
}
|
||||
|
||||
/// The extensions for the [`ChainSpec`].
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Extensions {
|
||||
/// The relay chain of the Parachain.
|
||||
pub relay_chain: String,
|
||||
/// The id of the Parachain.
|
||||
pub para_id: u32,
|
||||
}
|
||||
|
||||
impl Extensions {
|
||||
/// Try to get the extension from the given `ChainSpec`.
|
||||
pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {
|
||||
sc_chain_spec::get_extension(chain_spec.extensions())
|
||||
}
|
||||
}
|
||||
|
||||
type AccountPublic = <Signature as Verify>::Signer;
|
||||
|
||||
/// Generate collator keys from seed.
|
||||
///
|
||||
/// 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 {
|
||||
get_from_seed::<AuraId>(seed)
|
||||
}
|
||||
|
||||
/// Helper function to generate an account ID from seed
|
||||
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
|
||||
where
|
||||
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
|
||||
{
|
||||
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
|
||||
}
|
||||
|
||||
/// 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).
|
||||
pub fn template_session_keys(keys: AuraId) -> parachain_template_runtime::SessionKeys {
|
||||
parachain_template_runtime::SessionKeys { aura: keys }
|
||||
}
|
||||
|
||||
pub fn development_config() -> ChainSpec {
|
||||
// Give your base currency a unit name and decimal places
|
||||
let mut properties = sc_chain_spec::Properties::new();
|
||||
properties.insert("tokenSymbol".into(), "UNIT".into());
|
||||
properties.insert("tokenDecimals".into(), 12.into());
|
||||
properties.insert("ss58Format".into(), 42.into());
|
||||
|
||||
ChainSpec::from_genesis(
|
||||
// Name
|
||||
"Development",
|
||||
// ID
|
||||
"dev",
|
||||
ChainType::Development,
|
||||
move || {
|
||||
testnet_genesis(
|
||||
// initial collators.
|
||||
vec![
|
||||
(
|
||||
get_account_id_from_seed::<sr25519::Public>("Alice"),
|
||||
get_collator_keys_from_seed("Alice"),
|
||||
),
|
||||
(
|
||||
get_account_id_from_seed::<sr25519::Public>("Bob"),
|
||||
get_collator_keys_from_seed("Bob"),
|
||||
),
|
||||
],
|
||||
vec![
|
||||
get_account_id_from_seed::<sr25519::Public>("Alice"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Bob"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Charlie"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Dave"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Eve"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Ferdie"),
|
||||
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>("Charlie//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>("Ferdie//stash"),
|
||||
],
|
||||
get_account_id_from_seed::<sr25519::Public>("Alice"),
|
||||
1000.into(),
|
||||
)
|
||||
},
|
||||
Vec::new(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Extensions {
|
||||
relay_chain: "rococo-local".into(), // You MUST set this to the correct network!
|
||||
para_id: 1000,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn local_testnet_config() -> ChainSpec {
|
||||
// Give your base currency a unit name and decimal places
|
||||
let mut properties = sc_chain_spec::Properties::new();
|
||||
properties.insert("tokenSymbol".into(), "UNIT".into());
|
||||
properties.insert("tokenDecimals".into(), 12.into());
|
||||
properties.insert("ss58Format".into(), 42.into());
|
||||
|
||||
ChainSpec::from_genesis(
|
||||
// Name
|
||||
"Local Testnet",
|
||||
// ID
|
||||
"local_testnet",
|
||||
ChainType::Local,
|
||||
move || {
|
||||
testnet_genesis(
|
||||
// initial collators.
|
||||
vec![
|
||||
(
|
||||
get_account_id_from_seed::<sr25519::Public>("Alice"),
|
||||
get_collator_keys_from_seed("Alice"),
|
||||
),
|
||||
(
|
||||
get_account_id_from_seed::<sr25519::Public>("Bob"),
|
||||
get_collator_keys_from_seed("Bob"),
|
||||
),
|
||||
],
|
||||
vec![
|
||||
get_account_id_from_seed::<sr25519::Public>("Alice"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Bob"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Charlie"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Dave"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Eve"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Ferdie"),
|
||||
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>("Charlie//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>("Ferdie//stash"),
|
||||
],
|
||||
get_account_id_from_seed::<sr25519::Public>("Alice"),
|
||||
1000.into(),
|
||||
)
|
||||
},
|
||||
// Bootnodes
|
||||
Vec::new(),
|
||||
// Telemetry
|
||||
None,
|
||||
// Protocol ID
|
||||
Some("template-local"),
|
||||
// Fork ID
|
||||
None,
|
||||
// Properties
|
||||
Some(properties),
|
||||
// Extensions
|
||||
Extensions {
|
||||
relay_chain: "rococo-local".into(), // You MUST set this to the correct network!
|
||||
para_id: 1000,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn testnet_genesis(
|
||||
invulnerables: Vec<(AccountId, AuraId)>,
|
||||
endowed_accounts: Vec<AccountId>,
|
||||
root: AccountId,
|
||||
id: ParaId,
|
||||
) -> parachain_template_runtime::RuntimeGenesisConfig {
|
||||
parachain_template_runtime::RuntimeGenesisConfig {
|
||||
system: parachain_template_runtime::SystemConfig {
|
||||
code: parachain_template_runtime::WASM_BINARY
|
||||
.expect("WASM binary was not build, please build it!")
|
||||
.to_vec(),
|
||||
..Default::default()
|
||||
},
|
||||
balances: parachain_template_runtime::BalancesConfig {
|
||||
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(),
|
||||
},
|
||||
parachain_info: parachain_template_runtime::ParachainInfoConfig {
|
||||
parachain_id: id,
|
||||
..Default::default()
|
||||
},
|
||||
collator_selection: parachain_template_runtime::CollatorSelectionConfig {
|
||||
invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(),
|
||||
candidacy_bond: EXISTENTIAL_DEPOSIT * 16,
|
||||
..Default::default()
|
||||
},
|
||||
session: parachain_template_runtime::SessionConfig {
|
||||
keys: invulnerables
|
||||
.into_iter()
|
||||
.map(|(acc, aura)| {
|
||||
(
|
||||
acc.clone(), // account id
|
||||
acc, // validator id
|
||||
template_session_keys(aura), // session keys
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
// no need to pass anything to aura, in fact it will panic if we do. Session will take care
|
||||
// of this.
|
||||
aura: Default::default(),
|
||||
aura_ext: Default::default(),
|
||||
parachain_system: Default::default(),
|
||||
polkadot_xcm: parachain_template_runtime::PolkadotXcmConfig {
|
||||
safe_xcm_version: Some(SAFE_XCM_VERSION),
|
||||
..Default::default()
|
||||
},
|
||||
transaction_payment: Default::default(),
|
||||
sudo: parachain_template_runtime::SudoConfig { key: Some(root) },
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Sub-commands supported by the collator.
|
||||
#[derive(Debug, clap::Subcommand)]
|
||||
pub enum Subcommand {
|
||||
/// Build a chain specification.
|
||||
BuildSpec(sc_cli::BuildSpecCmd),
|
||||
|
||||
/// Validate blocks.
|
||||
CheckBlock(sc_cli::CheckBlockCmd),
|
||||
|
||||
/// Export blocks.
|
||||
ExportBlocks(sc_cli::ExportBlocksCmd),
|
||||
|
||||
/// Export the state of a given block into a chain spec.
|
||||
ExportState(sc_cli::ExportStateCmd),
|
||||
|
||||
/// Import blocks.
|
||||
ImportBlocks(sc_cli::ImportBlocksCmd),
|
||||
|
||||
/// Revert the chain to a previous state.
|
||||
Revert(sc_cli::RevertCmd),
|
||||
|
||||
/// Remove the whole chain.
|
||||
PurgeChain(cumulus_client_cli::PurgeChainCmd),
|
||||
|
||||
/// Export the genesis state of the parachain.
|
||||
ExportGenesisState(cumulus_client_cli::ExportGenesisStateCommand),
|
||||
|
||||
/// Export the genesis wasm of the parachain.
|
||||
ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand),
|
||||
|
||||
/// Sub-commands concerned with benchmarking.
|
||||
/// The pallet benchmarking moved to the `pallet` sub-command.
|
||||
#[command(subcommand)]
|
||||
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
|
||||
|
||||
/// Try-runtime has migrated to a standalone
|
||||
/// [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.
|
||||
TryRuntime,
|
||||
}
|
||||
|
||||
const AFTER_HELP_EXAMPLE: &str = color_print::cstr!(
|
||||
r#"<bold><underline>Examples:</></>
|
||||
<bold>parachain-template-node build-spec --disable-default-bootnode > plain-parachain-chainspec.json</>
|
||||
Export a chainspec for a local testnet in json format.
|
||||
<bold>parachain-template-node --chain plain-parachain-chainspec.json --tmp -- --chain rococo-local</>
|
||||
Launch a full node with chain specification loaded from plain-parachain-chainspec.json.
|
||||
<bold>parachain-template-node</>
|
||||
Launch a full node with default parachain <italic>local-testnet</> and relay chain <italic>rococo-local</>.
|
||||
<bold>parachain-template-node --collator</>
|
||||
Launch a collator with default parachain <italic>local-testnet</> and relay chain <italic>rococo-local</>.
|
||||
"#
|
||||
);
|
||||
#[derive(Debug, clap::Parser)]
|
||||
#[command(
|
||||
propagate_version = true,
|
||||
args_conflicts_with_subcommands = true,
|
||||
subcommand_negates_reqs = true
|
||||
)]
|
||||
#[clap(after_help = AFTER_HELP_EXAMPLE)]
|
||||
pub struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub subcommand: Option<Subcommand>,
|
||||
|
||||
#[command(flatten)]
|
||||
pub run: cumulus_client_cli::RunCmd,
|
||||
|
||||
/// Disable automatic hardware benchmarks.
|
||||
///
|
||||
/// By default these benchmarks are automatically ran at startup and measure
|
||||
/// 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
|
||||
/// telemetry, if telemetry is enabled.
|
||||
#[arg(long)]
|
||||
pub no_hardware_benchmarks: bool,
|
||||
|
||||
/// Relay chain arguments
|
||||
#[arg(raw = true)]
|
||||
pub relay_chain_args: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RelayChainCli {
|
||||
/// The actual relay chain cli object.
|
||||
pub base: polkadot_cli::RunCmd,
|
||||
|
||||
/// Optional chain id that should be passed to the relay chain.
|
||||
pub chain_id: Option<String>,
|
||||
|
||||
/// The base path that should be used by the relay chain.
|
||||
pub base_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl RelayChainCli {
|
||||
/// Parse the relay chain CLI parameters using the para chain `Configuration`.
|
||||
pub fn new<'a>(
|
||||
para_config: &sc_service::Configuration,
|
||||
relay_chain_args: impl Iterator<Item = &'a String>,
|
||||
) -> Self {
|
||||
let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec);
|
||||
let chain_id = extension.map(|e| e.relay_chain.clone());
|
||||
let base_path = para_config.base_path.path().join("polkadot");
|
||||
Self {
|
||||
base_path: Some(base_path),
|
||||
chain_id,
|
||||
base: clap::Parser::parse_from(relay_chain_args),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use cumulus_primitives_core::ParaId;
|
||||
use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
|
||||
use log::info;
|
||||
use parachain_template_runtime::Block;
|
||||
use sc_cli::{
|
||||
ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,
|
||||
NetworkParams, Result, SharedParams, SubstrateCli,
|
||||
};
|
||||
use sc_service::config::{BasePath, PrometheusConfig};
|
||||
use sp_runtime::traits::AccountIdConversion;
|
||||
|
||||
use crate::{
|
||||
chain_spec,
|
||||
cli::{Cli, RelayChainCli, Subcommand},
|
||||
service::new_partial,
|
||||
};
|
||||
|
||||
fn load_spec(id: &str) -> std::result::Result<Box<dyn ChainSpec>, String> {
|
||||
Ok(match id {
|
||||
"dev" => Box::new(chain_spec::development_config()),
|
||||
"template-rococo" => 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))?),
|
||||
})
|
||||
}
|
||||
|
||||
impl SubstrateCli for Cli {
|
||||
fn impl_name() -> String {
|
||||
"Parachain Collator Template".into()
|
||||
}
|
||||
|
||||
fn impl_version() -> String {
|
||||
env!("SUBSTRATE_CLI_IMPL_VERSION").into()
|
||||
}
|
||||
|
||||
fn description() -> String {
|
||||
format!(
|
||||
"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 \
|
||||
to the relay chain node.\n\n\
|
||||
{} <parachain-args> -- <relay-chain-args>",
|
||||
Self::executable_name()
|
||||
)
|
||||
}
|
||||
|
||||
fn author() -> String {
|
||||
env!("CARGO_PKG_AUTHORS").into()
|
||||
}
|
||||
|
||||
fn support_url() -> String {
|
||||
"https://github.com/paritytech/polkadot-sdk/issues/new".into()
|
||||
}
|
||||
|
||||
fn copyright_start_year() -> i32 {
|
||||
2020
|
||||
}
|
||||
|
||||
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
|
||||
load_spec(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl SubstrateCli for RelayChainCli {
|
||||
fn impl_name() -> String {
|
||||
"Parachain Collator Template".into()
|
||||
}
|
||||
|
||||
fn impl_version() -> String {
|
||||
env!("SUBSTRATE_CLI_IMPL_VERSION").into()
|
||||
}
|
||||
|
||||
fn description() -> String {
|
||||
format!(
|
||||
"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 \
|
||||
to the relay chain node.\n\n\
|
||||
{} <parachain-args> -- <relay-chain-args>",
|
||||
Self::executable_name()
|
||||
)
|
||||
}
|
||||
|
||||
fn author() -> String {
|
||||
env!("CARGO_PKG_AUTHORS").into()
|
||||
}
|
||||
|
||||
fn support_url() -> String {
|
||||
"https://github.com/paritytech/polkadot-sdk/issues/new".into()
|
||||
}
|
||||
|
||||
fn copyright_start_year() -> i32 {
|
||||
2020
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! construct_async_run {
|
||||
(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{
|
||||
let runner = $cli.create_runner($cmd)?;
|
||||
runner.async_run(|$config| {
|
||||
let $components = new_partial(&$config)?;
|
||||
let task_manager = $components.task_manager;
|
||||
{ $( $code )* }.map(|v| (v, task_manager))
|
||||
})
|
||||
}}
|
||||
}
|
||||
|
||||
/// Parse command line arguments into service configuration.
|
||||
pub fn run() -> Result<()> {
|
||||
let cli = Cli::from_args();
|
||||
|
||||
match &cli.subcommand {
|
||||
Some(Subcommand::BuildSpec(cmd)) => {
|
||||
let runner = cli.create_runner(cmd)?;
|
||||
runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
|
||||
},
|
||||
Some(Subcommand::CheckBlock(cmd)) => {
|
||||
construct_async_run!(|components, cli, cmd, config| {
|
||||
Ok(cmd.run(components.client, components.import_queue))
|
||||
})
|
||||
},
|
||||
Some(Subcommand::ExportBlocks(cmd)) => {
|
||||
construct_async_run!(|components, cli, cmd, config| {
|
||||
Ok(cmd.run(components.client, config.database))
|
||||
})
|
||||
},
|
||||
Some(Subcommand::ExportState(cmd)) => {
|
||||
construct_async_run!(|components, cli, cmd, config| {
|
||||
Ok(cmd.run(components.client, config.chain_spec))
|
||||
})
|
||||
},
|
||||
Some(Subcommand::ImportBlocks(cmd)) => {
|
||||
construct_async_run!(|components, cli, cmd, config| {
|
||||
Ok(cmd.run(components.client, components.import_queue))
|
||||
})
|
||||
},
|
||||
Some(Subcommand::Revert(cmd)) => {
|
||||
construct_async_run!(|components, cli, cmd, config| {
|
||||
Ok(cmd.run(components.client, components.backend, None))
|
||||
})
|
||||
},
|
||||
Some(Subcommand::PurgeChain(cmd)) => {
|
||||
let runner = cli.create_runner(cmd)?;
|
||||
|
||||
runner.sync_run(|config| {
|
||||
let polkadot_cli = RelayChainCli::new(
|
||||
&config,
|
||||
[RelayChainCli::executable_name()].iter().chain(cli.relay_chain_args.iter()),
|
||||
);
|
||||
|
||||
let polkadot_config = SubstrateCli::create_configuration(
|
||||
&polkadot_cli,
|
||||
&polkadot_cli,
|
||||
config.tokio_handle.clone(),
|
||||
)
|
||||
.map_err(|err| format!("Relay chain argument error: {}", err))?;
|
||||
|
||||
cmd.run(config, polkadot_config)
|
||||
})
|
||||
},
|
||||
Some(Subcommand::ExportGenesisState(cmd)) => {
|
||||
let runner = cli.create_runner(cmd)?;
|
||||
runner.sync_run(|config| {
|
||||
let partials = new_partial(&config)?;
|
||||
|
||||
cmd.run(&*config.chain_spec, &*partials.client)
|
||||
})
|
||||
},
|
||||
Some(Subcommand::ExportGenesisWasm(cmd)) => {
|
||||
let runner = cli.create_runner(cmd)?;
|
||||
runner.sync_run(|_config| {
|
||||
let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
|
||||
cmd.run(&*spec)
|
||||
})
|
||||
},
|
||||
Some(Subcommand::Benchmark(cmd)) => {
|
||||
let runner = cli.create_runner(cmd)?;
|
||||
// Switch on the concrete benchmark sub-command-
|
||||
match cmd {
|
||||
BenchmarkCmd::Pallet(cmd) =>
|
||||
if cfg!(feature = "runtime-benchmarks") {
|
||||
runner.sync_run(|config| cmd.run::<Block, ()>(config))
|
||||
} else {
|
||||
Err("Benchmarking wasn't enabled when building the node. \
|
||||
You can enable it with `--features runtime-benchmarks`."
|
||||
.into())
|
||||
},
|
||||
BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {
|
||||
let partials = new_partial(&config)?;
|
||||
cmd.run(partials.client)
|
||||
}),
|
||||
#[cfg(not(feature = "runtime-benchmarks"))]
|
||||
BenchmarkCmd::Storage(_) =>
|
||||
return Err(sc_cli::Error::Input(
|
||||
"Compile with --features=runtime-benchmarks \
|
||||
to enable storage benchmarks."
|
||||
.into(),
|
||||
)
|
||||
.into()),
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {
|
||||
let partials = new_partial(&config)?;
|
||||
let db = partials.backend.expose_db();
|
||||
let storage = partials.backend.expose_storage();
|
||||
cmd.run(config, partials.client.clone(), db, storage)
|
||||
}),
|
||||
BenchmarkCmd::Machine(cmd) =>
|
||||
runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone())),
|
||||
// NOTE: this allows the Client to leniently implement
|
||||
// new benchmark commands without requiring a companion MR.
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => Err("Benchmarking sub-command unsupported".into()),
|
||||
}
|
||||
},
|
||||
Some(Subcommand::TryRuntime) => Err("The `try-runtime` subcommand has been migrated to a standalone CLI (https://github.com/paritytech/try-runtime-cli). It is no longer being maintained here and will be removed entirely some time after January 2024. Please remove this subcommand from your runtime and use the standalone CLI.".into()),
|
||||
None => {
|
||||
let runner = cli.create_runner(&cli.run.normalize())?;
|
||||
let collator_options = cli.run.collator_options();
|
||||
|
||||
runner.run_node_until_exit(|config| async move {
|
||||
let hwbench = (!cli.no_hardware_benchmarks)
|
||||
.then_some(config.database.path().map(|database_path| {
|
||||
let _ = std::fs::create_dir_all(database_path);
|
||||
sc_sysinfo::gather_hwbench(Some(database_path))
|
||||
}))
|
||||
.flatten();
|
||||
|
||||
let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)
|
||||
.map(|e| e.para_id)
|
||||
.ok_or("Could not find parachain ID in chain-spec.")?;
|
||||
|
||||
let polkadot_cli = RelayChainCli::new(
|
||||
&config,
|
||||
[RelayChainCli::executable_name()].iter().chain(cli.relay_chain_args.iter()),
|
||||
);
|
||||
|
||||
let id = ParaId::from(para_id);
|
||||
|
||||
let parachain_account =
|
||||
AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(
|
||||
&id,
|
||||
);
|
||||
|
||||
let tokio_handle = config.tokio_handle.clone();
|
||||
let polkadot_config =
|
||||
SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, tokio_handle)
|
||||
.map_err(|err| format!("Relay chain argument error: {}", err))?;
|
||||
|
||||
info!("Parachain Account: {parachain_account}");
|
||||
info!("Is collating: {}", if config.role.is_authority() { "yes" } else { "no" });
|
||||
|
||||
crate::service::start_parachain_node(
|
||||
config,
|
||||
polkadot_config,
|
||||
collator_options,
|
||||
id,
|
||||
hwbench,
|
||||
)
|
||||
.await
|
||||
.map(|r| r.0)
|
||||
.map_err(Into::into)
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultConfigurationValues for RelayChainCli {
|
||||
fn p2p_listen_port() -> u16 {
|
||||
30334
|
||||
}
|
||||
|
||||
fn rpc_listen_port() -> u16 {
|
||||
9945
|
||||
}
|
||||
|
||||
fn prometheus_listen_port() -> u16 {
|
||||
9616
|
||||
}
|
||||
}
|
||||
|
||||
impl CliConfiguration<Self> for RelayChainCli {
|
||||
fn shared_params(&self) -> &SharedParams {
|
||||
self.base.base.shared_params()
|
||||
}
|
||||
|
||||
fn import_params(&self) -> Option<&ImportParams> {
|
||||
self.base.base.import_params()
|
||||
}
|
||||
|
||||
fn network_params(&self) -> Option<&NetworkParams> {
|
||||
self.base.base.network_params()
|
||||
}
|
||||
|
||||
fn keystore_params(&self) -> Option<&KeystoreParams> {
|
||||
self.base.base.keystore_params()
|
||||
}
|
||||
|
||||
fn base_path(&self) -> Result<Option<BasePath>> {
|
||||
Ok(self
|
||||
.shared_params()
|
||||
.base_path()?
|
||||
.or_else(|| self.base_path.clone().map(Into::into)))
|
||||
}
|
||||
|
||||
fn rpc_addr(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {
|
||||
self.base.base.rpc_addr(default_listen_port)
|
||||
}
|
||||
|
||||
fn prometheus_config(
|
||||
&self,
|
||||
default_listen_port: u16,
|
||||
chain_spec: &Box<dyn ChainSpec>,
|
||||
) -> Result<Option<PrometheusConfig>> {
|
||||
self.base.base.prometheus_config(default_listen_port, chain_spec)
|
||||
}
|
||||
|
||||
fn init<F>(
|
||||
&self,
|
||||
_support_url: &String,
|
||||
_impl_version: &String,
|
||||
_logger_hook: F,
|
||||
_config: &sc_service::Configuration,
|
||||
) -> Result<()>
|
||||
where
|
||||
F: FnOnce(&mut sc_cli::LoggerBuilder, &sc_service::Configuration),
|
||||
{
|
||||
unreachable!("PolkadotCli is never initialized; qed");
|
||||
}
|
||||
|
||||
fn chain_id(&self, is_dev: bool) -> Result<String> {
|
||||
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 })
|
||||
}
|
||||
|
||||
fn role(&self, is_dev: bool) -> Result<sc_service::Role> {
|
||||
self.base.base.role(is_dev)
|
||||
}
|
||||
|
||||
fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {
|
||||
self.base.base.transaction_pool(is_dev)
|
||||
}
|
||||
|
||||
fn trie_cache_maximum_size(&self) -> Result<Option<usize>> {
|
||||
self.base.base.trie_cache_maximum_size()
|
||||
}
|
||||
|
||||
fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {
|
||||
self.base.base.rpc_methods()
|
||||
}
|
||||
|
||||
fn rpc_max_connections(&self) -> Result<u32> {
|
||||
self.base.base.rpc_max_connections()
|
||||
}
|
||||
|
||||
fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {
|
||||
self.base.base.rpc_cors(is_dev)
|
||||
}
|
||||
|
||||
fn default_heap_pages(&self) -> Result<Option<u64>> {
|
||||
self.base.base.default_heap_pages()
|
||||
}
|
||||
|
||||
fn force_authoring(&self) -> Result<bool> {
|
||||
self.base.base.force_authoring()
|
||||
}
|
||||
|
||||
fn disable_grandpa(&self) -> Result<bool> {
|
||||
self.base.base.disable_grandpa()
|
||||
}
|
||||
|
||||
fn max_runtime_instances(&self) -> Result<Option<usize>> {
|
||||
self.base.base.max_runtime_instances()
|
||||
}
|
||||
|
||||
fn announce_block(&self) -> Result<bool> {
|
||||
self.base.base.announce_block()
|
||||
}
|
||||
|
||||
fn telemetry_endpoints(
|
||||
&self,
|
||||
chain_spec: &Box<dyn ChainSpec>,
|
||||
) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {
|
||||
self.base.base.telemetry_endpoints(chain_spec)
|
||||
}
|
||||
|
||||
fn node_name(&self) -> Result<String> {
|
||||
self.base.base.node_name()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Substrate Parachain Node Template CLI
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod chain_spec;
|
||||
#[macro_use]
|
||||
mod service;
|
||||
mod cli;
|
||||
mod command;
|
||||
mod rpc;
|
||||
|
||||
fn main() -> sc_cli::Result<()> {
|
||||
command::run()
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! A collection of node-specific RPC methods.
|
||||
//! Substrate provides the `sc-rpc` crate, which defines the core RPC layer
|
||||
//! used by Substrate nodes. This file extends those RPC definitions with
|
||||
//! capabilities that are specific to this project's runtime configuration.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use parachain_template_runtime::{opaque::Block, AccountId, Balance, Nonce};
|
||||
|
||||
use sc_client_api::AuxStore;
|
||||
pub use sc_rpc::{DenyUnsafe};
|
||||
use sc_transaction_pool_api::TransactionPool;
|
||||
use sp_api::ProvideRuntimeApi;
|
||||
use sp_block_builder::BlockBuilder;
|
||||
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
|
||||
|
||||
/// A type representing all RPC extensions.
|
||||
pub type RpcExtension = jsonrpsee::RpcModule<()>;
|
||||
|
||||
/// Full client dependencies
|
||||
pub struct FullDeps<C, P> {
|
||||
/// The client instance to use.
|
||||
pub client: Arc<C>,
|
||||
/// Transaction pool instance.
|
||||
pub pool: Arc<P>,
|
||||
/// Whether to deny unsafe calls
|
||||
pub deny_unsafe: DenyUnsafe,
|
||||
}
|
||||
|
||||
/// Instantiate all RPC extensions.
|
||||
pub fn create_full<C, P>(
|
||||
deps: FullDeps<C, P>,
|
||||
) -> Result<RpcExtension, Box<dyn std::error::Error + Send + Sync>>
|
||||
where
|
||||
C: ProvideRuntimeApi<Block>
|
||||
+ HeaderBackend<Block>
|
||||
+ AuxStore
|
||||
+ HeaderMetadata<Block, Error = BlockChainError>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
|
||||
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>,
|
||||
C::Api: BlockBuilder<Block>,
|
||||
P: TransactionPool + Sync + Send + 'static,
|
||||
{
|
||||
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
|
||||
use substrate_frame_rpc_system::{System, SystemApiServer};
|
||||
|
||||
let mut module = RpcExtension::new(());
|
||||
let FullDeps { client, pool, deny_unsafe } = deps;
|
||||
|
||||
module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
|
||||
module.merge(TransactionPayment::new(client).into_rpc())?;
|
||||
Ok(module)
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
|
||||
|
||||
// std
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use cumulus_client_cli::CollatorOptions;
|
||||
// Local Runtime Types
|
||||
use parachain_template_runtime::{
|
||||
opaque::{Block, Hash},
|
||||
RuntimeApi,
|
||||
};
|
||||
|
||||
// Cumulus Imports
|
||||
use cumulus_client_collator::service::CollatorService;
|
||||
use cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport;
|
||||
use cumulus_client_consensus_proposer::Proposer;
|
||||
use cumulus_client_service::{
|
||||
build_network, build_relay_chain_interface, prepare_node_config, start_relay_chain_tasks,
|
||||
BuildNetworkParams, CollatorSybilResistance, DARecoveryProfile, StartRelayChainTasksParams,
|
||||
};
|
||||
use cumulus_primitives_core::{relay_chain::CollatorPair, ParaId};
|
||||
use cumulus_relay_chain_interface::{OverseerHandle, RelayChainInterface};
|
||||
|
||||
// Substrate Imports
|
||||
use frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE;
|
||||
use sc_client_api::Backend;
|
||||
use sc_consensus::ImportQueue;
|
||||
use sc_executor::{
|
||||
HeapAllocStrategy, NativeElseWasmExecutor, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY,
|
||||
};
|
||||
use sc_network::NetworkBlock;
|
||||
use sc_network_sync::SyncingService;
|
||||
use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager};
|
||||
use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};
|
||||
use sc_transaction_pool_api::OffchainTransactionPoolFactory;
|
||||
use sp_keystore::KeystorePtr;
|
||||
use substrate_prometheus_endpoint::Registry;
|
||||
|
||||
/// Native executor type.
|
||||
pub struct ParachainNativeExecutor;
|
||||
|
||||
impl sc_executor::NativeExecutionDispatch for ParachainNativeExecutor {
|
||||
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
|
||||
|
||||
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
|
||||
parachain_template_runtime::api::dispatch(method, data)
|
||||
}
|
||||
|
||||
fn native_version() -> sc_executor::NativeVersion {
|
||||
parachain_template_runtime::native_version()
|
||||
}
|
||||
}
|
||||
|
||||
type ParachainExecutor = NativeElseWasmExecutor<ParachainNativeExecutor>;
|
||||
|
||||
type ParachainClient = TFullClient<Block, RuntimeApi, ParachainExecutor>;
|
||||
|
||||
type ParachainBackend = TFullBackend<Block>;
|
||||
|
||||
type ParachainBlockImport = TParachainBlockImport<Block, Arc<ParachainClient>, ParachainBackend>;
|
||||
|
||||
/// 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
|
||||
/// be able to perform chain operations.
|
||||
pub fn new_partial(
|
||||
config: &Configuration,
|
||||
) -> Result<
|
||||
PartialComponents<
|
||||
ParachainClient,
|
||||
ParachainBackend,
|
||||
(),
|
||||
sc_consensus::DefaultImportQueue<Block>,
|
||||
sc_transaction_pool::FullPool<Block, ParachainClient>,
|
||||
(ParachainBlockImport, Option<Telemetry>, Option<TelemetryWorkerHandle>),
|
||||
>,
|
||||
sc_service::Error,
|
||||
> {
|
||||
let telemetry = config
|
||||
.telemetry_endpoints
|
||||
.clone()
|
||||
.filter(|x| !x.is_empty())
|
||||
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
|
||||
let worker = TelemetryWorker::new(16)?;
|
||||
let telemetry = worker.handle().new_telemetry(endpoints);
|
||||
Ok((worker, telemetry))
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
let heap_pages = config
|
||||
.default_heap_pages
|
||||
.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ });
|
||||
|
||||
let wasm = WasmExecutor::builder()
|
||||
.with_execution_method(config.wasm_method)
|
||||
.with_onchain_heap_alloc_strategy(heap_pages)
|
||||
.with_offchain_heap_alloc_strategy(heap_pages)
|
||||
.with_max_runtime_instances(config.max_runtime_instances)
|
||||
.with_runtime_cache_size(config.runtime_cache_size)
|
||||
.build();
|
||||
|
||||
let executor = ParachainExecutor::new_with_wasm_executor(wasm);
|
||||
|
||||
let (client, backend, keystore_container, task_manager) =
|
||||
sc_service::new_full_parts::<Block, RuntimeApi, _>(
|
||||
config,
|
||||
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
|
||||
executor,
|
||||
)?;
|
||||
let client = Arc::new(client);
|
||||
|
||||
let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
|
||||
|
||||
let telemetry = telemetry.map(|(worker, telemetry)| {
|
||||
task_manager.spawn_handle().spawn("telemetry", None, worker.run());
|
||||
telemetry
|
||||
});
|
||||
|
||||
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
|
||||
config.transaction_pool.clone(),
|
||||
config.role.is_authority().into(),
|
||||
config.prometheus_registry(),
|
||||
task_manager.spawn_essential_handle(),
|
||||
client.clone(),
|
||||
);
|
||||
|
||||
let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
|
||||
|
||||
let import_queue = build_import_queue(
|
||||
client.clone(),
|
||||
block_import.clone(),
|
||||
config,
|
||||
telemetry.as_ref().map(|telemetry| telemetry.handle()),
|
||||
&task_manager,
|
||||
)?;
|
||||
|
||||
Ok(PartialComponents {
|
||||
backend,
|
||||
client,
|
||||
import_queue,
|
||||
keystore_container,
|
||||
task_manager,
|
||||
transaction_pool,
|
||||
select_chain: (),
|
||||
other: (block_import, telemetry, telemetry_worker_handle),
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[sc_tracing::logging::prefix_logs_with("Parachain")]
|
||||
async fn start_node_impl(
|
||||
parachain_config: Configuration,
|
||||
polkadot_config: Configuration,
|
||||
collator_options: CollatorOptions,
|
||||
para_id: ParaId,
|
||||
hwbench: Option<sc_sysinfo::HwBench>,
|
||||
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)> {
|
||||
let parachain_config = prepare_node_config(parachain_config);
|
||||
|
||||
let params = new_partial(¶chain_config)?;
|
||||
let (block_import, mut telemetry, telemetry_worker_handle) = params.other;
|
||||
let net_config = sc_network::config::FullNetworkConfiguration::new(¶chain_config.network);
|
||||
|
||||
let client = params.client.clone();
|
||||
let backend = params.backend.clone();
|
||||
let mut task_manager = params.task_manager;
|
||||
|
||||
let (relay_chain_interface, collator_key) = build_relay_chain_interface(
|
||||
polkadot_config,
|
||||
¶chain_config,
|
||||
telemetry_worker_handle,
|
||||
&mut task_manager,
|
||||
collator_options.clone(),
|
||||
hwbench.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
|
||||
|
||||
let validator = parachain_config.role.is_authority();
|
||||
let prometheus_registry = parachain_config.prometheus_registry().cloned();
|
||||
let transaction_pool = params.transaction_pool.clone();
|
||||
let import_queue_service = params.import_queue.service();
|
||||
|
||||
let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =
|
||||
build_network(BuildNetworkParams {
|
||||
parachain_config: ¶chain_config,
|
||||
net_config,
|
||||
client: client.clone(),
|
||||
transaction_pool: transaction_pool.clone(),
|
||||
para_id,
|
||||
spawn_handle: task_manager.spawn_handle(),
|
||||
relay_chain_interface: relay_chain_interface.clone(),
|
||||
import_queue: params.import_queue,
|
||||
sybil_resistance_level: CollatorSybilResistance::Resistant, // because of Aura
|
||||
})
|
||||
.await?;
|
||||
|
||||
if parachain_config.offchain_worker.enabled {
|
||||
use futures::FutureExt;
|
||||
|
||||
task_manager.spawn_handle().spawn(
|
||||
"offchain-workers-runner",
|
||||
"offchain-work",
|
||||
sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
|
||||
runtime_api_provider: client.clone(),
|
||||
keystore: Some(params.keystore_container.keystore()),
|
||||
offchain_db: backend.offchain_storage(),
|
||||
transaction_pool: Some(OffchainTransactionPoolFactory::new(
|
||||
transaction_pool.clone(),
|
||||
)),
|
||||
network_provider: network.clone(),
|
||||
is_validator: parachain_config.role.is_authority(),
|
||||
enable_http_requests: false,
|
||||
custom_extensions: move |_| vec![],
|
||||
})
|
||||
.run(client.clone(), task_manager.spawn_handle())
|
||||
.boxed(),
|
||||
);
|
||||
}
|
||||
|
||||
let rpc_builder = {
|
||||
let client = client.clone();
|
||||
let transaction_pool = transaction_pool.clone();
|
||||
|
||||
Box::new(move |deny_unsafe, _| {
|
||||
let deps = crate::rpc::FullDeps {
|
||||
client: client.clone(),
|
||||
pool: transaction_pool.clone(),
|
||||
deny_unsafe,
|
||||
};
|
||||
|
||||
crate::rpc::create_full(deps).map_err(Into::into)
|
||||
})
|
||||
};
|
||||
|
||||
sc_service::spawn_tasks(sc_service::SpawnTasksParams {
|
||||
rpc_builder,
|
||||
client: client.clone(),
|
||||
transaction_pool: transaction_pool.clone(),
|
||||
task_manager: &mut task_manager,
|
||||
config: parachain_config,
|
||||
keystore: params.keystore_container.keystore(),
|
||||
backend,
|
||||
network: network.clone(),
|
||||
sync_service: sync_service.clone(),
|
||||
system_rpc_tx,
|
||||
tx_handler_controller,
|
||||
telemetry: telemetry.as_mut(),
|
||||
})?;
|
||||
|
||||
if let Some(hwbench) = hwbench {
|
||||
sc_sysinfo::print_hwbench(&hwbench);
|
||||
// Here you can check whether the hardware meets your chains' requirements. Putting a link
|
||||
// in there and swapping out the requirements for your own are probably a good idea. The
|
||||
// requirements for a para-chain are dictated by its relay-chain.
|
||||
if !SUBSTRATE_REFERENCE_HARDWARE.check_hardware(&hwbench) && validator {
|
||||
log::warn!(
|
||||
"⚠️ The hardware does not meet the minimal requirements for role 'Authority'."
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(ref mut telemetry) = telemetry {
|
||||
let telemetry_handle = telemetry.handle();
|
||||
task_manager.spawn_handle().spawn(
|
||||
"telemetry_hwbench",
|
||||
None,
|
||||
sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let announce_block = {
|
||||
let sync_service = sync_service.clone();
|
||||
Arc::new(move |hash, data| sync_service.announce_block(hash, data))
|
||||
};
|
||||
|
||||
let relay_chain_slot_duration = Duration::from_secs(6);
|
||||
|
||||
let overseer_handle = relay_chain_interface
|
||||
.overseer_handle()
|
||||
.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
|
||||
|
||||
start_relay_chain_tasks(StartRelayChainTasksParams {
|
||||
client: client.clone(),
|
||||
announce_block: announce_block.clone(),
|
||||
para_id,
|
||||
relay_chain_interface: relay_chain_interface.clone(),
|
||||
task_manager: &mut task_manager,
|
||||
da_recovery_profile: if validator {
|
||||
DARecoveryProfile::Collator
|
||||
} else {
|
||||
DARecoveryProfile::FullNode
|
||||
},
|
||||
import_queue: import_queue_service,
|
||||
relay_chain_slot_duration,
|
||||
recovery_handle: Box::new(overseer_handle.clone()),
|
||||
sync_service: sync_service.clone(),
|
||||
})?;
|
||||
|
||||
if validator {
|
||||
start_consensus(
|
||||
client.clone(),
|
||||
block_import,
|
||||
prometheus_registry.as_ref(),
|
||||
telemetry.as_ref().map(|t| t.handle()),
|
||||
&task_manager,
|
||||
relay_chain_interface.clone(),
|
||||
transaction_pool,
|
||||
sync_service.clone(),
|
||||
params.keystore_container.keystore(),
|
||||
relay_chain_slot_duration,
|
||||
para_id,
|
||||
collator_key.expect("Command line arguments do not allow this. qed"),
|
||||
overseer_handle,
|
||||
announce_block,
|
||||
)?;
|
||||
}
|
||||
|
||||
start_network.start_network();
|
||||
|
||||
Ok((task_manager, client))
|
||||
}
|
||||
|
||||
/// Build the import queue for the parachain runtime.
|
||||
fn build_import_queue(
|
||||
client: Arc<ParachainClient>,
|
||||
block_import: ParachainBlockImport,
|
||||
config: &Configuration,
|
||||
telemetry: Option<TelemetryHandle>,
|
||||
task_manager: &TaskManager,
|
||||
) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error> {
|
||||
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
|
||||
|
||||
Ok(cumulus_client_consensus_aura::equivocation_import_queue::fully_verifying_import_queue::<
|
||||
sp_consensus_aura::sr25519::AuthorityPair,
|
||||
_,
|
||||
_,
|
||||
_,
|
||||
_,
|
||||
>(
|
||||
client,
|
||||
block_import,
|
||||
move |_, _| async move {
|
||||
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
|
||||
Ok(timestamp)
|
||||
},
|
||||
slot_duration,
|
||||
&task_manager.spawn_essential_handle(),
|
||||
config.prometheus_registry(),
|
||||
telemetry,
|
||||
))
|
||||
}
|
||||
|
||||
fn start_consensus(
|
||||
client: Arc<ParachainClient>,
|
||||
block_import: ParachainBlockImport,
|
||||
prometheus_registry: Option<&Registry>,
|
||||
telemetry: Option<TelemetryHandle>,
|
||||
task_manager: &TaskManager,
|
||||
relay_chain_interface: Arc<dyn RelayChainInterface>,
|
||||
transaction_pool: Arc<sc_transaction_pool::FullPool<Block, ParachainClient>>,
|
||||
sync_oracle: Arc<SyncingService<Block>>,
|
||||
keystore: KeystorePtr,
|
||||
relay_chain_slot_duration: Duration,
|
||||
para_id: ParaId,
|
||||
collator_key: CollatorPair,
|
||||
overseer_handle: OverseerHandle,
|
||||
announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
|
||||
) -> Result<(), sc_service::Error> {
|
||||
use cumulus_client_consensus_aura::collators::basic::{
|
||||
self as basic_aura, Params as BasicAuraParams,
|
||||
};
|
||||
|
||||
// NOTE: because we use Aura here explicitly, we can use `CollatorSybilResistance::Resistant`
|
||||
// when starting the network.
|
||||
|
||||
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
|
||||
|
||||
let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
|
||||
task_manager.spawn_handle(),
|
||||
client.clone(),
|
||||
transaction_pool,
|
||||
prometheus_registry,
|
||||
telemetry.clone(),
|
||||
);
|
||||
|
||||
let proposer = Proposer::new(proposer_factory);
|
||||
|
||||
let collator_service = CollatorService::new(
|
||||
client.clone(),
|
||||
Arc::new(task_manager.spawn_handle()),
|
||||
announce_block,
|
||||
client.clone(),
|
||||
);
|
||||
|
||||
let params = BasicAuraParams {
|
||||
create_inherent_data_providers: move |_, ()| async move { Ok(()) },
|
||||
block_import,
|
||||
para_client: client,
|
||||
relay_client: relay_chain_interface,
|
||||
sync_oracle,
|
||||
keystore,
|
||||
collator_key,
|
||||
para_id,
|
||||
overseer_handle,
|
||||
slot_duration,
|
||||
relay_chain_slot_duration,
|
||||
proposer,
|
||||
collator_service,
|
||||
// Very limited proposal time.
|
||||
authoring_duration: Duration::from_millis(500),
|
||||
collation_request_receiver: None,
|
||||
};
|
||||
|
||||
let fut =
|
||||
basic_aura::run::<Block, sp_consensus_aura::sr25519::AuthorityPair, _, _, _, _, _, _, _>(
|
||||
params,
|
||||
);
|
||||
task_manager.spawn_essential_handle().spawn("aura", None, fut);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start a parachain node.
|
||||
pub async fn start_parachain_node(
|
||||
parachain_config: Configuration,
|
||||
polkadot_config: Configuration,
|
||||
collator_options: CollatorOptions,
|
||||
para_id: ParaId,
|
||||
hwbench: Option<sc_sysinfo::HwBench>,
|
||||
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)> {
|
||||
start_node_impl(parachain_config, polkadot_config, collator_options, para_id, hwbench).await
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
[package]
|
||||
name = "pallet-parachain-template"
|
||||
authors = ["Anonymous"]
|
||||
description = "FRAME pallet template for defining custom runtime logic."
|
||||
version = "0.1.0"
|
||||
license = "Unlicense"
|
||||
homepage = "https://substrate.io"
|
||||
repository.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.0.0", features = [
|
||||
"derive",
|
||||
], default-features = false }
|
||||
scale-info = { version = "2.10.0", default-features = false, features = [
|
||||
"derive",
|
||||
] }
|
||||
# parity-scale-codec = { version = "3.1.5", default-features = false }
|
||||
# scale-info = { version = "2.1.2", default-features = false }
|
||||
|
||||
# Substrate
|
||||
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false, optional = true }
|
||||
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
serde = { version = "1.0.188" }
|
||||
|
||||
# Substrate
|
||||
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
runtime-benchmarks = [
|
||||
"frame-benchmarking/runtime-benchmarks",
|
||||
"frame-support/runtime-benchmarks",
|
||||
"frame-system/runtime-benchmarks",
|
||||
"sp-runtime/runtime-benchmarks",
|
||||
]
|
||||
std = [
|
||||
"codec/std",
|
||||
"frame-benchmarking/std",
|
||||
"frame-support/std",
|
||||
"frame-system/std",
|
||||
"scale-info/std",
|
||||
"sp-core/std",
|
||||
"sp-io/std",
|
||||
"sp-runtime/std",
|
||||
]
|
||||
try-runtime = [
|
||||
"frame-support/try-runtime",
|
||||
"frame-system/try-runtime",
|
||||
"sp-runtime/try-runtime",
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
License: Unlicense
|
||||
@@ -0,0 +1,20 @@
|
||||
//! 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_system::RawOrigin;
|
||||
|
||||
benchmarks! {
|
||||
do_something {
|
||||
let s in 0 .. 100;
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
}: _(RawOrigin::Signed(caller), s)
|
||||
verify {
|
||||
assert_eq!(Something::<T>::get(), Some(s));
|
||||
}
|
||||
}
|
||||
|
||||
impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,);
|
||||
@@ -0,0 +1,106 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
/// Edit this file to define custom logic or remove it if it is not needed.
|
||||
/// Learn more about FRAME and the core library of Substrate FRAME pallets:
|
||||
/// <https://docs.substrate.io/v3/runtime/frame>
|
||||
pub use pallet::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod mock;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
mod benchmarking;
|
||||
|
||||
#[frame_support::pallet]
|
||||
pub mod pallet {
|
||||
use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*};
|
||||
use frame_system::pallet_prelude::*;
|
||||
|
||||
/// Configure the pallet by specifying the parameters and types on which it depends.
|
||||
#[pallet::config]
|
||||
pub trait Config: frame_system::Config {
|
||||
/// 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]
|
||||
pub struct Pallet<T>(_);
|
||||
|
||||
// The pallet's runtime storage items.
|
||||
// https://docs.substrate.io/v3/runtime/storage
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn something)]
|
||||
// Learn more about declaring storage items:
|
||||
// https://docs.substrate.io/v3/runtime/storage#declaring-storage-items
|
||||
pub type Something<T> = StorageValue<_, u32>;
|
||||
|
||||
// Pallets use events to inform users when important changes are made.
|
||||
// https://docs.substrate.io/v3/runtime/events-and-errors
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(pub(super) fn deposit_event)]
|
||||
pub enum Event<T: Config> {
|
||||
/// Event documentation should end with an array that provides descriptive names for event
|
||||
/// parameters. [something, who]
|
||||
SomethingStored(u32, T::AccountId),
|
||||
}
|
||||
|
||||
// Errors inform users that something went wrong.
|
||||
#[pallet::error]
|
||||
pub enum Error<T> {
|
||||
/// Error names should be descriptive.
|
||||
NoneValue,
|
||||
/// Errors should have helpful documentation associated with them.
|
||||
StorageOverflow,
|
||||
}
|
||||
|
||||
#[pallet::hooks]
|
||||
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
|
||||
|
||||
// Dispatchable functions allows users to interact with the pallet and invoke state changes.
|
||||
// These functions materialize as "extrinsics", which are often compared to transactions.
|
||||
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
|
||||
#[pallet::call]
|
||||
impl<T: Config> Pallet<T> {
|
||||
/// An example dispatchable that takes a singles value as a parameter, writes the value to
|
||||
/// storage and emits an event. This function must be dispatched by a signed extrinsic.
|
||||
#[pallet::call_index(0)]
|
||||
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
|
||||
pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResultWithPostInfo {
|
||||
// Check that the extrinsic was signed and get the signer.
|
||||
// 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.
|
||||
<Something<T>>::put(something);
|
||||
|
||||
// Emit an event.
|
||||
Self::deposit_event(Event::SomethingStored(something, who));
|
||||
// Return a successful DispatchResultWithPostInfo
|
||||
Ok(().into())
|
||||
}
|
||||
|
||||
/// An example dispatchable that may throw a custom error.
|
||||
#[pallet::call_index(1)]
|
||||
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().reads_writes(1,1))]
|
||||
pub fn cause_error(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
|
||||
let _who = ensure_signed(origin)?;
|
||||
|
||||
// Read a value from storage.
|
||||
match <Something<T>>::get() {
|
||||
// Return an error if the value has not been set.
|
||||
None => Err(Error::<T>::NoneValue)?,
|
||||
Some(old) => {
|
||||
// Increment the value read from storage; will error in the event of overflow.
|
||||
let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?;
|
||||
// Update the value in storage with the incremented result.
|
||||
<Something<T>>::put(new);
|
||||
Ok(().into())
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use frame_support::{parameter_types, traits::Everything};
|
||||
use frame_system as system;
|
||||
use sp_core::H256;
|
||||
use sp_runtime::{
|
||||
traits::{BlakeTwo256, IdentityLookup},
|
||||
BuildStorage,
|
||||
};
|
||||
|
||||
type Block = frame_system::mocking::MockBlock<Test>;
|
||||
|
||||
// Configure a mock runtime to test the pallet.
|
||||
frame_support::construct_runtime!(
|
||||
pub enum Test
|
||||
{
|
||||
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
|
||||
TemplateModule: crate::{Pallet, Call, Storage, Event<T>},
|
||||
}
|
||||
);
|
||||
|
||||
parameter_types! {
|
||||
pub const BlockHashCount: u64 = 250;
|
||||
pub const SS58Prefix: u8 = 42;
|
||||
}
|
||||
|
||||
impl system::Config for Test {
|
||||
type BaseCallFilter = Everything;
|
||||
type BlockWeights = ();
|
||||
type BlockLength = ();
|
||||
type DbWeight = ();
|
||||
type RuntimeOrigin = RuntimeOrigin;
|
||||
type RuntimeCall = RuntimeCall;
|
||||
type Nonce = u64;
|
||||
type Hash = H256;
|
||||
type Hashing = BlakeTwo256;
|
||||
type AccountId = u64;
|
||||
type Lookup = IdentityLookup<Self::AccountId>;
|
||||
type Block = Block;
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type BlockHashCount = BlockHashCount;
|
||||
type Version = ();
|
||||
type PalletInfo = PalletInfo;
|
||||
type AccountData = ();
|
||||
type OnNewAccount = ();
|
||||
type OnKilledAccount = ();
|
||||
type SystemWeightInfo = ();
|
||||
type SS58Prefix = SS58Prefix;
|
||||
type OnSetCode = ();
|
||||
type MaxConsumers = frame_support::traits::ConstU32<16>;
|
||||
}
|
||||
|
||||
impl crate::Config for Test {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
}
|
||||
|
||||
// Build genesis storage according to the mock runtime.
|
||||
pub fn new_test_ext() -> sp_io::TestExternalities {
|
||||
system::GenesisConfig::<Test>::default().build_storage().unwrap().into()
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use crate::{mock::*, Error};
|
||||
use frame_support::{assert_noop, assert_ok};
|
||||
|
||||
#[test]
|
||||
fn it_works_for_default_value() {
|
||||
new_test_ext().execute_with(|| {
|
||||
// Dispatch a signed extrinsic.
|
||||
assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42));
|
||||
// Read pallet storage and assert an expected result.
|
||||
assert_eq!(TemplateModule::something(), Some(42));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn correct_error_for_none_value() {
|
||||
new_test_ext().execute_with(|| {
|
||||
// Ensure the expected error is thrown when no value is present.
|
||||
assert_noop!(
|
||||
TemplateModule::cause_error(RuntimeOrigin::signed(1)),
|
||||
Error::<Test>::NoneValue
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"relaychain": {
|
||||
"bin": "../../polkadot/target/release/polkadot",
|
||||
"chain": "rococo-local",
|
||||
"nodes": [
|
||||
{
|
||||
"name": "alice",
|
||||
"wsPort": 9944,
|
||||
"port": 30444
|
||||
},
|
||||
{
|
||||
"name": "bob",
|
||||
"wsPort": 9955,
|
||||
"port": 30555
|
||||
}
|
||||
]
|
||||
},
|
||||
"parachains": [
|
||||
{
|
||||
"bin": "../target/release/polkadot-parachain",
|
||||
"id": "200",
|
||||
"balance": "1000000000000000000000",
|
||||
"nodes": [
|
||||
{
|
||||
"wsPort": 9988,
|
||||
"name": "alice",
|
||||
"port": 31200,
|
||||
"flags": [
|
||||
"--force-authoring",
|
||||
"--",
|
||||
"--execution=wasm"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"types": {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
[package]
|
||||
name = "parachain-template-runtime"
|
||||
version = "0.1.0"
|
||||
authors = ["Anonymous"]
|
||||
description = "A new Cumulus FRAME-based Substrate Runtime, ready for hacking together a parachain."
|
||||
license = "Unlicense"
|
||||
homepage = "https://substrate.io"
|
||||
repository.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[build-dependencies]
|
||||
substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", optional = true }
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [
|
||||
"derive",
|
||||
] }
|
||||
hex-literal = { version = "0.4.1", optional = true }
|
||||
log = { version = "0.4.20", default-features = false }
|
||||
scale-info = { version = "2.10.0", default-features = false, features = [
|
||||
"derive",
|
||||
] }
|
||||
smallvec = "1.11.0"
|
||||
|
||||
# Local
|
||||
pallet-parachain-template = { path = "../pallets/template", default-features = false }
|
||||
|
||||
# Substrate
|
||||
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false, optional = true }
|
||||
frame-executive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
frame-system-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false, optional = true }
|
||||
frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
frame-try-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false, optional = true }
|
||||
pallet-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-genesis-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
sp-version = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
|
||||
# Polkadot
|
||||
pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
polkadot-parachain-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
polkadot-runtime-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
|
||||
# Cumulus
|
||||
cumulus-pallet-aura-ext = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-pallet-dmp-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-pallet-parachain-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false, features = [
|
||||
"parameterized-consensus-hook",
|
||||
] }
|
||||
cumulus-pallet-session-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
cumulus-primitives-utility = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
pallet-collator-selection = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
parachain-info = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.3.0", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"codec/std",
|
||||
"cumulus-pallet-aura-ext/std",
|
||||
"cumulus-pallet-dmp-queue/std",
|
||||
"cumulus-pallet-parachain-system/std",
|
||||
"cumulus-pallet-session-benchmarking/std",
|
||||
"cumulus-pallet-xcm/std",
|
||||
"cumulus-pallet-xcmp-queue/std",
|
||||
"cumulus-primitives-core/std",
|
||||
"cumulus-primitives-utility/std",
|
||||
"frame-benchmarking?/std",
|
||||
"frame-executive/std",
|
||||
"frame-support/std",
|
||||
"frame-system-benchmarking?/std",
|
||||
"frame-system-rpc-runtime-api/std",
|
||||
"frame-system/std",
|
||||
"frame-try-runtime?/std",
|
||||
"log/std",
|
||||
"pallet-aura/std",
|
||||
"pallet-authorship/std",
|
||||
"pallet-balances/std",
|
||||
"pallet-collator-selection/std",
|
||||
"pallet-parachain-template/std",
|
||||
"pallet-session/std",
|
||||
"pallet-sudo/std",
|
||||
"pallet-timestamp/std",
|
||||
"pallet-transaction-payment-rpc-runtime-api/std",
|
||||
"pallet-transaction-payment/std",
|
||||
"pallet-xcm/std",
|
||||
"parachain-info/std",
|
||||
"polkadot-parachain-primitives/std",
|
||||
"polkadot-runtime-common/std",
|
||||
"scale-info/std",
|
||||
"sp-api/std",
|
||||
"sp-block-builder/std",
|
||||
"sp-consensus-aura/std",
|
||||
"sp-core/std",
|
||||
"sp-genesis-builder/std",
|
||||
"sp-inherents/std",
|
||||
"sp-offchain/std",
|
||||
"sp-runtime/std",
|
||||
"sp-session/std",
|
||||
"sp-std/std",
|
||||
"sp-transaction-pool/std",
|
||||
"sp-version/std",
|
||||
"substrate-wasm-builder",
|
||||
"xcm-builder/std",
|
||||
"xcm-executor/std",
|
||||
"xcm/std",
|
||||
]
|
||||
|
||||
runtime-benchmarks = [
|
||||
"cumulus-pallet-parachain-system/runtime-benchmarks",
|
||||
"cumulus-pallet-session-benchmarking/runtime-benchmarks",
|
||||
"cumulus-pallet-xcmp-queue/runtime-benchmarks",
|
||||
"cumulus-primitives-utility/runtime-benchmarks",
|
||||
"frame-benchmarking/runtime-benchmarks",
|
||||
"frame-support/runtime-benchmarks",
|
||||
"frame-system-benchmarking/runtime-benchmarks",
|
||||
"frame-system/runtime-benchmarks",
|
||||
"hex-literal",
|
||||
"pallet-balances/runtime-benchmarks",
|
||||
"pallet-collator-selection/runtime-benchmarks",
|
||||
"pallet-parachain-template/runtime-benchmarks",
|
||||
"pallet-sudo/runtime-benchmarks",
|
||||
"pallet-timestamp/runtime-benchmarks",
|
||||
"pallet-xcm/runtime-benchmarks",
|
||||
"polkadot-parachain-primitives/runtime-benchmarks",
|
||||
"polkadot-runtime-common/runtime-benchmarks",
|
||||
"sp-runtime/runtime-benchmarks",
|
||||
"xcm-builder/runtime-benchmarks",
|
||||
"xcm-executor/runtime-benchmarks",
|
||||
]
|
||||
|
||||
try-runtime = [
|
||||
"cumulus-pallet-aura-ext/try-runtime",
|
||||
"cumulus-pallet-dmp-queue/try-runtime",
|
||||
"cumulus-pallet-parachain-system/try-runtime",
|
||||
"cumulus-pallet-xcm/try-runtime",
|
||||
"cumulus-pallet-xcmp-queue/try-runtime",
|
||||
"frame-executive/try-runtime",
|
||||
"frame-support/try-runtime",
|
||||
"frame-system/try-runtime",
|
||||
"frame-try-runtime/try-runtime",
|
||||
"pallet-aura/try-runtime",
|
||||
"pallet-authorship/try-runtime",
|
||||
"pallet-balances/try-runtime",
|
||||
"pallet-collator-selection/try-runtime",
|
||||
"pallet-parachain-template/try-runtime",
|
||||
"pallet-session/try-runtime",
|
||||
"pallet-sudo/try-runtime",
|
||||
"pallet-timestamp/try-runtime",
|
||||
"pallet-transaction-payment/try-runtime",
|
||||
"pallet-xcm/try-runtime",
|
||||
"parachain-info/try-runtime",
|
||||
"polkadot-runtime-common/try-runtime",
|
||||
"sp-runtime/try-runtime",
|
||||
]
|
||||
|
||||
experimental = ["pallet-aura/experimental"]
|
||||
@@ -0,0 +1,13 @@
|
||||
#[cfg(feature = "std")]
|
||||
fn main() {
|
||||
substrate_wasm_builder::WasmBuilder::new()
|
||||
.with_current_project()
|
||||
.export_heap_base()
|
||||
.import_memory()
|
||||
.build()
|
||||
}
|
||||
|
||||
/// The wasm builder is deactivated when compiling
|
||||
/// this crate for wasm to speed up the compilation.
|
||||
#[cfg(not(feature = "std"))]
|
||||
fn main() {}
|
||||
@@ -0,0 +1,764 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
// Make the WASM binary available.
|
||||
#[cfg(feature = "std")]
|
||||
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
|
||||
|
||||
mod weights;
|
||||
pub mod xcm_config;
|
||||
|
||||
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
|
||||
use cumulus_primitives_core::ParaId;
|
||||
use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery;
|
||||
use smallvec::smallvec;
|
||||
use sp_api::impl_runtime_apis;
|
||||
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
|
||||
use sp_runtime::{
|
||||
create_runtime_str, generic, impl_opaque_keys,
|
||||
traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify},
|
||||
transaction_validity::{TransactionSource, TransactionValidity},
|
||||
ApplyExtrinsicResult, MultiSignature,
|
||||
};
|
||||
|
||||
use sp_std::prelude::*;
|
||||
#[cfg(feature = "std")]
|
||||
use sp_version::NativeVersion;
|
||||
use sp_version::RuntimeVersion;
|
||||
|
||||
use frame_support::{
|
||||
construct_runtime,
|
||||
dispatch::DispatchClass,
|
||||
genesis_builder_helper::{build_config, create_default_config},
|
||||
parameter_types,
|
||||
traits::{ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Everything},
|
||||
weights::{
|
||||
constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, Weight, WeightToFeeCoefficient,
|
||||
WeightToFeeCoefficients, WeightToFeePolynomial,
|
||||
},
|
||||
PalletId,
|
||||
};
|
||||
use frame_system::{
|
||||
limits::{BlockLength, BlockWeights},
|
||||
EnsureRoot,
|
||||
};
|
||||
use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
|
||||
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
|
||||
pub use sp_runtime::{MultiAddress, Perbill, Permill};
|
||||
use xcm_config::{RelayLocation, XcmConfig, XcmOriginToTransactDispatchOrigin};
|
||||
|
||||
#[cfg(any(feature = "std", test))]
|
||||
pub use sp_runtime::BuildStorage;
|
||||
|
||||
// Polkadot imports
|
||||
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
|
||||
|
||||
use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
|
||||
|
||||
// XCM Imports
|
||||
use xcm::latest::prelude::BodyId;
|
||||
use xcm_executor::XcmExecutor;
|
||||
|
||||
/// Import the template pallet.
|
||||
pub use pallet_parachain_template;
|
||||
|
||||
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
|
||||
pub type Signature = MultiSignature;
|
||||
|
||||
/// Some way of identifying an account on the chain. We intentionally make it equivalent
|
||||
/// to the public key of our transaction signing scheme.
|
||||
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
|
||||
|
||||
/// Balance of an account.
|
||||
pub type Balance = u128;
|
||||
|
||||
/// Index of a transaction in the chain.
|
||||
pub type Nonce = u32;
|
||||
|
||||
/// A hash of some data used by the chain.
|
||||
pub type Hash = sp_core::H256;
|
||||
|
||||
/// An index to a block.
|
||||
pub type BlockNumber = u32;
|
||||
|
||||
/// The address format for describing accounts.
|
||||
pub type Address = MultiAddress<AccountId, ()>;
|
||||
|
||||
/// Block header type as expected by this runtime.
|
||||
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
|
||||
|
||||
/// Block type as expected by this runtime.
|
||||
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
|
||||
|
||||
/// A Block signed with a Justification
|
||||
pub type SignedBlock = generic::SignedBlock<Block>;
|
||||
|
||||
/// BlockId type as expected by this runtime.
|
||||
pub type BlockId = generic::BlockId<Block>;
|
||||
|
||||
/// The SignedExtension to the basic transaction logic.
|
||||
pub type SignedExtra = (
|
||||
frame_system::CheckNonZeroSender<Runtime>,
|
||||
frame_system::CheckSpecVersion<Runtime>,
|
||||
frame_system::CheckTxVersion<Runtime>,
|
||||
frame_system::CheckGenesis<Runtime>,
|
||||
frame_system::CheckEra<Runtime>,
|
||||
frame_system::CheckNonce<Runtime>,
|
||||
frame_system::CheckWeight<Runtime>,
|
||||
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
|
||||
);
|
||||
|
||||
/// Unchecked extrinsic type as expected by this runtime.
|
||||
pub type UncheckedExtrinsic =
|
||||
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
|
||||
|
||||
/// Executive: handles dispatch to the various modules.
|
||||
pub type Executive = frame_executive::Executive<
|
||||
Runtime,
|
||||
Block,
|
||||
frame_system::ChainContext<Runtime>,
|
||||
Runtime,
|
||||
AllPalletsWithSystem,
|
||||
>;
|
||||
|
||||
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
|
||||
/// node's balance type.
|
||||
///
|
||||
/// This should typically create a mapping between the following ranges:
|
||||
/// - `[0, MAXIMUM_BLOCK_WEIGHT]`
|
||||
/// - `[Balance::min, Balance::max]`
|
||||
///
|
||||
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
|
||||
/// - Setting it to `0` will essentially disable the weight fee.
|
||||
/// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
|
||||
pub struct WeightToFee;
|
||||
impl WeightToFeePolynomial for WeightToFee {
|
||||
type Balance = Balance;
|
||||
fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
|
||||
// in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
|
||||
// in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
|
||||
let p = MILLIUNIT / 10;
|
||||
let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
|
||||
smallvec![WeightToFeeCoefficient {
|
||||
degree: 1,
|
||||
negative: false,
|
||||
coeff_frac: Perbill::from_rational(p % q, q),
|
||||
coeff_integer: p / q,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
|
||||
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
|
||||
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
|
||||
/// to even the core data structures.
|
||||
pub mod opaque {
|
||||
use super::*;
|
||||
use sp_runtime::{
|
||||
generic,
|
||||
traits::{BlakeTwo256, Hash as HashT},
|
||||
};
|
||||
|
||||
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
|
||||
/// Opaque block header type.
|
||||
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
|
||||
/// Opaque block type.
|
||||
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
|
||||
/// Opaque block identifier type.
|
||||
pub type BlockId = generic::BlockId<Block>;
|
||||
/// Opaque block hash type.
|
||||
pub type Hash = <BlakeTwo256 as HashT>::Output;
|
||||
}
|
||||
|
||||
impl_opaque_keys! {
|
||||
pub struct SessionKeys {
|
||||
pub aura: Aura,
|
||||
}
|
||||
}
|
||||
|
||||
#[sp_version::runtime_version]
|
||||
pub const VERSION: RuntimeVersion = RuntimeVersion {
|
||||
spec_name: create_runtime_str!("template-parachain"),
|
||||
impl_name: create_runtime_str!("template-parachain"),
|
||||
authoring_version: 1,
|
||||
spec_version: 1,
|
||||
impl_version: 0,
|
||||
apis: RUNTIME_API_VERSIONS,
|
||||
transaction_version: 1,
|
||||
state_version: 1,
|
||||
};
|
||||
|
||||
/// This determines the average expected block time that we are targeting.
|
||||
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
|
||||
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
|
||||
/// up by `pallet_aura` to implement `fn slot_duration()`.
|
||||
///
|
||||
/// Change this to adjust the block time.
|
||||
pub const MILLISECS_PER_BLOCK: u64 = 12000;
|
||||
|
||||
// NOTE: Currently it is not possible to change the slot duration after the chain has started.
|
||||
// Attempting to do so will brick block production.
|
||||
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
|
||||
|
||||
// Time is measured by number of blocks.
|
||||
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
|
||||
pub const HOURS: BlockNumber = MINUTES * 60;
|
||||
pub const DAYS: BlockNumber = HOURS * 24;
|
||||
|
||||
// Unit = the base number of indivisible units for balances
|
||||
pub const UNIT: Balance = 1_000_000_000_000;
|
||||
pub const MILLIUNIT: Balance = 1_000_000_000;
|
||||
pub const MICROUNIT: Balance = 1_000_000;
|
||||
|
||||
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
|
||||
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
|
||||
|
||||
/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is
|
||||
/// used to limit the maximal weight of a single extrinsic.
|
||||
const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
|
||||
|
||||
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
|
||||
/// `Operational` extrinsics.
|
||||
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
|
||||
|
||||
/// We allow for 0.5 of a second of compute with a 12 second average block time.
|
||||
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
|
||||
WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
|
||||
cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
|
||||
);
|
||||
|
||||
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
|
||||
/// into the relay chain.
|
||||
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1;
|
||||
/// How many parachain blocks are processed by the relay chain per parent. Limits the
|
||||
/// number of blocks authored per slot.
|
||||
const BLOCK_PROCESSING_VELOCITY: u32 = 1;
|
||||
/// Relay chain slot duration, in milliseconds.
|
||||
const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
|
||||
|
||||
/// The version information used to identify this runtime when compiled natively.
|
||||
#[cfg(feature = "std")]
|
||||
pub fn native_version() -> NativeVersion {
|
||||
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const Version: RuntimeVersion = VERSION;
|
||||
|
||||
// This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
|
||||
// The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
|
||||
// `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
|
||||
// the lazy contract deletion.
|
||||
pub RuntimeBlockLength: BlockLength =
|
||||
BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
|
||||
pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
|
||||
.base_block(BlockExecutionWeight::get())
|
||||
.for_class(DispatchClass::all(), |weights| {
|
||||
weights.base_extrinsic = ExtrinsicBaseWeight::get();
|
||||
})
|
||||
.for_class(DispatchClass::Normal, |weights| {
|
||||
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
|
||||
})
|
||||
.for_class(DispatchClass::Operational, |weights| {
|
||||
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
|
||||
// Operational transactions have some extra reserved space, so that they
|
||||
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
|
||||
weights.reserved = Some(
|
||||
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
|
||||
);
|
||||
})
|
||||
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
|
||||
.build_or_panic();
|
||||
pub const SS58Prefix: u16 = 42;
|
||||
}
|
||||
|
||||
// Configure FRAME pallets to include in runtime.
|
||||
|
||||
impl frame_system::Config for Runtime {
|
||||
/// The identifier used to distinguish between accounts.
|
||||
type AccountId = AccountId;
|
||||
/// The aggregated dispatch type that is available for extrinsics.
|
||||
type RuntimeCall = RuntimeCall;
|
||||
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
|
||||
type Lookup = AccountIdLookup<AccountId, ()>;
|
||||
/// The index type for storing how many extrinsics an account has signed.
|
||||
type Nonce = Nonce;
|
||||
/// The type for hashing blocks and tries.
|
||||
type Hash = Hash;
|
||||
/// The hashing algorithm used.
|
||||
type Hashing = BlakeTwo256;
|
||||
/// The block type.
|
||||
type Block = Block;
|
||||
/// The ubiquitous event type.
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
/// The ubiquitous origin type.
|
||||
type RuntimeOrigin = RuntimeOrigin;
|
||||
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
|
||||
type BlockHashCount = BlockHashCount;
|
||||
/// Runtime version.
|
||||
type Version = Version;
|
||||
/// Converts a module to an index of this module in the runtime.
|
||||
type PalletInfo = PalletInfo;
|
||||
/// The data to be stored in an account.
|
||||
type AccountData = pallet_balances::AccountData<Balance>;
|
||||
/// What to do if a new account is created.
|
||||
type OnNewAccount = ();
|
||||
/// What to do if an account is fully reaped from the system.
|
||||
type OnKilledAccount = ();
|
||||
/// The weight of database operations that the runtime can invoke.
|
||||
type DbWeight = RocksDbWeight;
|
||||
/// The basic call filter to use in dispatchable.
|
||||
type BaseCallFilter = Everything;
|
||||
/// Weight information for the extrinsics of this pallet.
|
||||
type SystemWeightInfo = ();
|
||||
/// Block & extrinsics weights: base values and limits.
|
||||
type BlockWeights = RuntimeBlockWeights;
|
||||
/// The maximum length of a block (in bytes).
|
||||
type BlockLength = RuntimeBlockLength;
|
||||
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
|
||||
type SS58Prefix = SS58Prefix;
|
||||
/// The action to take on a Runtime Upgrade
|
||||
type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
|
||||
type MaxConsumers = frame_support::traits::ConstU32<16>;
|
||||
}
|
||||
|
||||
impl pallet_timestamp::Config for Runtime {
|
||||
/// A timestamp: milliseconds since the unix epoch.
|
||||
type Moment = u64;
|
||||
type OnTimestampSet = Aura;
|
||||
type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
impl pallet_authorship::Config for Runtime {
|
||||
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
|
||||
type EventHandler = (CollatorSelection,);
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
|
||||
}
|
||||
|
||||
impl pallet_balances::Config for Runtime {
|
||||
type MaxLocks = ConstU32<50>;
|
||||
/// The type for recording an account's balance.
|
||||
type Balance = Balance;
|
||||
/// The ubiquitous event type.
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type DustRemoval = ();
|
||||
type ExistentialDeposit = ExistentialDeposit;
|
||||
type AccountStore = System;
|
||||
type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
|
||||
type MaxReserves = ConstU32<50>;
|
||||
type ReserveIdentifier = [u8; 8];
|
||||
type RuntimeHoldReason = RuntimeHoldReason;
|
||||
type RuntimeFreezeReason = RuntimeFreezeReason;
|
||||
type FreezeIdentifier = ();
|
||||
type MaxHolds = ConstU32<0>;
|
||||
type MaxFreezes = ConstU32<0>;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
/// Relay Chain `TransactionByteFee` / 10
|
||||
pub const TransactionByteFee: Balance = 10 * MICROUNIT;
|
||||
}
|
||||
|
||||
impl pallet_transaction_payment::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;
|
||||
type WeightToFee = WeightToFee;
|
||||
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
|
||||
type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
|
||||
type OperationalFeeMultiplier = ConstU8<5>;
|
||||
}
|
||||
|
||||
impl pallet_sudo::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type RuntimeCall = RuntimeCall;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
|
||||
pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
|
||||
}
|
||||
|
||||
impl cumulus_pallet_parachain_system::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type OnSystemEvent = ();
|
||||
type SelfParaId = parachain_info::Pallet<Runtime>;
|
||||
type OutboundXcmpMessageSource = XcmpQueue;
|
||||
type DmpMessageHandler = DmpQueue;
|
||||
type ReservedDmpWeight = ReservedDmpWeight;
|
||||
type XcmpMessageHandler = XcmpQueue;
|
||||
type ReservedXcmpWeight = ReservedXcmpWeight;
|
||||
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
|
||||
type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
|
||||
Runtime,
|
||||
RELAY_CHAIN_SLOT_DURATION_MILLIS,
|
||||
BLOCK_PROCESSING_VELOCITY,
|
||||
UNINCLUDED_SEGMENT_CAPACITY,
|
||||
>;
|
||||
}
|
||||
|
||||
impl parachain_info::Config for Runtime {}
|
||||
|
||||
impl cumulus_pallet_aura_ext::Config for Runtime {}
|
||||
|
||||
impl cumulus_pallet_xcmp_queue::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type XcmExecutor = XcmExecutor<XcmConfig>;
|
||||
type ChannelInfo = ParachainSystem;
|
||||
type VersionWrapper = ();
|
||||
type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
|
||||
type ControllerOrigin = EnsureRoot<AccountId>;
|
||||
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
|
||||
type WeightInfo = ();
|
||||
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
|
||||
}
|
||||
|
||||
impl cumulus_pallet_dmp_queue::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type XcmExecutor = XcmExecutor<XcmConfig>;
|
||||
type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const Period: u32 = 6 * HOURS;
|
||||
pub const Offset: u32 = 0;
|
||||
}
|
||||
|
||||
impl pallet_session::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type ValidatorId = <Self as frame_system::Config>::AccountId;
|
||||
// we don't have stash and controller, thus we don't need the convert as well.
|
||||
type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
|
||||
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
|
||||
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
|
||||
type SessionManager = CollatorSelection;
|
||||
// Essentially just Aura, but let's be pedantic.
|
||||
type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
|
||||
type Keys = SessionKeys;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
impl pallet_aura::Config for Runtime {
|
||||
type AuthorityId = AuraId;
|
||||
type DisabledValidators = ();
|
||||
type MaxAuthorities = ConstU32<100_000>;
|
||||
type AllowMultipleBlocksPerSlot = ConstBool<false>;
|
||||
#[cfg(feature = "experimental")]
|
||||
type SlotDuration = pallet_aura::MinimumPeriodTimesTwo<Self>;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const PotId: PalletId = PalletId(*b"PotStake");
|
||||
pub const SessionLength: BlockNumber = 6 * HOURS;
|
||||
// StakingAdmin pluralistic body.
|
||||
pub const StakingAdminBodyId: BodyId = BodyId::Defense;
|
||||
}
|
||||
|
||||
/// We allow root and the StakingAdmin to execute privileged collator selection operations.
|
||||
pub type CollatorSelectionUpdateOrigin = EitherOfDiverse<
|
||||
EnsureRoot<AccountId>,
|
||||
EnsureXcm<IsVoiceOfBody<RelayLocation, StakingAdminBodyId>>,
|
||||
>;
|
||||
|
||||
impl pallet_collator_selection::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type Currency = Balances;
|
||||
type UpdateOrigin = CollatorSelectionUpdateOrigin;
|
||||
type PotId = PotId;
|
||||
type MaxCandidates = ConstU32<100>;
|
||||
type MinEligibleCollators = ConstU32<4>;
|
||||
type MaxInvulnerables = ConstU32<20>;
|
||||
// should be a multiple of session or things will get inconsistent
|
||||
type KickThreshold = Period;
|
||||
type ValidatorId = <Self as frame_system::Config>::AccountId;
|
||||
type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
|
||||
type ValidatorRegistration = Session;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
/// Configure the pallet template in pallets/template.
|
||||
impl pallet_parachain_template::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
}
|
||||
|
||||
// Create the runtime by composing the FRAME pallets that were previously configured.
|
||||
construct_runtime!(
|
||||
pub enum Runtime
|
||||
{
|
||||
// System support stuff.
|
||||
System: frame_system = 0,
|
||||
ParachainSystem: cumulus_pallet_parachain_system = 1,
|
||||
Timestamp: pallet_timestamp = 2,
|
||||
ParachainInfo: parachain_info = 3,
|
||||
|
||||
// Monetary stuff.
|
||||
Balances: pallet_balances = 10,
|
||||
TransactionPayment: pallet_transaction_payment = 11,
|
||||
|
||||
// Governance
|
||||
Sudo: pallet_sudo = 15,
|
||||
|
||||
// Collator support. The order of these 4 are important and shall not change.
|
||||
Authorship: pallet_authorship = 20,
|
||||
CollatorSelection: pallet_collator_selection = 21,
|
||||
Session: pallet_session = 22,
|
||||
Aura: pallet_aura = 23,
|
||||
AuraExt: cumulus_pallet_aura_ext = 24,
|
||||
|
||||
// XCM helpers.
|
||||
XcmpQueue: cumulus_pallet_xcmp_queue = 30,
|
||||
PolkadotXcm: pallet_xcm = 31,
|
||||
CumulusXcm: cumulus_pallet_xcm = 32,
|
||||
DmpQueue: cumulus_pallet_dmp_queue = 33,
|
||||
|
||||
// Template
|
||||
TemplatePallet: pallet_parachain_template = 50,
|
||||
}
|
||||
);
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
mod benches {
|
||||
frame_benchmarking::define_benchmarks!(
|
||||
[frame_system, SystemBench::<Runtime>]
|
||||
[pallet_balances, Balances]
|
||||
[pallet_session, SessionBench::<Runtime>]
|
||||
[pallet_timestamp, Timestamp]
|
||||
[pallet_sudo, Sudo]
|
||||
[pallet_collator_selection, CollatorSelection]
|
||||
[cumulus_pallet_xcmp_queue, XcmpQueue]
|
||||
);
|
||||
}
|
||||
|
||||
impl_runtime_apis! {
|
||||
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
|
||||
fn slot_duration() -> sp_consensus_aura::SlotDuration {
|
||||
sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
|
||||
}
|
||||
|
||||
fn authorities() -> Vec<AuraId> {
|
||||
Aura::authorities().into_inner()
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_api::Core<Block> for Runtime {
|
||||
fn version() -> RuntimeVersion {
|
||||
VERSION
|
||||
}
|
||||
|
||||
fn execute_block(block: Block) {
|
||||
Executive::execute_block(block)
|
||||
}
|
||||
|
||||
fn initialize_block(header: &<Block as BlockT>::Header) {
|
||||
Executive::initialize_block(header)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_api::Metadata<Block> for Runtime {
|
||||
fn metadata() -> OpaqueMetadata {
|
||||
OpaqueMetadata::new(Runtime::metadata().into())
|
||||
}
|
||||
|
||||
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
|
||||
Runtime::metadata_at_version(version)
|
||||
}
|
||||
|
||||
fn metadata_versions() -> sp_std::vec::Vec<u32> {
|
||||
Runtime::metadata_versions()
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_block_builder::BlockBuilder<Block> for Runtime {
|
||||
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
|
||||
Executive::apply_extrinsic(extrinsic)
|
||||
}
|
||||
|
||||
fn finalize_block() -> <Block as BlockT>::Header {
|
||||
Executive::finalize_block()
|
||||
}
|
||||
|
||||
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
|
||||
data.create_extrinsics()
|
||||
}
|
||||
|
||||
fn check_inherents(
|
||||
block: Block,
|
||||
data: sp_inherents::InherentData,
|
||||
) -> sp_inherents::CheckInherentsResult {
|
||||
data.check_extrinsics(&block)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
|
||||
fn validate_transaction(
|
||||
source: TransactionSource,
|
||||
tx: <Block as BlockT>::Extrinsic,
|
||||
block_hash: <Block as BlockT>::Hash,
|
||||
) -> TransactionValidity {
|
||||
Executive::validate_transaction(source, tx, block_hash)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
|
||||
fn offchain_worker(header: &<Block as BlockT>::Header) {
|
||||
Executive::offchain_worker(header)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_session::SessionKeys<Block> for Runtime {
|
||||
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
|
||||
SessionKeys::generate(seed)
|
||||
}
|
||||
|
||||
fn decode_session_keys(
|
||||
encoded: Vec<u8>,
|
||||
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
|
||||
SessionKeys::decode_into_raw_public_keys(&encoded)
|
||||
}
|
||||
}
|
||||
|
||||
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
|
||||
fn account_nonce(account: AccountId) -> Nonce {
|
||||
System::account_nonce(account)
|
||||
}
|
||||
}
|
||||
|
||||
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
|
||||
fn query_info(
|
||||
uxt: <Block as BlockT>::Extrinsic,
|
||||
len: u32,
|
||||
) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
|
||||
TransactionPayment::query_info(uxt, len)
|
||||
}
|
||||
fn query_fee_details(
|
||||
uxt: <Block as BlockT>::Extrinsic,
|
||||
len: u32,
|
||||
) -> pallet_transaction_payment::FeeDetails<Balance> {
|
||||
TransactionPayment::query_fee_details(uxt, len)
|
||||
}
|
||||
fn query_weight_to_fee(weight: Weight) -> Balance {
|
||||
TransactionPayment::weight_to_fee(weight)
|
||||
}
|
||||
fn query_length_to_fee(length: u32) -> Balance {
|
||||
TransactionPayment::length_to_fee(length)
|
||||
}
|
||||
}
|
||||
|
||||
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
|
||||
for Runtime
|
||||
{
|
||||
fn query_call_info(
|
||||
call: RuntimeCall,
|
||||
len: u32,
|
||||
) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
|
||||
TransactionPayment::query_call_info(call, len)
|
||||
}
|
||||
fn query_call_fee_details(
|
||||
call: RuntimeCall,
|
||||
len: u32,
|
||||
) -> pallet_transaction_payment::FeeDetails<Balance> {
|
||||
TransactionPayment::query_call_fee_details(call, len)
|
||||
}
|
||||
fn query_weight_to_fee(weight: Weight) -> Balance {
|
||||
TransactionPayment::weight_to_fee(weight)
|
||||
}
|
||||
fn query_length_to_fee(length: u32) -> Balance {
|
||||
TransactionPayment::length_to_fee(length)
|
||||
}
|
||||
}
|
||||
|
||||
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
|
||||
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
|
||||
ParachainSystem::collect_collation_info(header)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "try-runtime")]
|
||||
impl frame_try_runtime::TryRuntime<Block> for Runtime {
|
||||
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
|
||||
let weight = Executive::try_runtime_upgrade(checks).unwrap();
|
||||
(weight, RuntimeBlockWeights::get().max_block)
|
||||
}
|
||||
|
||||
fn execute_block(
|
||||
block: Block,
|
||||
state_root_check: bool,
|
||||
signature_check: bool,
|
||||
select: frame_try_runtime::TryStateSelect,
|
||||
) -> Weight {
|
||||
// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
|
||||
// have a backtrace here.
|
||||
Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
impl frame_benchmarking::Benchmark<Block> for Runtime {
|
||||
fn benchmark_metadata(extra: bool) -> (
|
||||
Vec<frame_benchmarking::BenchmarkList>,
|
||||
Vec<frame_support::traits::StorageInfo>,
|
||||
) {
|
||||
use frame_benchmarking::{Benchmarking, BenchmarkList};
|
||||
use frame_support::traits::StorageInfoTrait;
|
||||
use frame_system_benchmarking::Pallet as SystemBench;
|
||||
use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
|
||||
|
||||
let mut list = Vec::<BenchmarkList>::new();
|
||||
list_benchmarks!(list, extra);
|
||||
|
||||
let storage_info = AllPalletsWithSystem::storage_info();
|
||||
(list, storage_info)
|
||||
}
|
||||
|
||||
fn dispatch_benchmark(
|
||||
config: frame_benchmarking::BenchmarkConfig
|
||||
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
|
||||
use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch};
|
||||
|
||||
use frame_system_benchmarking::Pallet as SystemBench;
|
||||
impl frame_system_benchmarking::Config for Runtime {
|
||||
fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
|
||||
ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_set_code() {
|
||||
System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
|
||||
}
|
||||
}
|
||||
|
||||
use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
|
||||
impl cumulus_pallet_session_benchmarking::Config for Runtime {}
|
||||
|
||||
use frame_support::traits::WhitelistedStorageKeys;
|
||||
let whitelist = AllPalletsWithSystem::whitelisted_storage_keys();
|
||||
|
||||
let mut batches = Vec::<BenchmarkBatch>::new();
|
||||
let params = (&config, &whitelist);
|
||||
add_benchmarks!(params, batches);
|
||||
|
||||
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
|
||||
Ok(batches)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
|
||||
fn create_default_config() -> Vec<u8> {
|
||||
create_default_config::<RuntimeGenesisConfig>()
|
||||
}
|
||||
|
||||
fn build_config(config: Vec<u8>) -> sp_genesis_builder::Result {
|
||||
build_config::<RuntimeGenesisConfig>(config)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cumulus_pallet_parachain_system::register_validate_block! {
|
||||
Runtime = Runtime,
|
||||
BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
pub mod constants {
|
||||
use frame_support::{
|
||||
parameter_types,
|
||||
weights::{constants, Weight},
|
||||
};
|
||||
|
||||
parameter_types! {
|
||||
/// Importing a block with 0 Extrinsics.
|
||||
pub const BlockExecutionWeight: Weight =
|
||||
Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_weights {
|
||||
use frame_support::weights::constants;
|
||||
|
||||
/// Checks that the weight exists and is sane.
|
||||
// NOTE: If this test fails but you are sure that the generated values are fine,
|
||||
// you can delete it.
|
||||
#[test]
|
||||
fn sane() {
|
||||
let w = super::constants::BlockExecutionWeight::get();
|
||||
|
||||
// At least 100 µs.
|
||||
assert!(
|
||||
w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS,
|
||||
"Weight should be at least 100 µs."
|
||||
);
|
||||
// At most 50 ms.
|
||||
assert!(
|
||||
w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS,
|
||||
"Weight should be at most 50 ms."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
pub mod constants {
|
||||
use frame_support::{
|
||||
parameter_types,
|
||||
weights::{constants, Weight},
|
||||
};
|
||||
|
||||
parameter_types! {
|
||||
/// Executing a NO-OP `System::remarks` Extrinsic.
|
||||
pub const ExtrinsicBaseWeight: Weight =
|
||||
Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_weights {
|
||||
use frame_support::weights::constants;
|
||||
|
||||
/// Checks that the weight exists and is sane.
|
||||
// NOTE: If this test fails but you are sure that the generated values are fine,
|
||||
// you can delete it.
|
||||
#[test]
|
||||
fn sane() {
|
||||
let w = super::constants::ExtrinsicBaseWeight::get();
|
||||
|
||||
// At least 10 µs.
|
||||
assert!(
|
||||
w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS,
|
||||
"Weight should be at least 10 µs."
|
||||
);
|
||||
// At most 1 ms.
|
||||
assert!(
|
||||
w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
|
||||
"Weight should be at most 1 ms."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Expose the auto generated weight files.
|
||||
|
||||
pub mod block_weights;
|
||||
pub mod extrinsic_weights;
|
||||
pub mod paritydb_weights;
|
||||
pub mod rocksdb_weights;
|
||||
|
||||
pub use block_weights::constants::BlockExecutionWeight;
|
||||
pub use extrinsic_weights::constants::ExtrinsicBaseWeight;
|
||||
pub use rocksdb_weights::constants::RocksDbWeight;
|
||||
@@ -0,0 +1,63 @@
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
pub mod constants {
|
||||
use frame_support::{
|
||||
parameter_types,
|
||||
weights::{constants, RuntimeDbWeight},
|
||||
};
|
||||
|
||||
parameter_types! {
|
||||
/// `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.
|
||||
pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight {
|
||||
read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
|
||||
write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_db_weights {
|
||||
use super::constants::ParityDbWeight as W;
|
||||
use frame_support::weights::constants;
|
||||
|
||||
/// Checks that all weights exist and have sane values.
|
||||
// NOTE: If this test fails but you are sure that the generated values are fine,
|
||||
// you can delete it.
|
||||
#[test]
|
||||
fn sane() {
|
||||
// At least 1 µs.
|
||||
assert!(
|
||||
W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
|
||||
"Read weight should be at least 1 µs."
|
||||
);
|
||||
assert!(
|
||||
W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
|
||||
"Write weight should be at least 1 µs."
|
||||
);
|
||||
// At most 1 ms.
|
||||
assert!(
|
||||
W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
|
||||
"Read 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."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
pub mod constants {
|
||||
use frame_support::{
|
||||
parameter_types,
|
||||
weights::{constants, RuntimeDbWeight},
|
||||
};
|
||||
|
||||
parameter_types! {
|
||||
/// By default, Substrate uses `RocksDB`, so this will be the weight used throughout
|
||||
/// the runtime.
|
||||
pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight {
|
||||
read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
|
||||
write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_db_weights {
|
||||
use super::constants::RocksDbWeight as W;
|
||||
use frame_support::weights::constants;
|
||||
|
||||
/// Checks that all weights exist and have sane values.
|
||||
// NOTE: If this test fails but you are sure that the generated values are fine,
|
||||
// you can delete it.
|
||||
#[test]
|
||||
fn sane() {
|
||||
// At least 1 µs.
|
||||
assert!(
|
||||
W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
|
||||
"Read weight should be at least 1 µs."
|
||||
);
|
||||
assert!(
|
||||
W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
|
||||
"Write weight should be at least 1 µs."
|
||||
);
|
||||
// At most 1 ms.
|
||||
assert!(
|
||||
W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
|
||||
"Read 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."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
use super::{
|
||||
AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm,
|
||||
Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue,
|
||||
};
|
||||
use frame_support::{
|
||||
match_types, parameter_types,
|
||||
traits::{ConstU32, Everything, Nothing},
|
||||
weights::Weight,
|
||||
};
|
||||
use frame_system::EnsureRoot;
|
||||
use pallet_xcm::XcmPassthrough;
|
||||
use polkadot_parachain_primitives::primitives::Sibling;
|
||||
use polkadot_runtime_common::impls::ToAuthor;
|
||||
use xcm::latest::prelude::*;
|
||||
use xcm_builder::{
|
||||
AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom,
|
||||
CurrencyAdapter, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin,
|
||||
FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset, RelayChainAsNative,
|
||||
SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
|
||||
SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
|
||||
UsingComponents, WithComputedOrigin, WithUniqueTopic,
|
||||
};
|
||||
use xcm_executor::XcmExecutor;
|
||||
|
||||
parameter_types! {
|
||||
pub const RelayLocation: MultiLocation = MultiLocation::parent();
|
||||
pub const RelayNetwork: Option<NetworkId> = None;
|
||||
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.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
|
||||
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
|
||||
/// `Transact` in order to determine the dispatch Origin.
|
||||
pub type LocationToAccountId = (
|
||||
// The parent (Relay-chain) origin converts to the parent `AccountId`.
|
||||
ParentIsPreset<AccountId>,
|
||||
// Sibling parachain origins convert to AccountId via the `ParaId::into`.
|
||||
SiblingParachainConvertsVia<Sibling, AccountId>,
|
||||
// Straight up local `AccountId32` origins just alias directly to `AccountId`.
|
||||
AccountId32Aliases<RelayNetwork, AccountId>,
|
||||
);
|
||||
|
||||
/// Means for transacting assets on this chain.
|
||||
pub type LocalAssetTransactor = CurrencyAdapter<
|
||||
// Use this currency:
|
||||
Balances,
|
||||
// Use this currency when it is a fungible asset matching the given location or name:
|
||||
IsConcrete<RelayLocation>,
|
||||
// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
|
||||
LocationToAccountId,
|
||||
// Our chain's account ID type (we can't get away without mentioning it explicitly):
|
||||
AccountId,
|
||||
// We don't track any teleports.
|
||||
(),
|
||||
>;
|
||||
|
||||
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
|
||||
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
|
||||
/// biases the kind of local `Origin` it will become.
|
||||
pub type XcmOriginToTransactDispatchOrigin = (
|
||||
// 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
|
||||
// foreign chains who want to have a local sovereign account on this chain which they control.
|
||||
SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
|
||||
// Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
|
||||
// recognized.
|
||||
RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
|
||||
// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
|
||||
// recognized.
|
||||
SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
|
||||
// Native signed account converter; this just converts an `AccountId32` origin into a normal
|
||||
// `RuntimeOrigin::Signed` origin of the same 32-byte value.
|
||||
SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
|
||||
// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
|
||||
XcmPassthrough<RuntimeOrigin>,
|
||||
);
|
||||
|
||||
parameter_types! {
|
||||
// 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 const MaxInstructions: u32 = 100;
|
||||
pub const MaxAssetsIntoHolding: u32 = 64;
|
||||
}
|
||||
|
||||
match_types! {
|
||||
pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {
|
||||
MultiLocation { parents: 1, interior: Here } |
|
||||
MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }
|
||||
};
|
||||
}
|
||||
|
||||
pub type Barrier = TrailingSetTopicAsId<
|
||||
DenyThenTry<
|
||||
DenyReserveTransferToRelayChain,
|
||||
(
|
||||
TakeWeightCredit,
|
||||
WithComputedOrigin<
|
||||
(
|
||||
AllowTopLevelPaidExecutionFrom<Everything>,
|
||||
AllowExplicitUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
|
||||
// ^^^ Parent and its exec plurality get free execution
|
||||
),
|
||||
UniversalLocation,
|
||||
ConstU32<8>,
|
||||
>,
|
||||
),
|
||||
>,
|
||||
>;
|
||||
|
||||
pub struct XcmConfig;
|
||||
impl xcm_executor::Config for XcmConfig {
|
||||
type RuntimeCall = RuntimeCall;
|
||||
type XcmSender = XcmRouter;
|
||||
// How to withdraw and deposit an asset.
|
||||
type AssetTransactor = LocalAssetTransactor;
|
||||
type OriginConverter = XcmOriginToTransactDispatchOrigin;
|
||||
type IsReserve = NativeAsset;
|
||||
type IsTeleporter = (); // Teleporting is disabled.
|
||||
type UniversalLocation = UniversalLocation;
|
||||
type Barrier = Barrier;
|
||||
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
|
||||
type Trader =
|
||||
UsingComponents<WeightToFee, RelayLocation, AccountId, Balances, ToAuthor<Runtime>>;
|
||||
type ResponseHandler = PolkadotXcm;
|
||||
type AssetTrap = PolkadotXcm;
|
||||
type AssetClaims = PolkadotXcm;
|
||||
type SubscriptionService = PolkadotXcm;
|
||||
type PalletInstancesInfo = AllPalletsWithSystem;
|
||||
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
|
||||
type AssetLocker = ();
|
||||
type AssetExchanger = ();
|
||||
type FeeManager = ();
|
||||
type MessageExporter = ();
|
||||
type UniversalAliases = Nothing;
|
||||
type CallDispatcher = RuntimeCall;
|
||||
type SafeCallFilter = Everything;
|
||||
type Aliasers = Nothing;
|
||||
}
|
||||
|
||||
/// No local origins on this chain are allowed to dispatch XCM sends/executions.
|
||||
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
|
||||
|
||||
/// The means for routing XCM messages which are not for local execution into the right message
|
||||
/// queues.
|
||||
pub type XcmRouter = WithUniqueTopic<(
|
||||
// Two routers - use UMP to communicate with the relay chain:
|
||||
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, (), ()>,
|
||||
// ..and XCMP to communicate with the sibling chains.
|
||||
XcmpQueue,
|
||||
)>;
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
parameter_types! {
|
||||
pub ReachableDest: Option<MultiLocation> = Some(Parent.into());
|
||||
}
|
||||
|
||||
impl pallet_xcm::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
|
||||
type XcmRouter = XcmRouter;
|
||||
type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
|
||||
type XcmExecuteFilter = Nothing;
|
||||
// ^ Disable dispatchable execute on the XCM pallet.
|
||||
// Needs to be `Everything` for local testing.
|
||||
type XcmExecutor = XcmExecutor<XcmConfig>;
|
||||
type XcmTeleportFilter = Everything;
|
||||
type XcmReserveTransferFilter = Nothing;
|
||||
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
|
||||
type UniversalLocation = UniversalLocation;
|
||||
type RuntimeOrigin = RuntimeOrigin;
|
||||
type RuntimeCall = RuntimeCall;
|
||||
|
||||
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 {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type XcmExecutor = XcmExecutor<XcmConfig>;
|
||||
}
|
||||
Reference in New Issue
Block a user