From a6ec39273e5a20ecb38d79dea5b0374abe935b41 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 11 Aug 2022 12:43:45 +0200 Subject: [PATCH] Make the project capable of handling multiple runtimes (#721) * Migrate from modules to crates Previously all runtimes were united in one crate and toggled by using flags. The client must be able to offer all runtimes, which was impossible with all runtimes being in one crate: Rust prohibits linking to the same crate with different features. Consequently, each runtime must have its own crate. This complicates things significantly and if the previously common runtime schema wants to be used, wrapper macros have to be introduced. * Make client use required Executor and RuntimeApi * Adjust subcommand interpreter to select proper runtime * Add and implement abstract client * Make launcher select correct RuntimeAPI and Executor * Adjust SubstrateCli impl and make client work with chainspecs * Add macro to generate generic genesis across different runtimes --- Cargo.lock | 120 +- Cargo.toml | 4 +- node/Cargo.toml | 20 +- node/res/bs.json | 1 - node/src/chain_spec/battery_station.rs | 123 +- node/src/chain_spec/dev.rs | 54 +- node/src/chain_spec/mod.rs | 382 ++-- node/src/chain_spec/zeitgeist.rs | 125 +- node/src/cli.rs | 429 ++++- node/src/command.rs | 318 +++- node/src/command_helper.rs | 112 +- node/src/main.rs | 7 + node/src/rpc.rs | 3 +- node/src/service.rs | 121 +- node/src/service/service_parachain.rs | 30 +- node/src/service/service_standalone.rs | 28 +- primitives/src/types.rs | 10 +- runtime/{ => battery-station}/Cargo.toml | 33 +- runtime/{ => battery-station}/build.rs | 0 runtime/battery-station/src/lib.rs | 127 ++ .../src/parachain_params.rs | 12 +- .../{ => battery-station}/src/parameters.rs | 23 +- .../{ => battery-station}/src/xcm_config.rs | 2 +- runtime/common/Cargo.toml | 73 + runtime/common/src/lib.rs | 1660 +++++++++++++++++ .../src/weights/cumulus_pallet_xcmp_queue.rs | 0 .../{ => common}/src/weights/frame_system.rs | 0 runtime/{ => common}/src/weights/mod.rs | 0 .../src/weights/orml_currencies.rs | 0 .../{ => common}/src/weights/orml_tokens.rs | 0 .../src/weights/pallet_author_mapping.rs | 0 .../src/weights/pallet_author_slot_filter.rs | 0 .../src/weights/pallet_balances.rs | 0 .../src/weights/pallet_collective.rs | 0 .../src/weights/pallet_democracy.rs | 0 .../src/weights/pallet_grandpa.rs | 0 .../src/weights/pallet_identity.rs | 0 .../src/weights/pallet_membership.rs | 0 .../src/weights/pallet_multisig.rs | 0 .../src/weights/pallet_preimage.rs | 0 .../{ => common}/src/weights/pallet_proxy.rs | 0 .../src/weights/pallet_scheduler.rs | 0 .../src/weights/pallet_timestamp.rs | 0 .../src/weights/pallet_treasury.rs | 0 .../src/weights/pallet_utility.rs | 0 .../src/weights/pallet_vesting.rs | 0 .../src/weights/parachain_staking.rs | 0 runtime/src/benchmarking/currencies.rs | 131 -- runtime/src/benchmarking/mod.rs | 6 - runtime/src/benchmarking/tokens.rs | 99 - runtime/src/benchmarking/utils.rs | 44 - runtime/src/lib.rs | 1472 --------------- runtime/src/opaque.rs | 25 - runtime/src/tests/mod.rs | 1 - runtime/src/tests/multiplier.rs | 88 - runtime/zeitgeist/Cargo.toml | 337 ++++ runtime/zeitgeist/build.rs | 5 + runtime/zeitgeist/src/lib.rs | 117 ++ runtime/zeitgeist/src/parachain_params.rs | 160 ++ runtime/zeitgeist/src/parameters.rs | 158 ++ runtime/zeitgeist/src/xcm_config.rs | 26 + scripts/tests/misc.sh | 2 +- scripts/tests/parachain.sh | 3 +- scripts/tests/standalone.sh | 11 +- 64 files changed, 4107 insertions(+), 2395 deletions(-) rename runtime/{ => battery-station}/Cargo.toml (94%) rename runtime/{ => battery-station}/build.rs (100%) create mode 100644 runtime/battery-station/src/lib.rs rename runtime/{ => battery-station}/src/parachain_params.rs (96%) rename runtime/{ => battery-station}/src/parameters.rs (92%) rename runtime/{ => battery-station}/src/xcm_config.rs (98%) create mode 100644 runtime/common/Cargo.toml create mode 100644 runtime/common/src/lib.rs rename runtime/{ => common}/src/weights/cumulus_pallet_xcmp_queue.rs (100%) rename runtime/{ => common}/src/weights/frame_system.rs (100%) rename runtime/{ => common}/src/weights/mod.rs (100%) rename runtime/{ => common}/src/weights/orml_currencies.rs (100%) rename runtime/{ => common}/src/weights/orml_tokens.rs (100%) rename runtime/{ => common}/src/weights/pallet_author_mapping.rs (100%) rename runtime/{ => common}/src/weights/pallet_author_slot_filter.rs (100%) rename runtime/{ => common}/src/weights/pallet_balances.rs (100%) rename runtime/{ => common}/src/weights/pallet_collective.rs (100%) rename runtime/{ => common}/src/weights/pallet_democracy.rs (100%) rename runtime/{ => common}/src/weights/pallet_grandpa.rs (100%) rename runtime/{ => common}/src/weights/pallet_identity.rs (100%) rename runtime/{ => common}/src/weights/pallet_membership.rs (100%) rename runtime/{ => common}/src/weights/pallet_multisig.rs (100%) rename runtime/{ => common}/src/weights/pallet_preimage.rs (100%) rename runtime/{ => common}/src/weights/pallet_proxy.rs (100%) rename runtime/{ => common}/src/weights/pallet_scheduler.rs (100%) rename runtime/{ => common}/src/weights/pallet_timestamp.rs (100%) rename runtime/{ => common}/src/weights/pallet_treasury.rs (100%) rename runtime/{ => common}/src/weights/pallet_utility.rs (100%) rename runtime/{ => common}/src/weights/pallet_vesting.rs (100%) rename runtime/{ => common}/src/weights/parachain_staking.rs (100%) delete mode 100644 runtime/src/benchmarking/currencies.rs delete mode 100644 runtime/src/benchmarking/mod.rs delete mode 100644 runtime/src/benchmarking/tokens.rs delete mode 100644 runtime/src/benchmarking/utils.rs delete mode 100644 runtime/src/lib.rs delete mode 100644 runtime/src/opaque.rs delete mode 100644 runtime/src/tests/mod.rs delete mode 100644 runtime/src/tests/multiplier.rs create mode 100644 runtime/zeitgeist/Cargo.toml create mode 100644 runtime/zeitgeist/build.rs create mode 100644 runtime/zeitgeist/src/lib.rs create mode 100644 runtime/zeitgeist/src/parachain_params.rs create mode 100644 runtime/zeitgeist/src/parameters.rs create mode 100644 runtime/zeitgeist/src/xcm_config.rs diff --git a/Cargo.lock b/Cargo.lock index f136dbb5a..09af2feb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -441,6 +441,92 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dea908e7347a8c64e378c17e30ef880ad73e3b4498346b055c2c00ea342f3179" +[[package]] +name = "battery-station-runtime" +version = "0.3.4" +dependencies = [ + "cfg-if 1.0.0", + "common-runtime", + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-xcm", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-timestamp", + "cumulus-primitives-utility", + "frame-benchmarking", + "frame-executive", + "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "frame-try-runtime", + "hex-literal", + "log", + "nimbus-primitives", + "orml-benchmarking", + "orml-currencies", + "orml-tokens", + "orml-traits", + "pallet-aura", + "pallet-author-inherent", + "pallet-author-mapping", + "pallet-author-slot-filter", + "pallet-balances", + "pallet-collective", + "pallet-crowdloan-rewards", + "pallet-democracy", + "pallet-grandpa", + "pallet-identity", + "pallet-membership", + "pallet-multisig", + "pallet-preimage", + "pallet-proxy", + "pallet-randomness-collective-flip", + "pallet-scheduler", + "pallet-sudo", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-treasury", + "pallet-utility", + "pallet-vesting", + "pallet-xcm", + "parachain-info", + "parachain-staking", + "parity-scale-codec", + "polkadot-parachain", + "scale-info", + "sp-api", + "sp-block-builder", + "sp-consensus-aura", + "sp-core", + "sp-finality-grandpa", + "sp-inherents", + "sp-io", + "sp-offchain", + "sp-runtime", + "sp-session", + "sp-transaction-pool", + "sp-version", + "substrate-fixed", + "substrate-wasm-builder", + "xcm", + "xcm-builder", + "xcm-executor", + "zeitgeist-primitives", + "zrml-authorized", + "zrml-court", + "zrml-liquidity-mining", + "zrml-market-commons", + "zrml-prediction-markets", + "zrml-rikiddo", + "zrml-simple-disputes", + "zrml-styx", + "zrml-swaps", + "zrml-swaps-runtime-api", +] + [[package]] name = "beef" version = "0.5.1" @@ -1158,6 +1244,37 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "common-runtime" +version = "0.3.4" +dependencies = [ + "cfg-if 1.0.0", + "cumulus-pallet-xcmp-queue", + "frame-support", + "frame-system", + "orml-currencies", + "orml-tokens", + "pallet-author-mapping", + "pallet-author-slot-filter", + "pallet-balances", + "pallet-collective", + "pallet-democracy", + "pallet-identity", + "pallet-membership", + "pallet-multisig", + "pallet-preimage", + "pallet-proxy", + "pallet-randomness-collective-flip", + "pallet-scheduler", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-treasury", + "pallet-utility", + "pallet-vesting", + "parachain-staking", +] + [[package]] name = "concurrent-queue" version = "1.2.2" @@ -12412,6 +12529,7 @@ dependencies = [ name = "zeitgeist-node" version = "0.3.4" dependencies = [ + "battery-station-runtime", "cfg-if 1.0.0", "clap", "cumulus-client-cli", @@ -12511,6 +12629,7 @@ name = "zeitgeist-runtime" version = "0.3.4" dependencies = [ "cfg-if 1.0.0", + "common-runtime", "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-xcm", @@ -12548,7 +12667,6 @@ dependencies = [ "pallet-proxy", "pallet-randomness-collective-flip", "pallet-scheduler", - "pallet-sudo", "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", diff --git a/Cargo.toml b/Cargo.toml index d3fe14fcb..d9d391c72 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,9 @@ members = [ "node", "primitives", - "runtime", + "runtime/common", + "runtime/battery-station", + "runtime/zeitgeist", "zrml/authorized", "zrml/court", "zrml/liquidity-mining", diff --git a/node/Cargo.toml b/node/Cargo.toml index b26f1e4e9..29ab0d91a 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -34,6 +34,7 @@ sp-session = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/p sp-storage = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } sp-timestamp = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } sp-transaction-pool = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } +sp-trie = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } substrate-frame-rpc-system = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } # Try-Runtime @@ -70,7 +71,6 @@ sc-chain-spec = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.co sc-network = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } sc-tracing = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } serde = { features = ["derive"], optional = true, version = "1.0.136" } -sp-trie = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } sp-keystore = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } substrate-prometheus-endpoint = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } @@ -98,15 +98,17 @@ log = { optional = true, version = "0.4.14" } # Zeitgeist +battery-station-runtime = { path = "../runtime/battery-station", optional = true } zeitgeist-primitives = { path = "../primitives" } -zeitgeist-runtime = { path = "../runtime" } +zeitgeist-runtime = { path = "../runtime/zeitgeist", optional = true } zrml-liquidity-mining = { path = "../zrml/liquidity-mining" } zrml-swaps-rpc = { path = "../zrml/swaps/rpc" } [features] -default = [] +default = ["with-battery-station-runtime", "with-zeitgeist-runtime"] parachain = [ - "zeitgeist-runtime/parachain", + "battery-station-runtime?/parachain", + "zeitgeist-runtime?/parachain", # Cumulus @@ -136,7 +138,6 @@ parachain = [ "sc-tracing", "serde", "sp-keystore", - "sp-trie", "substrate-prometheus-endpoint", # Polkadot @@ -148,15 +149,18 @@ parachain = [ "polkadot-test-service", ] runtime-benchmarks = [ + "battery-station-runtime?/runtime-benchmarks", "frame-benchmarking/runtime-benchmarks", "polkadot-service?/runtime-benchmarks", - "zeitgeist-runtime/runtime-benchmarks" + "zeitgeist-runtime?/runtime-benchmarks", ] try-runtime = [ - "zeitgeist-runtime/try-runtime", + "battery-station-runtime?/try-runtime", + "zeitgeist-runtime?/try-runtime", "try-runtime-cli", ] -without-sudo = [] +with-battery-station-runtime = ["battery-station-runtime"] +with-zeitgeist-runtime = ["zeitgeist-runtime"] [package] authors = ["Zeitgeist PM "] diff --git a/node/res/bs.json b/node/res/bs.json index 425d72701..0a372d6f5 100644 --- a/node/res/bs.json +++ b/node/res/bs.json @@ -22,7 +22,6 @@ "tokenSymbol": "ZBP" }, "consensusEngine": null, - "lightSyncState": null, "genesis": { "raw": { "top": { diff --git a/node/src/chain_spec/battery_station.rs b/node/src/chain_spec/battery_station.rs index dff60d1ae..f64dc2adb 100644 --- a/node/src/chain_spec/battery_station.rs +++ b/node/src/chain_spec/battery_station.rs @@ -1,37 +1,130 @@ -#[cfg(not(feature = "without-sudo"))] -use crate::chain_spec::root_key_staging_testnet; -use crate::chain_spec::{ - additional_chain_spec_staging_testnet, endowed_accounts_staging_testnet, generic_genesis, - telemetry_endpoints, token_properties, zeitgeist_wasm, ChainSpec, -}; +#![cfg(feature = "with-battery-station-runtime")] + +use super::{AdditionalChainSpec, EndowedAccountWithBalance}; +use crate::chain_spec::{generate_generic_genesis_function, telemetry_endpoints, token_properties}; +use battery_station_runtime::parameters::SS58Prefix; +use hex_literal::hex; use sc_service::ChainType; +use sp_core::crypto::UncheckedInto; +use zeitgeist_primitives::{ + constants::{ + ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, + BASE, + }, + types::AccountId, +}; + +#[cfg(feature = "parachain")] +use { + super::{Extensions, DEFAULT_COLLATOR_INFLATION_INFO}, + battery_station_runtime::{CollatorDeposit, EligibilityValue, PolkadotXcmConfig}, +}; + +cfg_if::cfg_if! { + if #[cfg(feature = "parachain")] { + pub(super) const DEFAULT_STAKING_AMOUNT_BATTERY_STATION: u128 = 2_000 * BASE; + const DEFAULT_COLLATOR_BALANCE_BATTERY_STATION: Option = + DEFAULT_STAKING_AMOUNT_BATTERY_STATION.checked_add(CollatorDeposit::get()); + const DEFAULT_INITIAL_CROWDLOAN_FUNDS_BATTERY_STATION: u128 = 100 * BASE; + pub type BatteryStationChainSpec = sc_service::GenericChainSpec; + } else { + pub type BatteryStationChainSpec = sc_service::GenericChainSpec; + } +} + +const DEFAULT_INITIAL_BALANCE_BATTERY_STATION: u128 = 10_000 * BASE; + +#[cfg(feature = "parachain")] +fn additional_chain_spec_staging_battery_station( + parachain_id: cumulus_primitives_core::ParaId, +) -> AdditionalChainSpec { + AdditionalChainSpec { + candidates: vec![( + hex!["302f6d7467ae2d7e3b9b962bfc3b9d929da9fae5f1e8c977a031ddf721b0790d"].into(), + hex!["e6ea0b63b2b5b7247a1e8280350a14c5f9e7745dec2fe3428b68aa4167d48e66"] + .unchecked_into(), + DEFAULT_STAKING_AMOUNT_BATTERY_STATION, + )], + crowdloan_fund_pot: DEFAULT_INITIAL_CROWDLOAN_FUNDS_BATTERY_STATION, + inflation_info: DEFAULT_COLLATOR_INFLATION_INFO, + nominations: vec![], + parachain_id, + } +} + +#[cfg(not(feature = "parachain"))] +fn additional_chain_spec_staging_battery_station() -> AdditionalChainSpec { + AdditionalChainSpec { + initial_authorities: vec![( + // 5FCSJzvmeUW1hBo3ASnLzSxpUdn5QUDt1Eqobj1meiQB7mLu + hex!["8a9a54bdf73fb4a757f5ab81fabe2f173922fdb92bb8b6e8bedf8b17fa38f500"] + .unchecked_into(), + // 5HGProUwcyCDMJDxjBBKbv8u7ehr5uoTBS3bckYHPcZMTifW + hex!["e61786c6426b55a034f9c4b78dc57d4183927cef8e64b2e496225ed6fca41758"] + .unchecked_into(), + )], + } +} + +fn endowed_accounts_staging_battery_station() -> Vec { + vec![ + // 5D2L4ghyiYE8p2z7VNJo9JYwRuc8uzPWtMBqdVyvjRcsnw4P + EndowedAccountWithBalance( + hex!["2a6c61a907556e4c673880b5767dd4be08339ee7f2a58d5137d0c19ca9570a5c"].into(), + DEFAULT_INITIAL_BALANCE_BATTERY_STATION, + ), + // 5EeeZVU4SiPG6ZRY7o8aDcav2p2mZMdu3ZLzbREWuHktYdhX + EndowedAccountWithBalance( + hex!["725bb6fd13d52b3d6830e5a9faed1f6499ca0f5e8aa285df09490646e71e831b"].into(), + DEFAULT_INITIAL_BALANCE_BATTERY_STATION, + ), + // 5D9tF8w1FMSdz52bpiaQis1pCUZy5Gs6HcHS7gHxEzyq4XzU + #[cfg(feature = "parachain")] + EndowedAccountWithBalance( + hex!["302f6d7467ae2d7e3b9b962bfc3b9d929da9fae5f1e8c977a031ddf721b0790d"].into(), + DEFAULT_COLLATOR_BALANCE_BATTERY_STATION.unwrap(), + ), + ] +} + +fn root_key_staging_battery_station() -> AccountId { + hex!["2a6c61a907556e4c673880b5767dd4be08339ee7f2a58d5137d0c19ca9570a5c"].into() +} + +#[inline] +pub(super) fn get_wasm() -> Result<&'static [u8], String> { + battery_station_runtime::WASM_BINARY.ok_or_else(|| "WASM binary is not available".to_string()) +} + +generate_generic_genesis_function!( + battery_station_runtime, + sudo: battery_station_runtime::SudoConfig { key: Some(root_key_staging_battery_station()) }, +); pub fn battery_station_staging_config( #[cfg(feature = "parachain")] parachain_id: cumulus_primitives_core::ParaId, -) -> Result { - let zeitgeist_wasm = zeitgeist_wasm()?; +) -> Result { + let wasm = get_wasm()?; - Ok(ChainSpec::from_genesis( + Ok(BatteryStationChainSpec::from_genesis( "Battery Station Staging", "battery_station_staging", ChainType::Live, move || { generic_genesis( - additional_chain_spec_staging_testnet( + additional_chain_spec_staging_battery_station( #[cfg(feature = "parachain")] parachain_id, ), - endowed_accounts_staging_testnet(), - #[cfg(not(feature = "without-sudo"))] - root_key_staging_testnet(), - zeitgeist_wasm, + endowed_accounts_staging_battery_station(), + wasm, ) }, vec![], telemetry_endpoints(), Some("battery_station"), None, - Some(token_properties("ZBS")), + Some(token_properties("ZBS", SS58Prefix::get())), #[cfg(feature = "parachain")] crate::chain_spec::Extensions { relay_chain: "rococo".into(), diff --git a/node/src/chain_spec/dev.rs b/node/src/chain_spec/dev.rs index d4560233e..a89a07c6e 100644 --- a/node/src/chain_spec/dev.rs +++ b/node/src/chain_spec/dev.rs @@ -1,21 +1,45 @@ -use super::EndowedAccountWithBalance; -#[cfg(feature = "parachain")] -use crate::chain_spec::get_from_seed; -use crate::chain_spec::{ - generic_genesis, get_account_id_from_seed, token_properties, zeitgeist_wasm, - AdditionalChainSpec, ChainSpec, +#![cfg(feature = "with-battery-station-runtime")] + +use super::{ + battery_station::BatteryStationChainSpec, generate_generic_genesis_function, + get_account_id_from_seed, get_from_seed, token_properties, AdditionalChainSpec, + EndowedAccountWithBalance, }; + +#[cfg(feature = "parachain")] +use battery_station_runtime::{EligibilityValue, PolkadotXcmConfig}; use sc_service::ChainType; use sp_core::sr25519; -use zeitgeist_primitives::types::Balance; +use zeitgeist_primitives::{ + constants::ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, + types::Balance, +}; const INITIAL_BALANCE: Balance = Balance::MAX >> 4; +#[cfg(not(feature = "parachain"))] +fn authority_keys_from_seed( + s: &str, +) -> (sp_consensus_aura::sr25519::AuthorityId, sp_finality_grandpa::AuthorityId) { + ( + get_from_seed::(s), + get_from_seed::(s), + ) +} + +generate_generic_genesis_function! {battery_station_runtime, + sudo: battery_station_runtime::SudoConfig { key: Some(get_account_id_from_seed::("Alice")) }, +} + +// Dev currently uses battery station runtime for the following reasons: +// 1. It is the most experimental runtime (as of writing this) +// 2. It offers the sudo pallet pub fn dev_config( #[cfg(feature = "parachain")] parachain_id: cumulus_primitives_core::ParaId, -) -> Result { - let zeitgeist_wasm = zeitgeist_wasm()?; - Ok(ChainSpec::from_genesis( +) -> Result { + let wasm = super::battery_station::get_wasm()?; + + Ok(BatteryStationChainSpec::from_genesis( "Development", "dev", ChainType::Local, @@ -26,7 +50,7 @@ pub fn dev_config( candidates: vec![( get_account_id_from_seed::("Alice"), get_from_seed::("Alice"), - crate::chain_spec::DEFAULT_STAKING_AMOUNT_TESTNET, + super::battery_station::DEFAULT_STAKING_AMOUNT_BATTERY_STATION, )], crowdloan_fund_pot: zeitgeist_primitives::constants::BASE.saturating_mul(100), inflation_info: crate::chain_spec::DEFAULT_COLLATOR_INFLATION_INFO, @@ -35,7 +59,7 @@ pub fn dev_config( }, #[cfg(not(feature = "parachain"))] AdditionalChainSpec { - initial_authorities: vec![crate::chain_spec::authority_keys_from_seed("Alice")], + initial_authorities: vec![authority_keys_from_seed("Alice")], }, vec![ get_account_id_from_seed::("Alice"), @@ -54,16 +78,14 @@ pub fn dev_config( .into_iter() .map(|acc| EndowedAccountWithBalance(acc, INITIAL_BALANCE)) .collect(), - #[cfg(not(feature = "without-sudo"))] - get_account_id_from_seed::("Alice"), - zeitgeist_wasm, + wasm, ) }, vec![], None, None, None, - Some(token_properties("DEV")), + Some(token_properties("DEV", battery_station_runtime::SS58Prefix::get())), #[cfg(feature = "parachain")] crate::chain_spec::Extensions { relay_chain: "rococo-dev".into(), diff --git a/node/src/chain_spec/mod.rs b/node/src/chain_spec/mod.rs index 3c388f0bb..4c0030f7e 100644 --- a/node/src/chain_spec/mod.rs +++ b/node/src/chain_spec/mod.rs @@ -1,50 +1,41 @@ mod additional_chain_spec; -mod battery_station; +#[cfg(feature = "with-battery-station-runtime")] +pub(crate) mod battery_station; +#[cfg(feature = "with-battery-station-runtime")] mod dev; -mod zeitgeist; +#[cfg(feature = "with-zeitgeist-runtime")] +pub(crate) mod zeitgeist; pub use additional_chain_spec::AdditionalChainSpec; +#[cfg(feature = "with-battery-station-runtime")] pub use battery_station::battery_station_staging_config; +#[cfg(feature = "with-battery-station-runtime")] pub use dev::dev_config; -use hex_literal::hex; use jsonrpc_core::serde_json::{Map, Value}; use sc_telemetry::TelemetryEndpoints; -use sp_core::{crypto::UncheckedInto, Pair, Public}; +#[cfg(feature = "with-battery-station-runtime")] +use sp_core::{Pair, Public}; +#[cfg(feature = "with-battery-station-runtime")] use sp_runtime::traits::{IdentifyAccount, Verify}; +#[cfg(feature = "with-zeitgeist-runtime")] pub use zeitgeist::zeitgeist_staging_config; +#[cfg(feature = "with-battery-station-runtime")] +use zeitgeist_primitives::types::Signature; use zeitgeist_primitives::{ - constants::{ - ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, - BalanceFractionalDecimals, BASE, - }, - types::{AccountId, Balance, Signature}, + constants::BalanceFractionalDecimals, + types::{AccountId, Balance}, }; -use zeitgeist_runtime::SS58Prefix; #[cfg(feature = "parachain")] use { sp_runtime::Perbill, zeitgeist_primitives::constants::{ztg, MILLISECS_PER_BLOCK}, - zeitgeist_runtime::{ - CollatorDeposit, DefaultBlocksPerRound, EligibilityValue, MinCollatorStk, PolkadotXcmConfig, - }, + zeitgeist_runtime::DefaultBlocksPerRound, }; cfg_if::cfg_if! { if #[cfg(feature = "parachain")] { - // Testnet - const DEFAULT_STAKING_AMOUNT_TESTNET: u128 = 2_000 * BASE; - const DEFAULT_COLLATOR_BALANCE_TESTNET: Option = - DEFAULT_STAKING_AMOUNT_TESTNET.checked_add(CollatorDeposit::get()); - const DEFAULT_INITIAL_CROWDLOAN_FUNDS_TESTNET: u128 = 100 * BASE; - - // Mainnet - const DEFAULT_STAKING_AMOUNT_MAINNET: u128 = MinCollatorStk::get(); - const DEFAULT_COLLATOR_BALANCE_MAINNET: Option = - DEFAULT_STAKING_AMOUNT_MAINNET.checked_add(CollatorDeposit::get()); - const DEFAULT_INITIAL_CROWDLOAN_FUNDS_MAINNET: u128 = 0; - // Common - const DEFAULT_COLLATOR_INFLATION_INFO: parachain_staking::InflationInfo = { + pub(crate) const DEFAULT_COLLATOR_INFLATION_INFO: parachain_staking::InflationInfo = { let hours_per_year = 8766; let millisecs_per_year = hours_per_year * 60 * 60 * 1000; let round_millisecs = DefaultBlocksPerRound::get() as u64 * MILLISECS_PER_BLOCK as u64; @@ -74,103 +65,109 @@ cfg_if::cfg_if! { } }; - pub type ChainSpec = sc_service::GenericChainSpec; + pub type DummyChainSpec = sc_service::GenericChainSpec<(), Extensions>; } else { - pub type ChainSpec = sc_service::GenericChainSpec; + pub type DummyChainSpec = sc_service::GenericChainSpec<()>; } } -const DEFAULT_INITIAL_BALANCE_TESTNET: u128 = 10_000 * BASE; -#[cfg(not(feature = "without-sudo"))] -const DEFAULT_SUDO_BALANCE_MAINNET: u128 = 100 * BASE; const POLKADOT_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; const ZEITGEIST_TELEMETRY_URL: &str = "wss://telemetry.zeitgeist.pm/submit/"; -type AccountPublic = ::Signer; #[derive(Clone)] -struct EndowedAccountWithBalance(AccountId, Balance); +pub(crate) struct EndowedAccountWithBalance(AccountId, Balance); + +macro_rules! generate_generic_genesis_function { + ($runtime:ident, $($additional_genesis:tt)*) => { + pub(super) fn generic_genesis( + acs: AdditionalChainSpec, + endowed_accounts: Vec, + wasm_binary: &[u8], + ) -> $runtime::GenesisConfig { + $runtime::GenesisConfig { + // Common genesis + advisory_committee: Default::default(), + advisory_committee_membership: $runtime::AdvisoryCommitteeMembershipConfig { + members: vec![], + phantom: Default::default(), + }, + #[cfg(not(feature = "parachain"))] + aura: $runtime::AuraConfig { + authorities: acs.initial_authorities.iter().map(|x| (x.0.clone())).collect(), + }, + #[cfg(feature = "parachain")] + author_filter: $runtime::AuthorFilterConfig { + eligible_count: EligibilityValue::new_unchecked(50), + }, + #[cfg(feature = "parachain")] + author_mapping: $runtime::AuthorMappingConfig { + mappings: acs + .candidates + .iter() + .cloned() + .map(|(account_id, author_id, _)| (author_id, account_id)) + .collect(), + }, + balances: $runtime::BalancesConfig { + balances: endowed_accounts.iter().cloned().map(|k| (k.0, k.1)).collect(), + }, + council: Default::default(), + council_membership: $runtime::CouncilMembershipConfig { + members: vec![], + phantom: Default::default(), + }, + #[cfg(feature = "parachain")] + crowdloan: $runtime::CrowdloanConfig { funded_amount: acs.crowdloan_fund_pot }, + democracy: Default::default(), + #[cfg(not(feature = "parachain"))] + grandpa: $runtime::GrandpaConfig { + authorities: acs.initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), + }, + liquidity_mining: $runtime::LiquidityMiningConfig { + initial_balance: LIQUIDITY_MINING, + per_block_distribution: LIQUIDITY_MINING_PTD.mul_ceil(LIQUIDITY_MINING), + }, + #[cfg(feature = "parachain")] + parachain_info: $runtime::ParachainInfoConfig { parachain_id: acs.parachain_id }, + #[cfg(feature = "parachain")] + parachain_staking: $runtime::ParachainStakingConfig { + candidates: acs + .candidates + .iter() + .cloned() + .map(|(account, _, bond)| (account, bond)) + .collect(), + inflation_config: acs.inflation_info, + delegations: acs.nominations, + }, + #[cfg(feature = "parachain")] + parachain_system: Default::default(), + #[cfg(feature = "parachain")] + // Default should use the pallet configuration + polkadot_xcm: PolkadotXcmConfig::default(), + system: $runtime::SystemConfig { code: wasm_binary.to_vec() }, + technical_committee: Default::default(), + technical_committee_membership: $runtime::TechnicalCommitteeMembershipConfig { + members: vec![], + phantom: Default::default(), + }, + treasury: Default::default(), + transaction_payment: Default::default(), + tokens: Default::default(), + vesting: Default::default(), -fn generic_genesis( - acs: AdditionalChainSpec, - endowed_accounts: Vec, - #[cfg(not(feature = "without-sudo"))] root_key: AccountId, - wasm_binary: &[u8], -) -> zeitgeist_runtime::GenesisConfig { - zeitgeist_runtime::GenesisConfig { - advisory_committee: Default::default(), - advisory_committee_membership: zeitgeist_runtime::AdvisoryCommitteeMembershipConfig { - members: vec![], - phantom: Default::default(), - }, - #[cfg(not(feature = "parachain"))] - aura: zeitgeist_runtime::AuraConfig { - authorities: acs.initial_authorities.iter().map(|x| (x.0.clone())).collect(), - }, - #[cfg(feature = "parachain")] - author_filter: zeitgeist_runtime::AuthorFilterConfig { - eligible_count: EligibilityValue::new_unchecked(50), - }, - #[cfg(feature = "parachain")] - author_mapping: zeitgeist_runtime::AuthorMappingConfig { - mappings: acs - .candidates - .iter() - .cloned() - .map(|(account_id, author_id, _)| (author_id, account_id)) - .collect(), - }, - balances: zeitgeist_runtime::BalancesConfig { - balances: endowed_accounts.iter().cloned().map(|k| (k.0, k.1)).collect(), - }, - council: Default::default(), - council_membership: zeitgeist_runtime::CouncilMembershipConfig { - members: vec![], - phantom: Default::default(), - }, - #[cfg(feature = "parachain")] - crowdloan: zeitgeist_runtime::CrowdloanConfig { funded_amount: acs.crowdloan_fund_pot }, - democracy: Default::default(), - #[cfg(not(feature = "parachain"))] - grandpa: zeitgeist_runtime::GrandpaConfig { - authorities: acs.initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), - }, - liquidity_mining: zeitgeist_runtime::LiquidityMiningConfig { - initial_balance: LIQUIDITY_MINING, - per_block_distribution: LIQUIDITY_MINING_PTD.mul_ceil(LIQUIDITY_MINING), - }, - #[cfg(feature = "parachain")] - parachain_info: zeitgeist_runtime::ParachainInfoConfig { parachain_id: acs.parachain_id }, - #[cfg(feature = "parachain")] - parachain_staking: zeitgeist_runtime::ParachainStakingConfig { - candidates: acs - .candidates - .iter() - .cloned() - .map(|(account, _, bond)| (account, bond)) - .collect(), - inflation_config: acs.inflation_info, - delegations: acs.nominations, - }, - #[cfg(feature = "parachain")] - parachain_system: Default::default(), - #[cfg(feature = "parachain")] - // Default should use the pallet configuration - polkadot_xcm: PolkadotXcmConfig::default(), - #[cfg(not(feature = "without-sudo"))] - sudo: zeitgeist_runtime::SudoConfig { key: Some(root_key) }, - system: zeitgeist_runtime::SystemConfig { code: wasm_binary.to_vec() }, - technical_committee: Default::default(), - technical_committee_membership: zeitgeist_runtime::TechnicalCommitteeMembershipConfig { - members: vec![], - phantom: Default::default(), - }, - treasury: Default::default(), - transaction_payment: Default::default(), - tokens: Default::default(), - vesting: Default::default(), - } + // Additional genesis + $($additional_genesis)* + } + } + }; } +pub(crate) use generate_generic_genesis_function; + +#[cfg(feature = "with-battery-station-runtime")] +type AccountPublic = ::Signer; +#[cfg(feature = "with-battery-station-runtime")] fn get_account_id_from_seed(seed: &str) -> AccountId where AccountPublic: From<::Public>, @@ -178,6 +175,7 @@ where AccountPublic::from(get_from_seed::(seed)).into_account() } +#[cfg(feature = "with-battery-station-runtime")] fn get_from_seed(seed: &str) -> ::Public { TPublic::Pair::from_string(&format!("//{}", seed), None) .expect("static values are valid; qed") @@ -211,148 +209,12 @@ impl Extensions { } } -// Testnet configuration - -#[cfg(feature = "parachain")] -fn additional_chain_spec_staging_testnet( - parachain_id: cumulus_primitives_core::ParaId, -) -> AdditionalChainSpec { - AdditionalChainSpec { - candidates: vec![( - hex!["302f6d7467ae2d7e3b9b962bfc3b9d929da9fae5f1e8c977a031ddf721b0790d"].into(), - hex!["e6ea0b63b2b5b7247a1e8280350a14c5f9e7745dec2fe3428b68aa4167d48e66"] - .unchecked_into(), - DEFAULT_STAKING_AMOUNT_TESTNET, - )], - crowdloan_fund_pot: DEFAULT_INITIAL_CROWDLOAN_FUNDS_TESTNET, - inflation_info: DEFAULT_COLLATOR_INFLATION_INFO, - nominations: vec![], - parachain_id, - } -} - -#[cfg(not(feature = "parachain"))] -fn additional_chain_spec_staging_testnet() -> AdditionalChainSpec { - AdditionalChainSpec { - initial_authorities: vec![( - // 5FCSJzvmeUW1hBo3ASnLzSxpUdn5QUDt1Eqobj1meiQB7mLu - hex!["8a9a54bdf73fb4a757f5ab81fabe2f173922fdb92bb8b6e8bedf8b17fa38f500"] - .unchecked_into(), - // 5HGProUwcyCDMJDxjBBKbv8u7ehr5uoTBS3bckYHPcZMTifW - hex!["e61786c6426b55a034f9c4b78dc57d4183927cef8e64b2e496225ed6fca41758"] - .unchecked_into(), - )], - } -} - -#[cfg(not(feature = "parachain"))] -fn authority_keys_from_seed( - s: &str, -) -> (sp_consensus_aura::sr25519::AuthorityId, sp_finality_grandpa::AuthorityId) { - ( - get_from_seed::(s), - get_from_seed::(s), - ) -} - -fn endowed_accounts_staging_testnet() -> Vec { - vec![ - // 5D2L4ghyiYE8p2z7VNJo9JYwRuc8uzPWtMBqdVyvjRcsnw4P - EndowedAccountWithBalance( - hex!["2a6c61a907556e4c673880b5767dd4be08339ee7f2a58d5137d0c19ca9570a5c"].into(), - DEFAULT_INITIAL_BALANCE_TESTNET, - ), - // 5EeeZVU4SiPG6ZRY7o8aDcav2p2mZMdu3ZLzbREWuHktYdhX - EndowedAccountWithBalance( - hex!["725bb6fd13d52b3d6830e5a9faed1f6499ca0f5e8aa285df09490646e71e831b"].into(), - DEFAULT_INITIAL_BALANCE_TESTNET, - ), - // 5D9tF8w1FMSdz52bpiaQis1pCUZy5Gs6HcHS7gHxEzyq4XzU - #[cfg(feature = "parachain")] - EndowedAccountWithBalance( - hex!["302f6d7467ae2d7e3b9b962bfc3b9d929da9fae5f1e8c977a031ddf721b0790d"].into(), - DEFAULT_COLLATOR_BALANCE_TESTNET.unwrap(), - ), - ] -} - -#[cfg(not(feature = "without-sudo"))] -fn root_key_staging_testnet() -> AccountId { - hex!["2a6c61a907556e4c673880b5767dd4be08339ee7f2a58d5137d0c19ca9570a5c"].into() -} - -// Mainnet configuration - -fn endowed_accounts_staging_mainnet() -> Vec { - vec![ - // dDzt4vaprRfHqGBat44bWD4i36WMDXjsGXmCHoxMom2eQgQCd - #[cfg(feature = "parachain")] - EndowedAccountWithBalance( - hex!["524e9aac979cbb9ecdb7acd1635755c3b15696321a3345ca77f0ab0ae23f675a"].into(), - DEFAULT_COLLATOR_BALANCE_MAINNET.unwrap(), - ), - // dDy7WSPy4pvWBKsUta8MdWxduWFTpJtv9zgBiVGtqWmMh6bi6 - #[cfg(feature = "parachain")] - EndowedAccountWithBalance( - hex!["04163722a7f1f900c1ec502383d4959360e374c8808e13d47b3e553d761a6329"].into(), - DEFAULT_COLLATOR_BALANCE_MAINNET.unwrap(), - ), - // dE36Y98QpX8hEkLANntbtUvt7figSPGxSrDxU4sscuX989CTJ - #[cfg(feature = "parachain")] - EndowedAccountWithBalance( - hex!["b449a256f73e59602eb742071a07e4d94aaae91e6872f28e161f34982a0bfc0d"].into(), - DEFAULT_COLLATOR_BALANCE_MAINNET.unwrap(), - ), - // dE2nxuZc5e7xBbU1cGikmtVGws9niNPUayigoDdyqB7hzHQ6X - #[cfg(not(feature = "without-sudo"))] - EndowedAccountWithBalance( - hex!["203ef582312dae988433920791ce584daeca819a76d000175dc6d7d1a0fb1413"].into(), - DEFAULT_SUDO_BALANCE_MAINNET, - ), - ] -} - -#[cfg(not(feature = "without-sudo"))] -fn root_key_staging_mainnet() -> AccountId { - // dDykRtA8VyuVVtWTD5PWst3f33L1NMVKseQEji8e3B4ZCHrjK - hex!["203ef582312dae988433920791ce584daeca819a76d000175dc6d7d1a0fb1413"].into() -} - -#[cfg(feature = "parachain")] -fn additional_chain_spec_staging_mainnet( - parachain_id: cumulus_primitives_core::ParaId, -) -> AdditionalChainSpec { - AdditionalChainSpec { - candidates: vec![ - ( - hex!["524e9aac979cbb9ecdb7acd1635755c3b15696321a3345ca77f0ab0ae23f675a"].into(), - hex!["e251731d35dd19aeb7db1ffe06227d0b7da3b3eabb5ec1d79da453ac9949e80b"] - .unchecked_into(), - DEFAULT_STAKING_AMOUNT_MAINNET, - ), - ( - hex!["04163722a7f1f900c1ec502383d4959360e374c8808e13d47b3e553d761a6329"].into(), - hex!["76d3384620053d1eb67e0f7fa8af93a8028e5cf74f22a12a5f2393b286463753"] - .unchecked_into(), - DEFAULT_STAKING_AMOUNT_MAINNET, - ), - ( - hex!["b449a256f73e59602eb742071a07e4d94aaae91e6872f28e161f34982a0bfc0d"].into(), - hex!["14a3becfeeb700ff6a41927a2924493717aea238d9c5bea15368d61550f63e44"] - .unchecked_into(), - DEFAULT_STAKING_AMOUNT_MAINNET, - ), - ], - crowdloan_fund_pot: DEFAULT_INITIAL_CROWDLOAN_FUNDS_MAINNET, - inflation_info: DEFAULT_COLLATOR_INFLATION_INFO, - nominations: vec![], - parachain_id, - } -} - -#[cfg(not(feature = "parachain"))] -fn additional_chain_spec_staging_mainnet() -> AdditionalChainSpec { - additional_chain_spec_staging_testnet() +fn token_properties(token_symbol: &str, ss58_prefix: u8) -> Map { + let mut properties = Map::new(); + properties.insert("ss58Format".into(), ss58_prefix.into()); + properties.insert("tokenSymbol".into(), token_symbol.into()); + properties.insert("tokenDecimals".into(), BalanceFractionalDecimals::get().into()); + properties } fn telemetry_endpoints() -> Option { @@ -362,15 +224,3 @@ fn telemetry_endpoints() -> Option { ]) .ok() } - -fn token_properties(token_symbol: &str) -> Map { - let mut properties = Map::new(); - properties.insert("ss58Format".into(), SS58Prefix::get().into()); - properties.insert("tokenSymbol".into(), token_symbol.into()); - properties.insert("tokenDecimals".into(), BalanceFractionalDecimals::get().into()); - properties -} - -fn zeitgeist_wasm() -> Result<&'static [u8], String> { - zeitgeist_runtime::WASM_BINARY.ok_or_else(|| "WASM binary is not available".to_string()) -} diff --git a/node/src/chain_spec/zeitgeist.rs b/node/src/chain_spec/zeitgeist.rs index eec8012fb..f674d7088 100644 --- a/node/src/chain_spec/zeitgeist.rs +++ b/node/src/chain_spec/zeitgeist.rs @@ -1,37 +1,132 @@ -#[cfg(not(feature = "without-sudo"))] -use crate::chain_spec::root_key_staging_mainnet; -use crate::chain_spec::{ - additional_chain_spec_staging_mainnet, endowed_accounts_staging_mainnet, generic_genesis, - telemetry_endpoints, token_properties, zeitgeist_wasm, ChainSpec, -}; +#![cfg(feature = "with-zeitgeist-runtime")] + +use super::{AdditionalChainSpec, EndowedAccountWithBalance}; +use crate::chain_spec::{generate_generic_genesis_function, telemetry_endpoints, token_properties}; +use hex_literal::hex; use sc_service::ChainType; +use sp_core::crypto::UncheckedInto; +use zeitgeist_runtime::parameters::SS58Prefix; + +use zeitgeist_primitives::constants::ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}; + +#[cfg(feature = "parachain")] +use { + super::{Extensions, DEFAULT_COLLATOR_INFLATION_INFO}, + zeitgeist_runtime::{CollatorDeposit, EligibilityValue, MinCollatorStk, PolkadotXcmConfig}, +}; + +cfg_if::cfg_if! { + if #[cfg(feature = "parachain")] { + const DEFAULT_STAKING_AMOUNT_ZEITGEIST: u128 = MinCollatorStk::get(); + const DEFAULT_COLLATOR_BALANCE_ZEITGEIST: Option = + DEFAULT_STAKING_AMOUNT_ZEITGEIST.checked_add(CollatorDeposit::get()); + const DEFAULT_INITIAL_CROWDLOAN_FUNDS_ZEITGEIST: u128 = 0; + pub type ZeitgeistChainSpec = sc_service::GenericChainSpec; + } else { + pub type ZeitgeistChainSpec = sc_service::GenericChainSpec; + } +} + +fn endowed_accounts_staging_zeitgeist() -> Vec { + vec![ + // dDzt4vaprRfHqGBat44bWD4i36WMDXjsGXmCHoxMom2eQgQCd + #[cfg(feature = "parachain")] + EndowedAccountWithBalance( + hex!["524e9aac979cbb9ecdb7acd1635755c3b15696321a3345ca77f0ab0ae23f675a"].into(), + DEFAULT_COLLATOR_BALANCE_ZEITGEIST.unwrap(), + ), + // dDy7WSPy4pvWBKsUta8MdWxduWFTpJtv9zgBiVGtqWmMh6bi6 + #[cfg(feature = "parachain")] + EndowedAccountWithBalance( + hex!["04163722a7f1f900c1ec502383d4959360e374c8808e13d47b3e553d761a6329"].into(), + DEFAULT_COLLATOR_BALANCE_ZEITGEIST.unwrap(), + ), + // dE36Y98QpX8hEkLANntbtUvt7figSPGxSrDxU4sscuX989CTJ + #[cfg(feature = "parachain")] + EndowedAccountWithBalance( + hex!["b449a256f73e59602eb742071a07e4d94aaae91e6872f28e161f34982a0bfc0d"].into(), + DEFAULT_COLLATOR_BALANCE_ZEITGEIST.unwrap(), + ), + ] +} + +#[cfg(feature = "parachain")] +fn additional_chain_spec_staging_zeitgeist( + parachain_id: cumulus_primitives_core::ParaId, +) -> AdditionalChainSpec { + AdditionalChainSpec { + candidates: vec![ + ( + hex!["524e9aac979cbb9ecdb7acd1635755c3b15696321a3345ca77f0ab0ae23f675a"].into(), + hex!["e251731d35dd19aeb7db1ffe06227d0b7da3b3eabb5ec1d79da453ac9949e80b"] + .unchecked_into(), + DEFAULT_STAKING_AMOUNT_ZEITGEIST, + ), + ( + hex!["04163722a7f1f900c1ec502383d4959360e374c8808e13d47b3e553d761a6329"].into(), + hex!["76d3384620053d1eb67e0f7fa8af93a8028e5cf74f22a12a5f2393b286463753"] + .unchecked_into(), + DEFAULT_STAKING_AMOUNT_ZEITGEIST, + ), + ( + hex!["b449a256f73e59602eb742071a07e4d94aaae91e6872f28e161f34982a0bfc0d"].into(), + hex!["14a3becfeeb700ff6a41927a2924493717aea238d9c5bea15368d61550f63e44"] + .unchecked_into(), + DEFAULT_STAKING_AMOUNT_ZEITGEIST, + ), + ], + crowdloan_fund_pot: DEFAULT_INITIAL_CROWDLOAN_FUNDS_ZEITGEIST, + inflation_info: DEFAULT_COLLATOR_INFLATION_INFO, + nominations: vec![], + parachain_id, + } +} + +#[cfg(not(feature = "parachain"))] +fn additional_chain_spec_staging_zeitgeist() -> AdditionalChainSpec { + AdditionalChainSpec { + initial_authorities: vec![( + // 5FCSJzvmeUW1hBo3ASnLzSxpUdn5QUDt1Eqobj1meiQB7mLu + hex!["8a9a54bdf73fb4a757f5ab81fabe2f173922fdb92bb8b6e8bedf8b17fa38f500"] + .unchecked_into(), + // 5HGProUwcyCDMJDxjBBKbv8u7ehr5uoTBS3bckYHPcZMTifW + hex!["e61786c6426b55a034f9c4b78dc57d4183927cef8e64b2e496225ed6fca41758"] + .unchecked_into(), + )], + } +} + +#[inline] +pub(super) fn get_wasm() -> Result<&'static [u8], String> { + zeitgeist_runtime::WASM_BINARY.ok_or_else(|| "WASM binary is not available".to_string()) +} + +generate_generic_genesis_function!(zeitgeist_runtime,); pub fn zeitgeist_staging_config( #[cfg(feature = "parachain")] parachain_id: cumulus_primitives_core::ParaId, -) -> Result { - let zeitgeist_wasm = zeitgeist_wasm()?; +) -> Result { + let wasm = get_wasm()?; - Ok(ChainSpec::from_genesis( + Ok(ZeitgeistChainSpec::from_genesis( "Zeitgeist Staging", "zeitgeist_staging", ChainType::Live, move || { generic_genesis( - additional_chain_spec_staging_mainnet( + additional_chain_spec_staging_zeitgeist( #[cfg(feature = "parachain")] parachain_id, ), - endowed_accounts_staging_mainnet(), - #[cfg(not(feature = "without-sudo"))] - root_key_staging_mainnet(), - zeitgeist_wasm, + endowed_accounts_staging_zeitgeist(), + wasm, ) }, vec![], telemetry_endpoints(), Some("zeitgeist"), None, - Some(token_properties("ZTG")), + Some(token_properties("ZTG", SS58Prefix::get())), #[cfg(feature = "parachain")] crate::chain_spec::Extensions { relay_chain: "kusama".into(), diff --git a/node/src/cli.rs b/node/src/cli.rs index a14ab7bbd..9b6466e7b 100644 --- a/node/src/cli.rs +++ b/node/src/cli.rs @@ -1,11 +1,33 @@ #[cfg(feature = "parachain")] mod cli_parachain; +use super::service::{ + AdditionalRuntimeApiCollection, FullBackend, FullClient, IdentifyVariant, RuntimeApiCollection, +}; +use clap::Parser; #[cfg(feature = "parachain")] pub use cli_parachain::RelayChainCli; - -use clap::Parser; use sc_cli::{ChainSpec, RuntimeVersion, SubstrateCli}; +use sc_client_api::{Backend as BackendT, BlockchainEvents, KeyIterator}; +use sp_api::{CallApiAt, NumberFor, ProvideRuntimeApi}; +use sp_blockchain::HeaderBackend; +use sp_consensus::BlockStatus; +use sp_runtime::{ + generic::{BlockId, SignedBlock}, + traits::{BlakeTwo256, Block as BlockT}, + Justifications, +}; +use sp_storage::{ChildInfo, StorageData, StorageKey}; +use std::sync::Arc; +pub use zeitgeist_primitives::types::{AccountId, Balance, BlockNumber, Hash, Index}; +use zeitgeist_primitives::types::{Block, Header}; +#[cfg(feature = "with-battery-station-runtime")] +use { + super::service::BatteryStationExecutor, + battery_station_runtime::RuntimeApi as BatteryStationRuntimeApi, +}; +#[cfg(feature = "with-zeitgeist-runtime")] +use {super::service::ZeitgeistExecutor, zeitgeist_runtime::RuntimeApi as ZeitgeistRuntimeApi}; const COPYRIGHT_START_YEAR: i32 = 2021; const IMPL_NAME: &str = "Zeitgeist Node"; @@ -16,6 +38,75 @@ type RunCmd = cumulus_client_cli::RunCmd; #[cfg(not(feature = "parachain"))] type RunCmd = sc_cli::RunCmd; +pub fn load_spec( + id: &str, + #[cfg(feature = "parachain")] parachain_id: cumulus_primitives_core::ParaId, +) -> Result, String> { + Ok(match id { + #[cfg(feature = "with-battery-station-runtime")] + "" | "dev" => Box::new(crate::chain_spec::dev_config( + #[cfg(feature = "parachain")] + parachain_id, + )?), + "battery_station" => Box::new(crate::chain_spec::DummyChainSpec::from_json_bytes( + #[cfg(feature = "parachain")] + &include_bytes!("../res/bs_parachain.json")[..], + #[cfg(not(feature = "parachain"))] + &include_bytes!("../res/bs.json")[..], + )?), + #[cfg(feature = "with-battery-station-runtime")] + "battery_station_staging" => Box::new(crate::chain_spec::battery_station_staging_config( + #[cfg(feature = "parachain")] + parachain_id, + )?), + #[cfg(not(feature = "with-battery-station-runtime"))] + "battery_station_staging" => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), + "zeitgeist" => Box::new(crate::chain_spec::DummyChainSpec::from_json_bytes( + #[cfg(feature = "parachain")] + &include_bytes!("../res/zeitgeist_parachain.json")[..], + #[cfg(not(feature = "parachain"))] + &include_bytes!("../res/zeitgeist.json")[..], + )?), + #[cfg(feature = "with-zeitgeist-runtime")] + "zeitgeist_staging" => Box::new(crate::chain_spec::zeitgeist_staging_config( + #[cfg(feature = "parachain")] + parachain_id, + )?), + #[cfg(not(feature = "with-zeitgeist-runtime"))] + "zeitgeist_staging" => panic!("{}", crate::ZEITGEIST_RUNTIME_NOT_AVAILABLE), + path => { + let spec = Box::new(crate::chain_spec::DummyChainSpec::from_json_file( + std::path::PathBuf::from(path), + )?) as Box; + + match spec { + spec if spec.is_zeitgeist() => { + #[cfg(feature = "with-zeitgeist-runtime")] + return Ok(Box::new( + crate::chain_spec::zeitgeist::ZeitgeistChainSpec::from_json_file( + std::path::PathBuf::from(path), + )?, + )); + #[cfg(not(feature = "with-zeitgeist-runtime"))] + panic!("{}", crate::ZEITGEIST_RUNTIME_NOT_AVAILABLE); + } + _ => { + #[cfg(feature = "with-battery-station-runtime")] + return Ok( + Box::new( + crate::chain_spec::battery_station::BatteryStationChainSpec::from_json_file( + std::path::PathBuf::from(path) + )? + ) + ); + #[cfg(not(feature = "with-battery-station-runtime"))] + panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE); + } + } + } + }) +} + #[derive(Debug, clap::Subcommand)] pub enum Subcommand { /// The custom benchmark subcommmand benchmarking runtime pallets. @@ -133,8 +224,21 @@ impl SubstrateCli for Cli { ) } - fn native_runtime_version(_: &Box) -> &'static RuntimeVersion { - &zeitgeist_runtime::VERSION + fn native_runtime_version(spec: &Box) -> &'static RuntimeVersion { + match spec { + spec if spec.is_zeitgeist() => { + #[cfg(feature = "with-zeitgeist-runtime")] + return &zeitgeist_runtime::VERSION; + #[cfg(not(feature = "with-zeitgeist-runtime"))] + panic!("{}", crate::ZEITGEIST_RUNTIME_NOT_AVAILABLE); + } + _spec => { + #[cfg(feature = "with-battery-station-runtime")] + return &battery_station_runtime::VERSION; + #[cfg(not(feature = "with-battery-station-runtime"))] + panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE); + } + } } fn support_url() -> String { @@ -142,37 +246,290 @@ impl SubstrateCli for Cli { } } -pub fn load_spec( - id: &str, - #[cfg(feature = "parachain")] parachain_id: cumulus_primitives_core::ParaId, -) -> Result, String> { - Ok(match id { - "" | "dev" => Box::new(crate::chain_spec::dev_config( - #[cfg(feature = "parachain")] - parachain_id, - )?), - "battery_station" => Box::new(crate::chain_spec::ChainSpec::from_json_bytes( - #[cfg(feature = "parachain")] - &include_bytes!("../res/bs_parachain.json")[..], - #[cfg(not(feature = "parachain"))] - &include_bytes!("../res/bs.json")[..], - )?), - "battery_station_staging" => Box::new(crate::chain_spec::battery_station_staging_config( - #[cfg(feature = "parachain")] - parachain_id, - )?), - "zeitgeist" => Box::new(crate::chain_spec::ChainSpec::from_json_bytes( - #[cfg(feature = "parachain")] - &include_bytes!("../res/zeitgeist_parachain.json")[..], - #[cfg(not(feature = "parachain"))] - &include_bytes!("../res/zeitgeist.json")[..], - )?), - "zeitgeist_staging" => Box::new(crate::chain_spec::zeitgeist_staging_config( - #[cfg(feature = "parachain")] - parachain_id, - )?), - path => { - Box::new(crate::chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?) +/// Config that abstracts over all available client implementations. +/// +/// For a concrete type there exists [`Client`]. +pub trait AbstractClient: + BlockchainEvents + + Sized + + Send + + Sync + + ProvideRuntimeApi + + HeaderBackend + + CallApiAt +where + Block: BlockT, + Backend: BackendT, + Backend::State: sp_api::StateBackend, + Self::Api: RuntimeApiCollection + + AdditionalRuntimeApiCollection, +{ +} + +impl AbstractClient for Client +where + Block: BlockT, + Backend: BackendT, + Backend::State: sp_api::StateBackend, + Client: BlockchainEvents + + ProvideRuntimeApi + + HeaderBackend + + Sized + + Send + + Sync + + CallApiAt, + Client::Api: RuntimeApiCollection + + AdditionalRuntimeApiCollection, +{ +} + +/// Execute something with the client instance. +/// +/// As there exist multiple chains inside Zeitgeist, like Zeitgeist itself, +/// Battery Station etc., there can exist different kinds of client types. As these +/// client types differ in the generics that are being used, we can not easily +/// return them from a function. For returning them from a function there exists +/// [`Client`]. However, the problem on how to use this client instance still +/// exists. This trait "solves" it in a dirty way. It requires a type to +/// implement this trait and than the [`execute_with_client`](ExecuteWithClient: +/// :execute_with_client) function can be called with any possible client +/// instance. +/// +/// In a perfect world, we could make a closure work in this way. +pub trait ExecuteWithClient { + /// The return type when calling this instance. + type Output; + + /// Execute whatever should be executed with the given client instance. + fn execute_with_client(self, client: Arc) -> Self::Output + where + >::StateBackend: sp_api::StateBackend, + Backend: sc_client_api::Backend, + Backend::State: sp_api::StateBackend, + Api: RuntimeApiCollection + + AdditionalRuntimeApiCollection, + Client: AbstractClient + 'static; +} + +/// A handle to a Zeitgeist client instance. +/// +/// The Zeitgeist service supports multiple different runtimes (Zeitgeist, Battery +/// Station, etc.). As each runtime has a specialized client, we need to hide them +/// behind a trait. This is this trait. +/// +/// When wanting to work with the inner client, you need to use `execute_with`. +pub trait ClientHandle { + /// Execute the given something with the client. + fn execute_with(&self, t: T) -> T::Output; +} + +/// A client instance of Zeitgeist. +#[derive(Clone)] +pub enum Client { + #[cfg(feature = "with-battery-station-runtime")] + BatteryStation(Arc>), + #[cfg(feature = "with-zeitgeist-runtime")] + Zeitgeist(Arc>), +} + +#[cfg(feature = "with-battery-station-runtime")] +impl From>> for Client { + fn from(client: Arc>) -> Self { + Self::BatteryStation(client) + } +} + +#[cfg(feature = "with-zeitgeist-runtime")] +impl From>> for Client { + fn from(client: Arc>) -> Self { + Self::Zeitgeist(client) + } +} + +impl ClientHandle for Client { + fn execute_with(&self, t: T) -> T::Output { + match self { + #[cfg(feature = "with-battery-station-runtime")] + Self::BatteryStation(client) => { + T::execute_with_client::<_, _, FullBackend>(t, client.clone()) + } + #[cfg(feature = "with-zeitgeist-runtime")] + Self::Zeitgeist(client) => { + T::execute_with_client::<_, _, FullBackend>(t, client.clone()) + } } - }) + } +} + +macro_rules! match_client { + ($self:ident, $method:ident($($param:ident),*)) => { + match $self { + #[cfg(feature = "with-battery-station-runtime")] + Self::BatteryStation(client) => client.$method($($param),*), + #[cfg(feature = "with-zeitgeist-runtime")] + Self::Zeitgeist(client) => client.$method($($param),*), + } + }; +} + +impl sc_client_api::UsageProvider for Client { + fn usage_info(&self) -> sc_client_api::ClientInfo { + match_client!(self, usage_info()) + } +} + +impl sc_client_api::BlockBackend for Client { + fn block_body( + &self, + id: &BlockId, + ) -> sp_blockchain::Result::Extrinsic>>> { + match_client!(self, block_body(id)) + } + + fn block_indexed_body( + &self, + id: &BlockId, + ) -> sp_blockchain::Result>>> { + match_client!(self, block_indexed_body(id)) + } + + fn block(&self, id: &BlockId) -> sp_blockchain::Result>> { + match_client!(self, block(id)) + } + + fn block_status(&self, id: &BlockId) -> sp_blockchain::Result { + match_client!(self, block_status(id)) + } + + fn justifications(&self, id: &BlockId) -> sp_blockchain::Result> { + match_client!(self, justifications(id)) + } + + fn block_hash( + &self, + number: NumberFor, + ) -> sp_blockchain::Result::Hash>> { + match_client!(self, block_hash(number)) + } + + fn indexed_transaction( + &self, + hash: &::Hash, + ) -> sp_blockchain::Result>> { + match_client!(self, indexed_transaction(hash)) + } + + fn has_indexed_transaction( + &self, + hash: &::Hash, + ) -> sp_blockchain::Result { + match_client!(self, has_indexed_transaction(hash)) + } +} + +impl sc_client_api::StorageProvider for Client { + fn storage( + &self, + id: &BlockId, + key: &StorageKey, + ) -> sp_blockchain::Result> { + match_client!(self, storage(id, key)) + } + + fn storage_keys( + &self, + id: &BlockId, + key_prefix: &StorageKey, + ) -> sp_blockchain::Result> { + match_client!(self, storage_keys(id, key_prefix)) + } + + fn storage_hash( + &self, + id: &BlockId, + key: &StorageKey, + ) -> sp_blockchain::Result::Hash>> { + match_client!(self, storage_hash(id, key)) + } + + fn storage_pairs( + &self, + id: &BlockId, + key_prefix: &StorageKey, + ) -> sp_blockchain::Result> { + match_client!(self, storage_pairs(id, key_prefix)) + } + + fn storage_keys_iter<'a>( + &self, + id: &BlockId, + prefix: Option<&'a StorageKey>, + start_key: Option<&StorageKey>, + ) -> sp_blockchain::Result< + KeyIterator<'a, >::State, Block>, + > { + match_client!(self, storage_keys_iter(id, prefix, start_key)) + } + + fn child_storage( + &self, + id: &BlockId, + child_info: &ChildInfo, + key: &StorageKey, + ) -> sp_blockchain::Result> { + match_client!(self, child_storage(id, child_info, key)) + } + + fn child_storage_keys( + &self, + id: &BlockId, + child_info: &ChildInfo, + key_prefix: &StorageKey, + ) -> sp_blockchain::Result> { + match_client!(self, child_storage_keys(id, child_info, key_prefix)) + } + + fn child_storage_keys_iter<'a>( + &self, + id: &BlockId, + child_info: ChildInfo, + prefix: Option<&'a StorageKey>, + start_key: Option<&StorageKey>, + ) -> sp_blockchain::Result< + KeyIterator<'a, >::State, Block>, + > { + match_client!(self, child_storage_keys_iter(id, child_info, prefix, start_key)) + } + + fn child_storage_hash( + &self, + id: &BlockId, + child_info: &ChildInfo, + key: &StorageKey, + ) -> sp_blockchain::Result::Hash>> { + match_client!(self, child_storage_hash(id, child_info, key)) + } +} + +impl sp_blockchain::HeaderBackend for Client { + fn header(&self, id: BlockId) -> sp_blockchain::Result> { + let id = &id; + match_client!(self, header(id)) + } + + fn info(&self) -> sp_blockchain::Info { + match_client!(self, info()) + } + + fn status(&self, id: BlockId) -> sp_blockchain::Result { + match_client!(self, status(id)) + } + + fn number(&self, hash: Hash) -> sp_blockchain::Result> { + match_client!(self, number(hash)) + } + + fn hash(&self, number: BlockNumber) -> sp_blockchain::Result> { + match_client!(self, hash(number)) + } } diff --git a/node/src/command.rs b/node/src/command.rs index 2e6c6c90d..8b7ad285c 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -1,13 +1,18 @@ use super::{ cli::{Cli, Subcommand}, command_helper::{inherent_benchmark_data, BenchmarkExtrinsicBuilder}, - service::{new_partial, ExecutorDispatch}, + service::{new_chain_ops, new_full, IdentifyVariant}, }; use frame_benchmarking_cli::BenchmarkCmd; use sc_cli::SubstrateCli; -use sc_service::PartialComponents; use std::sync::Arc; -use zeitgeist_runtime::{Block, RuntimeApi}; +#[cfg(feature = "with-battery-station-runtime")] +use { + super::service::BatteryStationExecutor, + battery_station_runtime::RuntimeApi as BatteryStationRuntimeApi, +}; +#[cfg(feature = "with-zeitgeist-runtime")] +use {super::service::ZeitgeistExecutor, zeitgeist_runtime::RuntimeApi as ZeitgeistRuntimeApi}; #[cfg(feature = "parachain")] use { sc_client_api::client::BlockBackend, sp_core::hexdisplay::HexDisplay, sp_core::Encode, @@ -30,46 +35,124 @@ pub fn run() -> sc_cli::Result<()> { match &cli.subcommand { Some(Subcommand::Benchmark(cmd)) => { let runner = cli.create_runner(cmd)?; + let chain_spec = &runner.config().chain_spec; - runner.sync_run(|config| { - let PartialComponents { client, backend, .. } = - new_partial::(&config)?; - + match cmd { // This switch needs to be in the client, since the client decides // which sub-commands it wants to support. - match cmd { - BenchmarkCmd::Pallet(cmd) => { - if !cfg!(feature = "runtime-benchmarks") { - return Err("Runtime benchmarking wasn't enabled when building the \ - node. You can enable it with `--features \ - runtime-benchmarks`." - .into()); - } - - cmd.run::(config) + BenchmarkCmd::Pallet(cmd) => { + if !cfg!(feature = "runtime-benchmarks") { + return Err("Runtime benchmarking wasn't enabled when building the node. \ + You can enable it with `--features runtime-benchmarks`." + .into()); } - BenchmarkCmd::Block(cmd) => cmd.run(client), - BenchmarkCmd::Storage(cmd) => { - let db = backend.expose_db(); - let storage = backend.expose_storage(); - cmd.run(config, client, db, storage) + match chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => runner.sync_run(|config| { + cmd.run::(config) + }), + #[cfg(feature = "with-battery-station-runtime")] + _ => runner.sync_run(|config| { + cmd.run::( + config, + ) + }), + #[cfg(not(feature = "with-battery-station-runtime"))] + _ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), + } + } + BenchmarkCmd::Block(cmd) => match chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => runner.sync_run(|config| { + let params = crate::service::new_partial::< + zeitgeist_runtime::RuntimeApi, + ZeitgeistExecutor, + >(&config)?; + cmd.run(params.client) + }), + #[cfg(feature = "with-battery-station-runtime")] + _ => runner.sync_run(|config| { + let params = crate::service::new_partial::< + battery_station_runtime::RuntimeApi, + BatteryStationExecutor, + >(&config)?; + cmd.run(params.client) + }), + #[cfg(not(feature = "with-battery-station-runtime"))] + _ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), + }, + BenchmarkCmd::Storage(cmd) => match chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => runner.sync_run(|config| { + let params = crate::service::new_partial::< + zeitgeist_runtime::RuntimeApi, + ZeitgeistExecutor, + >(&config)?; + + let db = params.backend.expose_db(); + let storage = params.backend.expose_storage(); + + cmd.run(config, params.client, db, storage) + }), + #[cfg(feature = "with-battery-station-runtime")] + _ => runner.sync_run(|config| { + let params = crate::service::new_partial::< + battery_station_runtime::RuntimeApi, + BatteryStationExecutor, + >(&config)?; + + let db = params.backend.expose_db(); + let storage = params.backend.expose_storage(); + + cmd.run(config, params.client, db, storage) + }), + #[cfg(not(feature = "with-battery-station-runtime"))] + _ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), + }, + + BenchmarkCmd::Overhead(cmd) => { + if cfg!(feature = "parachain") { + return Err("Overhead is only supported in standalone chain".into()); } - BenchmarkCmd::Overhead(cmd) => { - if cfg!(feature = "parachain") { - Err("Overhead is only supported in standalone chain".into()) - } else { - let ext_builder = BenchmarkExtrinsicBuilder::new(client.clone()); + match chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => runner.sync_run(|config| { + let params = crate::service::new_partial::< + zeitgeist_runtime::RuntimeApi, + ZeitgeistExecutor, + >(&config)?; + + let ext_builder = + BenchmarkExtrinsicBuilder::new(params.client.clone(), true); cmd.run( config, - client, + params.client, inherent_benchmark_data()?, Arc::new(ext_builder), ) - } + }), + #[cfg(feature = "with-battery-station-runtime")] + _ => runner.sync_run(|config| { + let params = crate::service::new_partial::< + battery_station_runtime::RuntimeApi, + BatteryStationExecutor, + >(&config)?; + + let ext_builder = + BenchmarkExtrinsicBuilder::new(params.client.clone(), false); + cmd.run( + config, + params.client, + inherent_benchmark_data()?, + Arc::new(ext_builder), + ) + }), + #[cfg(not(feature = "with-battery-station-runtime"))] + _ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), } } - }) + } } Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; @@ -77,17 +160,15 @@ pub fn run() -> sc_cli::Result<()> { } Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, import_queue, .. } = - new_partial::(&config)?; + runner.async_run(|mut config| { + let (client, _, import_queue, task_manager) = new_chain_ops(&mut config)?; Ok((cmd.run(client, import_queue), task_manager)) }) } Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, .. } = - new_partial::(&config)?; + runner.async_run(|mut config| { + let (client, _, _, task_manager) = new_chain_ops(&mut config)?; Ok((cmd.run(client, config.database), task_manager)) }) } @@ -95,11 +176,8 @@ pub fn run() -> sc_cli::Result<()> { Some(Subcommand::ExportHeader(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| { - let PartialComponents { client, .. }: crate::service::ParachainPartialComponents< - ExecutorDispatch, - RuntimeApi, - > = crate::service::new_partial(&config)?; + runner.sync_run(|mut config| { + let (client, _, _, _) = new_chain_ops(&mut config)?; match client.block(&cmd.input.parse()?) { Ok(Some(block)) => { @@ -122,13 +200,39 @@ pub fn run() -> sc_cli::Result<()> { )?; let state_version = Cli::native_runtime_version(chain_spec).state_version(); - let block: zeitgeist_runtime::Block = - cumulus_client_service::genesis::generate_genesis_block(chain_spec, state_version)?; - let raw_header = block.header().encode(); - let buf = if params.raw { - raw_header - } else { - format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() + let buf = match chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => { + let block: zeitgeist_runtime::Block = + cumulus_client_service::genesis::generate_genesis_block( + chain_spec, + state_version, + )?; + let raw_header = block.header().encode(); + + if params.raw { + raw_header + } else { + format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() + } + } + #[cfg(feature = "with-battery-station-runtime")] + _ => { + let block: battery_station_runtime::Block = + cumulus_client_service::genesis::generate_genesis_block( + chain_spec, + state_version, + )?; + let raw_header = block.header().encode(); + + if params.raw { + raw_header + } else { + format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() + } + } + #[cfg(not(feature = "with-battery-station-runtime"))] + _ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), }; if let Some(output) = ¶ms.output { @@ -163,17 +267,15 @@ pub fn run() -> sc_cli::Result<()> { } Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, .. } = - new_partial::(&config)?; + runner.async_run(|mut config| { + let (client, _, _, task_manager) = new_chain_ops(&mut config)?; Ok((cmd.run(client, config.chain_spec), task_manager)) }) } Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, import_queue, .. } = - new_partial::(&config)?; + runner.async_run(|mut config| { + let (client, _, import_queue, task_manager) = new_chain_ops(&mut config)?; Ok((cmd.run(client, import_queue), task_manager)) }) } @@ -207,31 +309,51 @@ pub fn run() -> sc_cli::Result<()> { } Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, backend, .. } = - new_partial::(&config)?; - - let aux_revert = Box::new(move |client, _, blocks| { - sc_finality_grandpa::revert(client, blocks)?; - Ok(()) - }); + runner.async_run(|mut config| { + let (client, backend, _, task_manager) = new_chain_ops(&mut config)?; - Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) + Ok((cmd.run(client, backend, None), task_manager)) }) } #[cfg(feature = "try-runtime")] Some(Subcommand::TryRuntime(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - // we don't need any of the components of new_partial, just a runtime, or a task - // manager to do `async_run`. - let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry); - let task_manager = - sc_service::TaskManager::new(config.tokio_handle.clone(), registry) - .map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?; - - Ok((cmd.run::(config), task_manager)) - }) + let chain_spec = &runner.config().chain_spec; + + match chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => { + runner.async_run(|config| { + // we don't need any of the components of new_partial, just a runtime, or a task + // manager to do `async_run`. + let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry); + let task_manager = + sc_service::TaskManager::new(config.tokio_handle.clone(), registry) + .map_err(|e| { + sc_cli::Error::Service(sc_service::Error::Prometheus(e)) + })?; + return Ok(( + cmd.run::(config), + task_manager, + )); + }) + } + #[cfg(feature = "with-battery-station-runtime")] + _ => runner.async_run(|config| { + let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry); + let task_manager = + sc_service::TaskManager::new(config.tokio_handle.clone(), registry) + .map_err(|e| { + sc_cli::Error::Service(sc_service::Error::Prometheus(e)) + })?; + return Ok(( + cmd.run::(config), + task_manager, + )); + }), + #[cfg(not(feature = "with-battery-station-runtime"))] + _ => Err("Invalid chain spec"), + } } #[cfg(not(feature = "try-runtime"))] Some(Subcommand::TryRuntime) => Err("TryRuntime wasn't enabled when building the node. \ @@ -288,10 +410,28 @@ fn none_command(cli: &Cli) -> sc_cli::Result<()> { log::info!("Parachain Account: {}", parachain_account); log::info!("Parachain genesis state: {}", genesis_state); - crate::service::new_full(parachain_config, parachain_id, polkadot_config) + match ¶chain_config.chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => new_full::( + parachain_config, + parachain_id, + polkadot_config, + ) + .await + .map(|r| r.0) + .map_err(Into::into), + #[cfg(feature = "with-battery-station-runtime")] + _ => new_full::( + parachain_config, + parachain_id, + polkadot_config, + ) .await .map(|r| r.0) - .map_err(Into::into) + .map_err(Into::into), + #[cfg(not(feature = "with-battery-station-runtime"))] + _ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), + } }) } @@ -299,10 +439,30 @@ fn none_command(cli: &Cli) -> sc_cli::Result<()> { fn none_command(cli: &Cli) -> sc_cli::Result<()> { let runner = cli.create_runner(&cli.run)?; runner.run_node_until_exit(|config| async move { - match config.role { - sc_cli::Role::Light => return Err("Light client not supported!".into()), - _ => crate::service::new_full(config), + if let sc_cli::Role::Light = config.role { + return Err("Light client not supported!".into()); + } + + match &config.chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => { + new_full::(config) + .map_err(sc_cli::Error::Service) + } + #[cfg(feature = "with-battery-station-runtime")] + _ => new_full::(config) + .map_err(sc_cli::Error::Service), + #[cfg(all( + not(feature = "with-battery-station-runtime"), + feature = "with-zeitgeist-runtime" + ))] + _ => new_full::(config) + .map_err(sc_cli::Error::Service), + #[cfg(all( + not(feature = "with-battery-station-runtime"), + not(feature = "with-zeitgeist-runtime") + ))] + _ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), } - .map_err(sc_cli::Error::Service) }) } diff --git a/node/src/command_helper.rs b/node/src/command_helper.rs index 81157acee..aecfdacd0 100644 --- a/node/src/command_helper.rs +++ b/node/src/command_helper.rs @@ -1,4 +1,4 @@ -use crate::service::FullClient; +use super::service::FullClient; use sc_cli::Result; use sc_client_api::BlockBackend; @@ -9,21 +9,21 @@ use sp_keyring::Sr25519Keyring; use sp_runtime::{OpaqueExtrinsic, SaturatedConversion}; use std::{sync::Arc, time::Duration}; use zeitgeist_primitives::{constants::BlockHashCount, types::Signature}; -use zeitgeist_runtime::{SystemCall, UncheckedExtrinsic, VERSION}; /// Generates extrinsics for the `benchmark overhead` command. /// /// Note: Should only be used for benchmarking. pub struct BenchmarkExtrinsicBuilder { client: Arc>, + is_zeitgeist: bool, } impl BenchmarkExtrinsicBuilder { /// Creates a new [`Self`] from the given client. - pub fn new(client: Arc>) -> Self { - Self { client } + pub fn new(client: Arc>, is_zeitgeist: bool) -> Self { + Self { client, is_zeitgeist } } } @@ -32,27 +32,45 @@ impl { fn remark(&self, nonce: u32) -> std::result::Result { let acc = Sr25519Keyring::Bob.pair(); - let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic( - self.client.as_ref(), - acc, - SystemCall::remark { remark: vec![] }.into(), - nonce, - ) - .into(); - - Ok(extrinsic) + + #[cfg(feature = "with-zeitgeist-runtime")] + if self.is_zeitgeist { + return Ok(create_benchmark_extrinsic_zeitgeist( + self.client.as_ref(), + acc, + zeitgeist_runtime::SystemCall::remark { remark: vec![] }.into(), + nonce, + ) + .into()); + } + #[cfg(feature = "with-battery-station-runtime")] + if !self.is_zeitgeist { + return Ok(create_benchmark_extrinsic_battery_station( + self.client.as_ref(), + acc, + battery_station_runtime::SystemCall::remark { remark: vec![] }.into(), + nonce, + ) + .into()); + } + + Err(crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE) } } /// Creates a transaction using the given `call`. /// /// Note: Should only be used for benchmarking. -pub fn create_benchmark_extrinsic( +#[cfg(feature = "with-zeitgeist-runtime")] +pub fn create_benchmark_extrinsic_zeitgeist< + RuntimeApi, + Executor: NativeExecutionDispatch + 'static, +>( client: &FullClient, sender: sp_core::sr25519::Pair, call: zeitgeist_runtime::Call, nonce: u32, -) -> UncheckedExtrinsic { +) -> zeitgeist_runtime::UncheckedExtrinsic { let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); let best_hash = client.chain_info().best_hash; let best_block = client.chain_info().best_number; @@ -69,7 +87,7 @@ pub fn create_benchmark_extrinsic::from(nonce.into()), zeitgeist_runtime::CheckWeight::::new(), - zeitgeist_runtime::ChargeTransactionPayment::::from(0), + pallet_transaction_payment::ChargeTransactionPayment::::from(0), ); let raw_payload = zeitgeist_runtime::SignedPayload::from_raw( @@ -77,8 +95,64 @@ pub fn create_benchmark_extrinsic( + client: &FullClient, + sender: sp_core::sr25519::Pair, + call: battery_station_runtime::Call, + nonce: u32, +) -> battery_station_runtime::UncheckedExtrinsic { + let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); + let best_hash = client.chain_info().best_hash; + let best_block = client.chain_info().best_number; + + let period = + BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64; + let extra: battery_station_runtime::SignedExtra = ( + battery_station_runtime::CheckNonZeroSender::::new(), + battery_station_runtime::CheckSpecVersion::::new(), + battery_station_runtime::CheckTxVersion::::new(), + battery_station_runtime::CheckGenesis::::new(), + battery_station_runtime::CheckEra::::from( + sp_runtime::generic::Era::mortal(period, best_block.saturated_into()), + ), + battery_station_runtime::CheckNonce::::from(nonce.into()), + battery_station_runtime::CheckWeight::::new(), + pallet_transaction_payment::ChargeTransactionPayment::::from(0), + ); + + let raw_payload = battery_station_runtime::SignedPayload::from_raw( + call.clone(), + extra.clone(), + ( + (), + battery_station_runtime::VERSION.spec_version, + battery_station_runtime::VERSION.transaction_version, genesis_hash, best_hash, (), @@ -88,7 +162,7 @@ pub fn create_benchmark_extrinsic { diff --git a/node/src/service.rs b/node/src/service.rs index 4c66833bf..c02a419b0 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -4,17 +4,47 @@ mod service_parachain; mod service_standalone; use sp_runtime::traits::BlakeTwo256; -use zeitgeist_primitives::types::{AccountId, Balance, Index, MarketId, PoolId}; -use zeitgeist_runtime::opaque::Block; +use zeitgeist_primitives::types::{AccountId, Balance, Block, Index, MarketId, PoolId}; +use super::cli::Client; +use sc_executor::NativeExecutionDispatch; +use sc_service::{ + error::Error as ServiceError, ChainSpec, Configuration, PartialComponents, TaskManager, +}; #[cfg(feature = "parachain")] -pub use service_parachain::{new_full, new_partial, FullClient, ParachainPartialComponents}; +pub use service_parachain::{ + new_full, new_partial, FullBackend, FullClient, ParachainPartialComponents, +}; #[cfg(not(feature = "parachain"))] -pub use service_standalone::{new_full, new_partial, FullClient}; +pub use service_standalone::{new_full, new_partial, FullBackend, FullClient}; +use sp_api::ConstructRuntimeApi; +use sp_trie::PrefixedMemoryDB; +use std::sync::Arc; -pub struct ExecutorDispatch; +#[cfg(feature = "with-battery-station-runtime")] +pub struct BatteryStationExecutor; -impl sc_executor::NativeExecutionDispatch for ExecutorDispatch { +#[cfg(feature = "with-battery-station-runtime")] +impl sc_executor::NativeExecutionDispatch for BatteryStationExecutor { + #[cfg(feature = "runtime-benchmarks")] + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + #[cfg(not(feature = "runtime-benchmarks"))] + type ExtendHostFunctions = (); + + fn dispatch(method: &str, data: &[u8]) -> Option> { + battery_station_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + battery_station_runtime::native_version() + } +} + +#[cfg(feature = "with-zeitgeist-runtime")] +pub struct ZeitgeistExecutor; + +#[cfg(feature = "with-zeitgeist-runtime")] +impl sc_executor::NativeExecutionDispatch for ZeitgeistExecutor { #[cfg(feature = "runtime-benchmarks")] type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; #[cfg(not(feature = "runtime-benchmarks"))] @@ -29,8 +59,28 @@ impl sc_executor::NativeExecutionDispatch for ExecutorDispatch { } } +/// Can be called for a `Configuration` to check if it is a configuration for +/// the `Zeitgeist` network. +pub trait IdentifyVariant { + /// Returns `true` if this is a configuration for the `Battery Station` network. + fn is_battery_station(&self) -> bool; + + /// Returns `true` if this is a configuration for the `Zeitgeist` network. + fn is_zeitgeist(&self) -> bool; +} + +impl IdentifyVariant for Box { + fn is_battery_station(&self) -> bool { + self.id().starts_with("battery_station") + } + + fn is_zeitgeist(&self) -> bool { + self.id().starts_with("zeitgeist") + } +} + /// A set of common runtime APIs between standalone an parachain runtimes. -pub trait CommonRuntimeApiCollection: +pub trait RuntimeApiCollection: sp_transaction_pool::runtime_api::TaggedTransactionQueue + sp_api::ApiExt + sp_block_builder::BlockBuilder @@ -45,7 +95,7 @@ where { } -impl CommonRuntimeApiCollection for Api +impl RuntimeApiCollection for Api where Api: sp_transaction_pool::runtime_api::TaggedTransactionQueue + sp_api::ApiExt @@ -103,3 +153,58 @@ cfg_if::cfg_if! { } } } + +/// Builds a new object suitable for chain operations. +#[allow(clippy::type_complexity)] +pub fn new_chain_ops( + config: &mut Configuration, +) -> Result< + ( + Arc, + Arc, + sc_consensus::BasicQueue>, + TaskManager, + ), + ServiceError, +> { + match &config.chain_spec { + #[cfg(feature = "with-zeitgeist-runtime")] + spec if spec.is_zeitgeist() => { + new_chain_ops_inner::(config) + } + #[cfg(feature = "with-battery-station-runtime")] + _ => new_chain_ops_inner::( + config, + ), + #[cfg(not(feature = "with-battery-station-runtime"))] + _ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE), + } +} + +#[allow(clippy::type_complexity)] +fn new_chain_ops_inner( + mut config: &mut Configuration, +) -> Result< + ( + Arc, + Arc, + sc_consensus::BasicQueue>, + TaskManager, + ), + ServiceError, +> +where + Client: From>>, + RuntimeApi: + ConstructRuntimeApi> + Send + Sync + 'static, + RuntimeApi::RuntimeApi: RuntimeApiCollection> + + AdditionalRuntimeApiCollection< + StateBackend = sc_client_api::StateBackendFor, + >, + Executor: NativeExecutionDispatch + 'static, +{ + config.keystore = sc_service::config::KeystoreConfig::InMemory; + let PartialComponents { client, backend, import_queue, task_manager, .. } = + new_partial::(config)?; + Ok((Arc::new(Client::from(client)), backend, import_queue, task_manager)) +} diff --git a/node/src/service/service_parachain.rs b/node/src/service/service_parachain.rs index 1a89f3941..1db4a3c94 100644 --- a/node/src/service/service_parachain.rs +++ b/node/src/service/service_parachain.rs @@ -1,5 +1,5 @@ use crate::{ - service::{AdditionalRuntimeApiCollection, CommonRuntimeApiCollection, ExecutorDispatch}, + service::{AdditionalRuntimeApiCollection, RuntimeApiCollection}, KUSAMA_BLOCK_DURATION, SOFT_DEADLINE_PERCENT, }; use cumulus_client_cli::CollatorOptions; @@ -21,10 +21,9 @@ use sp_api::ConstructRuntimeApi; use sp_keystore::SyncCryptoStorePtr; use std::sync::Arc; use substrate_prometheus_endpoint::Registry; -use zeitgeist_primitives::types::Hash; -use zeitgeist_runtime::{opaque::Block, RuntimeApi}; +use zeitgeist_primitives::types::{Block, Hash}; -type FullBackend = TFullBackend; +pub type FullBackend = TFullBackend; pub type FullClient = TFullClient>; pub type ParachainPartialComponents = PartialComponents< @@ -37,11 +36,20 @@ pub type ParachainPartialComponents = PartialComponents< >; /// Start a parachain node. -pub async fn new_full( +pub async fn new_full( parachain_config: Configuration, parachain_id: ParaId, polkadot_config: Configuration, -) -> sc_service::error::Result<(TaskManager, Arc>)> { +) -> sc_service::error::Result<(TaskManager, Arc>)> +where + RuntimeApi: + ConstructRuntimeApi> + Send + Sync + 'static, + RuntimeApi::RuntimeApi: RuntimeApiCollection> + + AdditionalRuntimeApiCollection< + StateBackend = sc_client_api::StateBackendFor, + >, + Executor: NativeExecutionDispatch + 'static, +{ do_new_full( parachain_config, polkadot_config, @@ -115,9 +123,8 @@ pub fn new_partial( where RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: CommonRuntimeApiCollection< - StateBackend = sc_client_api::StateBackendFor, - > + AdditionalRuntimeApiCollection< + RuntimeApi::RuntimeApi: RuntimeApiCollection> + + AdditionalRuntimeApiCollection< StateBackend = sc_client_api::StateBackendFor, >, Executor: NativeExecutionDispatch + 'static, @@ -201,9 +208,8 @@ async fn do_new_full( where RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: CommonRuntimeApiCollection< - StateBackend = sc_client_api::StateBackendFor, - > + AdditionalRuntimeApiCollection< + RuntimeApi::RuntimeApi: RuntimeApiCollection> + + AdditionalRuntimeApiCollection< StateBackend = sc_client_api::StateBackendFor, >, Executor: NativeExecutionDispatch + 'static, diff --git a/node/src/service/service_standalone.rs b/node/src/service/service_standalone.rs index 7a6159ed5..57057dc29 100644 --- a/node/src/service/service_standalone.rs +++ b/node/src/service/service_standalone.rs @@ -1,8 +1,6 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. -use crate::service::{ - AdditionalRuntimeApiCollection, CommonRuntimeApiCollection, ExecutorDispatch, -}; +use crate::service::{AdditionalRuntimeApiCollection, RuntimeApiCollection}; use sc_client_api::{BlockBackend, ExecutorProvider}; use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_executor::{NativeElseWasmExecutor, NativeExecutionDispatch}; @@ -15,15 +13,26 @@ use sc_telemetry::{Telemetry, TelemetryWorker}; use sp_api::ConstructRuntimeApi; use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; use std::{sync::Arc, time::Duration}; -use zeitgeist_runtime::{opaque::Block, RuntimeApi}; +use zeitgeist_primitives::types::Block; pub type FullClient = TFullClient>; -type FullBackend = TFullBackend; +pub type FullBackend = TFullBackend; type FullSelectChain = sc_consensus::LongestChain; /// Builds a new service for a full client. -pub fn new_full(mut config: Configuration) -> Result { +pub fn new_full( + mut config: Configuration, +) -> Result +where + RuntimeApi: + ConstructRuntimeApi> + Send + Sync + 'static, + RuntimeApi::RuntimeApi: RuntimeApiCollection> + + AdditionalRuntimeApiCollection< + StateBackend = sc_client_api::StateBackendFor, + >, + Executor: NativeExecutionDispatch + 'static, +{ let sc_service::PartialComponents { client, backend, @@ -33,7 +42,7 @@ pub fn new_full(mut config: Configuration) -> Result select_chain, transaction_pool, other: (block_import, grandpa_link, mut telemetry), - } = new_partial::(&config)?; + } = new_partial::(&config)?; if let Some(url) = &config.keystore_remote { match remote_keystore(url) { @@ -232,9 +241,8 @@ pub fn new_partial( where RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: CommonRuntimeApiCollection< - StateBackend = sc_client_api::StateBackendFor, - > + AdditionalRuntimeApiCollection< + RuntimeApi::RuntimeApi: RuntimeApiCollection> + + AdditionalRuntimeApiCollection< StateBackend = sc_client_api::StateBackendFor, >, Executor: NativeExecutionDispatch + 'static, diff --git a/primitives/src/types.rs b/primitives/src/types.rs index 0500ec8da..4cfe814dc 100644 --- a/primitives/src/types.rs +++ b/primitives/src/types.rs @@ -8,8 +8,8 @@ use frame_support::dispatch::{Decode, Encode, Weight}; use scale_info::TypeInfo; use sp_runtime::{ generic, - traits::{IdentifyAccount, Verify}, - MultiSignature, + traits::{BlakeTwo256, IdentifyAccount, Verify}, + MultiSignature, OpaqueExtrinsic, }; /// Signed counter-part of Balance @@ -26,6 +26,9 @@ pub type AccountIndex = u64; /// Balance of an account. pub type Balance = u128; +/// Block type. +pub type Block = generic::Block; + /// An index to a block. pub type BlockNumber = u64; @@ -67,6 +70,9 @@ pub type Index = u64; /// A hash of some data used by the chain. pub type Hash = sp_core::H256; +/// Block header type as expected by this runtime. +pub type Header = generic::Header; + /// Digest item type. pub type DigestItem = generic::DigestItem; diff --git a/runtime/Cargo.toml b/runtime/battery-station/Cargo.toml similarity index 94% rename from runtime/Cargo.toml rename to runtime/battery-station/Cargo.toml index 2ed42abd3..335d17497 100644 --- a/runtime/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -91,17 +91,18 @@ log = { version = "0.4.8", default-features = false, optional = true } # Zeitgeist -zeitgeist-primitives = { default-features = false, path = "../primitives" } -zrml-authorized = { default-features = false, path = "../zrml/authorized" } -zrml-court = { default-features = false, path = "../zrml/court" } -zrml-liquidity-mining = { default-features = false, path = "../zrml/liquidity-mining" } -zrml-market-commons = { default-features = false, path = "../zrml/market-commons" } -zrml-prediction-markets = { default-features = false, path = "../zrml/prediction-markets" } -zrml-rikiddo = { default-features = false, path = "../zrml/rikiddo" } -zrml-simple-disputes = { default-features = false, path = "../zrml/simple-disputes" } -zrml-styx = { default-features = false, path = "../zrml/styx" } -zrml-swaps = { default-features = false, path = "../zrml/swaps" } -zrml-swaps-runtime-api = { default-features = false, path = "../zrml/swaps/runtime-api" } +common-runtime = { default-features = false, path = "../common" } +zeitgeist-primitives = { default-features = false, path = "../../primitives" } +zrml-authorized = { default-features = false, path = "../../zrml/authorized" } +zrml-court = { default-features = false, path = "../../zrml/court" } +zrml-liquidity-mining = { default-features = false, path = "../../zrml/liquidity-mining" } +zrml-market-commons = { default-features = false, path = "../../zrml/market-commons" } +zrml-prediction-markets = { default-features = false, path = "../../zrml/prediction-markets" } +zrml-rikiddo = { default-features = false, path = "../../zrml/rikiddo" } +zrml-simple-disputes = { default-features = false, path = "../../zrml/simple-disputes" } +zrml-styx = { default-features = false, path = "../../zrml/styx" } +zrml-swaps = { default-features = false, path = "../../zrml/swaps" } +zrml-swaps-runtime-api = { default-features = false, path = "../../zrml/swaps/runtime-api" } [dev-dependencies] sp-io = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } @@ -139,9 +140,9 @@ parachain = [ # Misc - "log" + "common-runtime/parachain", + "log", ] - runtime-benchmarks = [ "cumulus-pallet-xcmp-queue/runtime-benchmarks", "frame-benchmarking/runtime-benchmarks", @@ -274,10 +275,10 @@ std = [ "zrml-prediction-markets/std", "zrml-rikiddo/std", "zrml-simple-disputes/std", + "zrml-styx/std", "zrml-swaps-runtime-api/std", "zrml-swaps/std", ] -txfilter = [] try-runtime = [ "frame-executive/try-runtime", "frame-try-runtime", @@ -305,7 +306,6 @@ try-runtime = [ # Other Parity runtime pallets "pallet-identity/try-runtime", - "pallet-sudo/try-runtime", "pallet-utility/try-runtime", # ORML runtime pallets @@ -328,12 +328,11 @@ try-runtime = [ "pallet-author-slot-filter?/try-runtime", "parachain-staking?/try-runtime", ] -without-sudo=[] [package] authors = ["Zeitgeist PM "] edition = "2021" -name = "zeitgeist-runtime" +name = "battery-station-runtime" version = "0.3.4" [package.metadata.docs.rs] diff --git a/runtime/build.rs b/runtime/battery-station/build.rs similarity index 100% rename from runtime/build.rs rename to runtime/battery-station/build.rs diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs new file mode 100644 index 000000000..e837e3ef3 --- /dev/null +++ b/runtime/battery-station/src/lib.rs @@ -0,0 +1,127 @@ +#![cfg_attr(not(feature = "std"), no_std)] +#![recursion_limit = "256"] + +extern crate alloc; + +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +use common_runtime::{ + create_common_benchmark_logic, create_common_tests, create_runtime, create_runtime_api, + create_runtime_with_additional_pallets, decl_common_types, impl_config_traits, +}; +pub use frame_system::{ + Call as SystemCall, CheckEra, CheckGenesis, CheckNonZeroSender, CheckNonce, CheckSpecVersion, + CheckTxVersion, CheckWeight, +}; +#[cfg(feature = "parachain")] +pub use pallet_author_slot_filter::EligibilityValue; + +#[cfg(feature = "parachain")] +pub use crate::parachain_params::*; +pub use crate::parameters::*; +use alloc::vec; +use frame_support::{ + traits::{ConstU16, ConstU32, Contains, EnsureOneOf, EqualPrivilegeOnly, InstanceFilter}, + weights::{constants::RocksDbWeight, ConstantMultiplier, IdentityFee}, +}; +use frame_system::EnsureRoot; +use pallet_collective::{EnsureProportionAtLeast, PrimeDefaultVote}; +use pallet_transaction_payment::ChargeTransactionPayment; +use sp_runtime::traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256}; +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use substrate_fixed::{types::extra::U33, FixedI128, FixedU128}; +use zeitgeist_primitives::{constants::*, types::*}; +use zrml_rikiddo::types::{EmaMarketVolume, FeeSigmoid, RikiddoSigmoidMV}; +#[cfg(feature = "parachain")] +use { + frame_support::traits::{Everything, Nothing}, + frame_system::EnsureSigned, + xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, + xcm_config::XcmConfig, +}; + +use frame_support::construct_runtime; + +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + create_runtime_str, + traits::Block as BlockT, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, +}; + +#[cfg(feature = "parachain")] +use nimbus_primitives::{CanAuthor, NimbusId}; +use sp_version::RuntimeVersion; + +#[cfg(feature = "parachain")] +pub mod parachain_params; +pub mod parameters; +#[cfg(feature = "parachain")] +pub mod xcm_config; + +pub const VERSION: RuntimeVersion = RuntimeVersion { + spec_name: create_runtime_str!("zeitgeist"), + impl_name: create_runtime_str!("zeitgeist"), + authoring_version: 1, + spec_version: 38, + impl_version: 1, + apis: RUNTIME_API_VERSIONS, + transaction_version: 15, + state_version: 1, +}; + +#[derive(scale_info::TypeInfo)] +pub struct IsCallable; + +// Currently disables Court, Rikiddo and creation of markets using Court or SimpleDisputes +// dispute mechanism. +impl Contains for IsCallable { + fn contains(call: &Call) -> bool { + use zeitgeist_primitives::types::{ + MarketDisputeMechanism::{Court, SimpleDisputes}, + ScoringRule::RikiddoSigmoidFeeMarketEma, + }; + use zrml_prediction_markets::Call::{create_cpmm_market_and_deploy_assets, create_market}; + + #[allow(clippy::match_like_matches_macro)] + match call { + Call::Court(_) => false, + Call::LiquidityMining(_) => false, + Call::PredictionMarkets(inner_call) => { + match inner_call { + // Disable Rikiddo markets + create_market { scoring_rule: RikiddoSigmoidFeeMarketEma, .. } => false, + // Disable Court & SimpleDisputes dispute resolution mechanism + create_market { dispute_mechanism: Court | SimpleDisputes, .. } => false, + create_cpmm_market_and_deploy_assets { + dispute_mechanism: Court | SimpleDisputes, + .. + } => false, + _ => true, + } + } + _ => true, + } + } +} + +decl_common_types!(); + +create_runtime_with_additional_pallets!( + // Others + Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, +); + +impl pallet_sudo::Config for Runtime { + type Call = Call; + type Event = Event; +} + +impl_config_traits!(); +create_runtime_api!(); +create_common_benchmark_logic!(); +create_common_tests!(); diff --git a/runtime/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs similarity index 96% rename from runtime/src/parachain_params.rs rename to runtime/battery-station/src/parachain_params.rs index 70c615f76..b1331b3bc 100644 --- a/runtime/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -3,10 +3,11 @@ // arithmetic operations at compile time clippy::integer_arithmetic )] +#![cfg(feature = "parachain")] -use crate::{ - AccountId, Balances, Origin, ParachainInfo, ParachainSystem, XcmpQueue, BASE, - BLOCKS_PER_MINUTE, MAXIMUM_BLOCK_WEIGHT, +use super::{ + parameters::MAXIMUM_BLOCK_WEIGHT, AccountId, Balances, Origin, ParachainInfo, ParachainSystem, + XcmpQueue, }; use frame_support::{match_types, parameter_types, traits::Everything, weights::Weight}; use pallet_xcm::XcmPassthrough; @@ -19,7 +20,10 @@ use xcm_builder::{ SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, }; -use zeitgeist_primitives::{constants::MICRO, types::Balance}; +use zeitgeist_primitives::{ + constants::{BASE, BLOCKS_PER_MINUTE, MICRO}, + types::Balance, +}; match_types! { pub type ParentOrParentsUnitPlurality: impl Contains = { diff --git a/runtime/src/parameters.rs b/runtime/battery-station/src/parameters.rs similarity index 92% rename from runtime/src/parameters.rs rename to runtime/battery-station/src/parameters.rs index abd938024..de9ad30be 100644 --- a/runtime/src/parameters.rs +++ b/runtime/battery-station/src/parameters.rs @@ -4,7 +4,7 @@ clippy::integer_arithmetic )] -use crate::VERSION; +use super::VERSION; use frame_support::{ parameter_types, weights::{ @@ -98,28 +98,31 @@ parameter_types! { pub const AnnouncementDepositFactor: Balance = deposit(0, 66); // Scheduler - pub MaximumSchedulerWeight: Weight = Perbill::from_percent(10) * RuntimeBlockWeights::get().max_block; + pub MaximumSchedulerWeight: Weight = + Perbill::from_percent(10) * RuntimeBlockWeights::get().max_block; // No hard limit, used for worst-case weight estimation pub const MaxScheduledPerBlock: u32 = 50; pub const NoPreimagePostponement: Option = Some(5 * BLOCKS_PER_MINUTE); - // System pub const SS58Prefix: u8 = 73; pub const Version: RuntimeVersion = VERSION; - pub RuntimeBlockLength: BlockLength = BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + 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(); + weights.base_extrinsic = ExtrinsicBaseWeight::get(); }) .for_class(DispatchClass::Normal, |weights| { - weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); }) .for_class(DispatchClass::Operational, |weights| { - weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); - weights.reserved = Some( - MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT - ); + weights.max_total = Some(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(); diff --git a/runtime/src/xcm_config.rs b/runtime/battery-station/src/xcm_config.rs similarity index 98% rename from runtime/src/xcm_config.rs rename to runtime/battery-station/src/xcm_config.rs index 830f03f68..6409c2a80 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/battery-station/src/xcm_config.rs @@ -1,4 +1,4 @@ -use crate::{ +use super::{ AccountId, Ancestry, Balance, Balances, Barrier, Call, LocalAssetTransactor, MaxInstructions, PolkadotXcm, RelayLocation, UnitWeightCost, XcmOriginToTransactDispatchOrigin, XcmRouter, }; diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml new file mode 100644 index 000000000..f164c0da0 --- /dev/null +++ b/runtime/common/Cargo.toml @@ -0,0 +1,73 @@ +[dependencies] +# Pallets +cumulus-pallet-xcmp-queue = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } +frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +orml-currencies = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-tokens = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +pallet-author-mapping = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", default-features = false, git = "https://github.com/purestake/moonbeam", optional = true } +pallet-author-slot-filter = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/nimbus", optional = true } +pallet-balances = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-collective = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-democracy = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-identity = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-membership = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-multisig = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-preimage = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-proxy = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-randomness-collective-flip = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-scheduler = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-timestamp = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-transaction-payment = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-transaction-payment-rpc-runtime-api = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-treasury = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-utility = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-vesting = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +parachain-staking = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", default-features = false, git = "https://github.com/purestake/moonbeam", optional = true } + +# Utility +cfg-if = { version = "1.0.0" } + +[features] +default=["std"] +std=[ + "cumulus-pallet-xcmp-queue?/std", + "frame-system/std", + "frame-support/std", + "orml-currencies/std", + "orml-tokens/std", + "pallet-author-mapping?/std", + "pallet-author-slot-filter?/std", + "pallet-balances/std", + "pallet-collective/std", + "pallet-democracy/std", + "pallet-identity/std", + "pallet-membership/std", + "pallet-multisig/std", + "pallet-preimage/std", + "pallet-proxy/std", + "pallet-randomness-collective-flip/std", + "pallet-scheduler/std", + "pallet-timestamp/std", + "pallet-transaction-payment-rpc-runtime-api/std", + "pallet-transaction-payment/std", + "pallet-treasury/std", + "pallet-utility/std", + "pallet-vesting/std", + "parachain-staking?/std", +] +parachain=[ + "cumulus-pallet-xcmp-queue", + "pallet-author-mapping", + "pallet-author-slot-filter", + "parachain-staking", +] + +[package] +authors = ["Zeitgeist PM "] +edition = "2021" +name = "common-runtime" +version = "0.3.4" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs new file mode 100644 index 000000000..b9b2d9767 --- /dev/null +++ b/runtime/common/src/lib.rs @@ -0,0 +1,1660 @@ +#![cfg_attr(not(feature = "std"), no_std)] +#![recursion_limit = "256"] +#![allow(clippy::crate_in_macro_def)] + +pub mod weights; + +#[macro_export] +macro_rules! decl_common_types { + {} => { + use sp_runtime::generic; + + pub type Block = generic::Block; + + type Address = sp_runtime::MultiAddress; + + pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + ( + zrml_court::migrations::JurorsCountedStorageMapMigration, + zrml_prediction_markets::migrations::MigrateMarketPoolsBeforeOpen, + zrml_prediction_markets::migrations::CleanUpStorageForResolvedOrClosedMarkets, + ), + >; + + pub type Header = generic::Header; + pub(crate) type NodeBlock = generic::Block; + type RikiddoSigmoidFeeMarketVolumeEma = zrml_rikiddo::Instance1; + pub type SignedExtra = ( + CheckNonZeroSender, + CheckSpecVersion, + CheckTxVersion, + CheckGenesis, + CheckEra, + CheckNonce, + CheckWeight, + ChargeTransactionPayment, + ); + pub type SignedPayload = generic::SignedPayload; + pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; + + // Governance + type AdvisoryCommitteeInstance = pallet_collective::Instance1; + type AdvisoryCommitteeMembershipInstance = pallet_membership::Instance1; + type CouncilInstance = pallet_collective::Instance2; + type CouncilMembershipInstance = pallet_membership::Instance2; + type TechnicalCommitteeInstance = pallet_collective::Instance3; + type TechnicalCommitteeMembershipInstance = pallet_membership::Instance3; + + // Council vote proportions + // At least 50% + type EnsureRootOrHalfCouncil = + EnsureOneOf, EnsureProportionAtLeast>; + + // At least 66% + type EnsureRootOrTwoThirdsCouncil = + EnsureOneOf, EnsureProportionAtLeast>; + + // At least 75% + type EnsureRootOrThreeFourthsCouncil = + EnsureOneOf, EnsureProportionAtLeast>; + + // At least 100% + type EnsureRootOrAllCouncil = + EnsureOneOf, EnsureProportionAtLeast>; + + // Technical committee vote proportions + // At least 50% + #[cfg(feature = "parachain")] + type EnsureRootOrHalfTechnicalCommittee = EnsureOneOf< + EnsureRoot, + EnsureProportionAtLeast, + >; + + // At least 66% + type EnsureRootOrTwoThirdsTechnicalCommittee = EnsureOneOf< + EnsureRoot, + EnsureProportionAtLeast, + >; + + // At least 100% + type EnsureRootOrAllTechnicalCommittee = EnsureOneOf< + EnsureRoot, + EnsureProportionAtLeast, + >; + + // Advisory committee vote proportions + // At least 50% + type EnsureRootOrHalfAdvisoryCommittee = EnsureOneOf< + EnsureRoot, + EnsureProportionAtLeast, + >; + + // Technical committee vote proportions + // At least 66% + type EnsureRootOrTwoThirdsAdvisoryCommittee = EnsureOneOf< + EnsureRoot, + EnsureProportionAtLeast, + >; + + // At least 100% + type EnsureRootOrAllAdvisoryCommittee = EnsureOneOf< + EnsureRoot, + EnsureProportionAtLeast, + >; + + #[cfg(feature = "std")] + pub fn native_version() -> NativeVersion { + NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } + } + + // Accounts protected from being deleted due to a too low amount of funds. + pub struct DustRemovalWhitelist; + + impl Contains for DustRemovalWhitelist + where + frame_support::PalletId: AccountIdConversion, + { + fn contains(ai: &AccountId) -> bool { + let pallets = vec![ + AuthorizedPalletId::get(), + CourtPalletId::get(), + LiquidityMiningPalletId::get(), + PmPalletId::get(), + SimpleDisputesPalletId::get(), + SwapsPalletId::get(), + ]; + + if let Some(pallet_id) = frame_support::PalletId::try_from_sub_account::(ai) { + return pallets.contains(&pallet_id.0); + } + + for pallet_id in pallets { + let pallet_acc: AccountId = pallet_id.into_account(); + + if pallet_acc == *ai { + return true; + } + } + + false + } + } + + pub mod opaque { + //! 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. + + use super::Header; + use alloc::vec::Vec; + use sp_runtime::{generic, impl_opaque_keys}; + + pub type Block = generic::Block; + + #[cfg(feature = "parachain")] + impl_opaque_keys! { + pub struct SessionKeys { + pub nimbus: crate::AuthorInherent, + } + } + + #[cfg(not(feature = "parachain"))] + impl_opaque_keys! { + pub struct SessionKeys { + pub aura: crate::Aura, + pub grandpa: crate::Grandpa, + } + } + } + } +} + +// Construct runtime +#[macro_export] +macro_rules! create_runtime { + ($($additional_pallets:tt)*) => { + use alloc::{boxed::Box, vec::Vec}; + // Pallets are enumerated based on the dependency graph. + // + // For example, `PredictionMarkets` is pĺaced after `SimpleDisputes` because + // `PredictionMarkets` depends on `SimpleDisputes`. + + construct_runtime!( + pub enum Runtime where + Block = crate::Block, + NodeBlock = crate::NodeBlock, + UncheckedExtrinsic = crate::UncheckedExtrinsic, + { + // System + System: frame_system::{Call, Config, Event, Pallet, Storage} = 0, + Timestamp: pallet_timestamp::{Call, Pallet, Storage, Inherent} = 1, + RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 2, + Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 3, + Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 4, + + // Money + Balances: pallet_balances::{Call, Config, Event, Pallet, Storage} = 10, + TransactionPayment: pallet_transaction_payment::{Config, Pallet, Storage} = 11, + Treasury: pallet_treasury::{Call, Config, Event, Pallet, Storage} = 12, + Vesting: pallet_vesting::{Call, Config, Event, Pallet, Storage} = 13, + MultiSig: pallet_multisig::{Call, Event, Pallet, Storage} = 14, + + // Governance + Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 20, + AdvisoryCommittee: pallet_collective::::{Call, Config, Event, Origin, Pallet, Storage} = 21, + AdvisoryCommitteeMembership: pallet_membership::::{Call, Config, Event, Pallet, Storage} = 22, + Council: pallet_collective::::{Call, Config, Event, Origin, Pallet, Storage} = 23, + CouncilMembership: pallet_membership::::{Call, Config, Event, Pallet, Storage} = 24, + TechnicalCommittee: pallet_collective::::{Call, Config, Event, Origin, Pallet, Storage} = 25, + TechnicalCommitteeMembership: pallet_membership::::{Call, Config, Event, Pallet, Storage} = 26, + + // Other Parity pallets + Identity: pallet_identity::{Call, Event, Pallet, Storage} = 30, + Utility: pallet_utility::{Call, Event, Pallet, Storage} = 31, + Proxy: pallet_proxy::{Call, Event, Pallet, Storage} = 32, + + // Third-party + AssetManager: orml_currencies::{Call, Pallet, Storage} = 40, + Tokens: orml_tokens::{Config, Event, Pallet, Storage} = 41, + + // Zeitgeist + MarketCommons: zrml_market_commons::{Pallet, Storage} = 50, + Authorized: zrml_authorized::{Call, Event, Pallet, Storage} = 51, + Court: zrml_court::{Call, Event, Pallet, Storage} = 52, + LiquidityMining: zrml_liquidity_mining::{Call, Config, Event, Pallet, Storage} = 53, + RikiddoSigmoidFeeMarketEma: zrml_rikiddo::::{Pallet, Storage} = 54, + SimpleDisputes: zrml_simple_disputes::{Event, Pallet, Storage} = 55, + Swaps: zrml_swaps::{Call, Event, Pallet, Storage} = 56, + PredictionMarkets: zrml_prediction_markets::{Call, Event, Pallet, Storage} = 57, + Styx: zrml_styx::{Call, Event, Pallet, Storage} = 58, + + $($additional_pallets)* + } + ); + } +} + +#[macro_export] +macro_rules! create_runtime_with_additional_pallets { + ($($additional_pallets:tt)*) => { + #[cfg(feature = "parachain")] + create_runtime!( + // System + ParachainSystem: cumulus_pallet_parachain_system::{Call, Config, Event, Inherent, Pallet, Storage, ValidateUnsigned} = 100, + ParachainInfo: parachain_info::{Config, Pallet, Storage} = 101, + + // Consensus + ParachainStaking: parachain_staking::{Call, Config, Event, Pallet, Storage} = 110, + AuthorInherent: pallet_author_inherent::{Call, Inherent, Pallet, Storage} = 111, + AuthorFilter: pallet_author_slot_filter::{Call, Config, Event, Pallet, Storage} = 112, + AuthorMapping: pallet_author_mapping::{Call, Config, Event, Pallet, Storage} = 113, + + // XCM + CumulusXcm: cumulus_pallet_xcm::{Event, Origin, Pallet} = 120, + DmpQueue: cumulus_pallet_dmp_queue::{Call, Event, Pallet, Storage} = 121, + PolkadotXcm: pallet_xcm::{Call, Config, Event, Origin, Pallet, Storage} = 122, + XcmpQueue: cumulus_pallet_xcmp_queue::{Call, Event, Pallet, Storage} = 123, + + // Third-party + Crowdloan: pallet_crowdloan_rewards::{Call, Config, Event, Pallet, Storage} = 130, + + // Others + $($additional_pallets)* + ); + + #[cfg(not(feature = "parachain"))] + create_runtime!( + // Consensus + Aura: pallet_aura::{Config, Pallet, Storage} = 100, + Grandpa: pallet_grandpa::{Call, Config, Event, Pallet, Storage} = 101, + + // Others + $($additional_pallets)* + ); + } +} + +#[macro_export] +macro_rules! impl_config_traits { + {} => { + use common_runtime::weights; + + // Configure Pallets + #[cfg(feature = "parachain")] + impl cumulus_pallet_dmp_queue::Config for Runtime { + type Event = Event; + type ExecuteOverweightOrigin = EnsureRootOrHalfTechnicalCommittee; + type XcmExecutor = xcm_executor::XcmExecutor; + } + + #[cfg(feature = "parachain")] + impl cumulus_pallet_parachain_system::Config for Runtime { + type DmpMessageHandler = DmpQueue; + type Event = Event; + type OnSystemEvent = (); + type OutboundXcmpMessageSource = XcmpQueue; + type ReservedDmpWeight = crate::parachain_params::ReservedDmpWeight; + type ReservedXcmpWeight = crate::parachain_params::ReservedXcmpWeight; + type SelfParaId = parachain_info::Pallet; + type XcmpMessageHandler = XcmpQueue; + } + + #[cfg(feature = "parachain")] + impl cumulus_pallet_xcm::Config for Runtime { + type Event = Event; + type XcmExecutor = xcm_executor::XcmExecutor; + } + + #[cfg(feature = "parachain")] + impl cumulus_pallet_xcmp_queue::Config for Runtime { + type ChannelInfo = ParachainSystem; + type ControllerOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; + type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; + type Event = Event; + type ExecuteOverweightOrigin = EnsureRootOrHalfTechnicalCommittee; + type VersionWrapper = (); + type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; + type XcmExecutor = xcm_executor::XcmExecutor; + } + + impl frame_system::Config for Runtime { + type AccountData = pallet_balances::AccountData; + type AccountId = AccountId; + type BaseCallFilter = IsCallable; + type BlockHashCount = BlockHashCount; + type BlockLength = RuntimeBlockLength; + type BlockNumber = BlockNumber; + type BlockWeights = RuntimeBlockWeights; + type Call = Call; + type DbWeight = RocksDbWeight; + type Event = Event; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Header = generic::Header; + type Index = Index; + type Lookup = AccountIdLookup; + type MaxConsumers = ConstU32<16>; + type OnKilledAccount = (); + type OnNewAccount = (); + #[cfg(feature = "parachain")] + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + #[cfg(not(feature = "parachain"))] + type OnSetCode = (); + type Origin = Origin; + type PalletInfo = PalletInfo; + type SS58Prefix = SS58Prefix; + type SystemWeightInfo = weights::frame_system::WeightInfo; + type Version = Version; + } + + #[cfg(not(feature = "parachain"))] + impl pallet_aura::Config for Runtime { + type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; + type DisabledValidators = (); + type MaxAuthorities = MaxAuthorities; + } + + #[cfg(feature = "parachain")] + impl pallet_author_inherent::Config for Runtime { + type AccountLookup = AuthorMapping; + type CanAuthor = AuthorFilter; + type EventHandler = ParachainStaking; + type SlotBeacon = cumulus_pallet_parachain_system::RelaychainBlockNumberProvider; + } + + #[cfg(feature = "parachain")] + impl pallet_author_mapping::Config for Runtime { + type DepositAmount = CollatorDeposit; + type DepositCurrency = Balances; + type Event = Event; + type WeightInfo = weights::pallet_author_mapping::WeightInfo; + } + + #[cfg(feature = "parachain")] + impl pallet_author_slot_filter::Config for Runtime { + type Event = Event; + type RandomnessSource = RandomnessCollectiveFlip; + type PotentialAuthors = ParachainStaking; + type WeightInfo = weights::pallet_author_slot_filter::WeightInfo; + } + + #[cfg(not(feature = "parachain"))] + impl pallet_grandpa::Config for Runtime { + type Event = Event; + type Call = Call; + type KeyOwnerProofSystem = (); + type KeyOwnerProof = + >::Proof; + type KeyOwnerIdentification = + >::IdentificationTuple; + type HandleEquivocation = (); + type MaxAuthorities = MaxAuthorities; + // Currently the benchmark does yield an invalid weight implementation + // type WeightInfo = weights::pallet_grandpa::WeightInfo; + type WeightInfo = (); + } + + #[cfg(feature = "parachain")] + impl pallet_xcm::Config for Runtime { + type Event = Event; + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = EnsureXcmOrigin; + type XcmExecuteFilter = Nothing; + // ^ Disable dispatchable execute on the XCM pallet. + // Needs to be `Everything` for local testing. + type XcmExecutor = xcm_executor::XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Nothing; + type Weigher = FixedWeightBounds; + type LocationInverter = LocationInverter; + type Origin = Origin; + type Call = Call; + + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + // ^ Override for AdvertisedXcmVersion default + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + } + + #[cfg(feature = "parachain")] + impl parachain_staking::Config for Runtime { + type CandidateBondLessDelay = CandidateBondLessDelay; + type Currency = Balances; + type DefaultBlocksPerRound = DefaultBlocksPerRound; + type DefaultCollatorCommission = DefaultCollatorCommission; + type DefaultParachainBondReservePercent = DefaultParachainBondReservePercent; + type DelegationBondLessDelay = DelegationBondLessDelay; + type Event = Event; + type LeaveCandidatesDelay = LeaveCandidatesDelay; + type LeaveDelegatorsDelay = LeaveDelegatorsDelay; + type MaxBottomDelegationsPerCandidate = MaxBottomDelegationsPerCandidate; + type MaxTopDelegationsPerCandidate = MaxTopDelegationsPerCandidate; + type MaxDelegationsPerDelegator = MaxDelegationsPerDelegator; + type MinBlocksPerRound = MinBlocksPerRound; + type MinCandidateStk = MinCollatorStk; + type MinCollatorStk = MinCollatorStk; + type MinDelegation = MinDelegatorStk; + type MinDelegatorStk = MinDelegatorStk; + type MinSelectedCandidates = MinSelectedCandidates; + type MonetaryGovernanceOrigin = EnsureRoot; + type RevokeDelegationDelay = RevokeDelegationDelay; + type RewardPaymentDelay = RewardPaymentDelay; + type WeightInfo = weights::parachain_staking::WeightInfo; + } + + impl orml_currencies::Config for Runtime { + type GetNativeCurrencyId = GetNativeCurrencyId; + type MultiCurrency = Tokens; + type NativeCurrency = BasicCurrencyAdapter; + type WeightInfo = weights::orml_currencies::WeightInfo; + } + + impl orml_tokens::Config for Runtime { + type Amount = Amount; + type Balance = Balance; + type CurrencyId = CurrencyId; + type DustRemovalWhitelist = DustRemovalWhitelist; + type Event = Event; + type ExistentialDeposits = ExistentialDeposits; + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; + type OnDust = orml_tokens::TransferDust; + type ReserveIdentifier = [u8; 8]; + type WeightInfo = weights::orml_tokens::WeightInfo; + type OnNewTokenAccount = (); + type OnKilledTokenAccount = (); + } + + #[cfg(feature = "parachain")] + impl pallet_crowdloan_rewards::Config for Runtime { + type Event = Event; + type InitializationPayment = InitializationPayment; + type Initialized = Initialized; + type MaxInitContributors = MaxInitContributorsBatchSizes; + type MinimumReward = MinimumReward; + type RelayChainAccountId = AccountId; + type RewardCurrency = Balances; + type RewardAddressAssociateOrigin = EnsureSigned; + type RewardAddressChangeOrigin = frame_system::EnsureSigned; + type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold; + type SignatureNetworkIdentifier = SignatureNetworkIdentifier; + type VestingBlockNumber = cumulus_primitives_core::relay_chain::BlockNumber; + type VestingBlockProvider = + cumulus_pallet_parachain_system::RelaychainBlockNumberProvider; + type WeightInfo = pallet_crowdloan_rewards::weights::SubstrateWeight; + } + + impl pallet_balances::Config for Runtime { + type AccountStore = System; + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = ExistentialDeposit; + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type WeightInfo = pallet_balances::weights::SubstrateWeight; // weights::pallet_balances::WeightInfo; + } + + impl pallet_collective::Config for Runtime { + type DefaultVote = PrimeDefaultVote; + type Event = Event; + type MaxMembers = AdvisoryCommitteeMaxMembers; + type MaxProposals = AdvisoryCommitteeMaxProposals; + type MotionDuration = AdvisoryCommitteeMotionDuration; + type Origin = Origin; + type Proposal = Call; + type WeightInfo = weights::pallet_collective::WeightInfo; + } + + impl pallet_collective::Config for Runtime { + type DefaultVote = PrimeDefaultVote; + type Event = Event; + type MaxMembers = CouncilMaxMembers; + type MaxProposals = CouncilMaxProposals; + type MotionDuration = CouncilMotionDuration; + type Origin = Origin; + type Proposal = Call; + type WeightInfo = weights::pallet_collective::WeightInfo; + } + + impl pallet_collective::Config for Runtime { + type DefaultVote = PrimeDefaultVote; + type Event = Event; + type MaxMembers = TechnicalCommitteeMaxMembers; + type MaxProposals = TechnicalCommitteeMaxProposals; + type MotionDuration = TechnicalCommitteeMotionDuration; + type Origin = Origin; + type Proposal = Call; + type WeightInfo = weights::pallet_collective::WeightInfo; + } + + impl pallet_democracy::Config for Runtime { + type Proposal = Call; + type Event = Event; + type Currency = Balances; + type EnactmentPeriod = EnactmentPeriod; + type LaunchPeriod = LaunchPeriod; + type VotingPeriod = VotingPeriod; + type VoteLockingPeriod = VoteLockingPeriod; + type MinimumDeposit = MinimumDeposit; + /// Origin that can decide what their next motion is. + type ExternalOrigin = EnsureRootOrHalfCouncil; + /// Origin that can have the next scheduled referendum be a straight majority-carries vote. + type ExternalMajorityOrigin = EnsureRootOrHalfCouncil; + /// Origina that can have the next scheduled referendum be a straight default-carries + /// (NTB) vote. + type ExternalDefaultOrigin = EnsureRootOrAllCouncil; + /// Origin that can have an ExternalMajority/ExternalDefault vote + /// be tabled immediately and with a shorter voting/enactment period. + type FastTrackOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; + /// Origin from which the next majority-carries (or more permissive) referendum may be tabled + /// to vote immediately and asynchronously in a similar manner to the emergency origin. + type InstantOrigin = EnsureRootOrAllTechnicalCommittee; + type InstantAllowed = InstantAllowed; + type FastTrackVotingPeriod = FastTrackVotingPeriod; + /// Origin from which any referendum may be cancelled in an emergency. + type CancellationOrigin = EnsureRootOrThreeFourthsCouncil; + /// Origin from which proposals may be blacklisted. + type BlacklistOrigin = EnsureRootOrAllCouncil; + /// Origin from which a proposal may be cancelled and its backers slashed. + type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee; + /// Origin for anyone able to veto proposals. + type VetoOrigin = pallet_collective::EnsureMember; + type CooloffPeriod = CooloffPeriod; + type PreimageByteDeposit = PreimageByteDeposit; + type OperationalPreimageOrigin = pallet_collective::EnsureMember; + type Slash = Treasury; + type Scheduler = Scheduler; + type PalletsOrigin = OriginCaller; + type MaxVotes = MaxVotes; + type WeightInfo = weights::pallet_democracy::WeightInfo; + type MaxProposals = MaxProposals; + } + + impl pallet_identity::Config for Runtime { + type BasicDeposit = BasicDeposit; + type Currency = Balances; + type Event = Event; + type FieldDeposit = FieldDeposit; + type ForceOrigin = EnsureRootOrTwoThirdsAdvisoryCommittee; + type MaxAdditionalFields = MaxAdditionalFields; + type MaxRegistrars = MaxRegistrars; + type MaxSubAccounts = MaxSubAccounts; + type RegistrarOrigin = EnsureRootOrHalfCouncil; + type Slashed = Treasury; + type SubAccountDeposit = SubAccountDeposit; + type WeightInfo = weights::pallet_identity::WeightInfo; + } + + impl pallet_membership::Config for Runtime { + type AddOrigin = EnsureRootOrTwoThirdsCouncil; + type Event = Event; + type MaxMembers = AdvisoryCommitteeMaxMembers; + type MembershipChanged = AdvisoryCommittee; + type MembershipInitialized = AdvisoryCommittee; + type PrimeOrigin = EnsureRootOrTwoThirdsCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsCouncil; + type WeightInfo = weights::pallet_membership::WeightInfo; + } + + impl pallet_membership::Config for Runtime { + type AddOrigin = EnsureRootOrThreeFourthsCouncil; + type Event = Event; + type MaxMembers = CouncilMaxMembers; + type MembershipChanged = Council; + type MembershipInitialized = Council; + type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; + type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; + type ResetOrigin = EnsureRootOrThreeFourthsCouncil; + type SwapOrigin = EnsureRootOrThreeFourthsCouncil; + type WeightInfo = weights::pallet_membership::WeightInfo; + } + + impl pallet_membership::Config for Runtime { + type AddOrigin = EnsureRootOrTwoThirdsCouncil; + type Event = Event; + type MaxMembers = TechnicalCommitteeMaxMembers; + type MembershipChanged = TechnicalCommittee; + type MembershipInitialized = TechnicalCommittee; + type PrimeOrigin = EnsureRootOrTwoThirdsCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsCouncil; + type WeightInfo = weights::pallet_membership::WeightInfo; + } + + impl pallet_multisig::Config for Runtime { + type Event = Event; + type Call = Call; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = ConstU16<100>; + type WeightInfo = weights::pallet_multisig::WeightInfo; + } + + impl pallet_preimage::Config for Runtime { + type WeightInfo = weights::pallet_preimage::WeightInfo; + type Event = Event; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type MaxSize = PreimageMaxSize; + type BaseDeposit = PreimageBaseDeposit; + type ByteDeposit = PreimageByteDeposit; + } + + impl InstanceFilter for ProxyType { + fn filter(&self, c: &Call) -> bool { + match self { + ProxyType::Any => true, + ProxyType::CancelProxy => { + matches!(c, Call::Proxy(pallet_proxy::Call::reject_announcement { .. })) + } + ProxyType::Governance => matches!( + c, + Call::Democracy(..) + | Call::Council(..) + | Call::TechnicalCommittee(..) + | Call::AdvisoryCommittee(..) + | Call::Treasury(..) + ), + #[cfg(feature = "parachain")] + ProxyType::Staking => matches!(c, Call::ParachainStaking(..)), + #[cfg(not(feature = "parachain"))] + ProxyType::Staking => false, + } + } + + fn is_superset(&self, o: &Self) -> bool { + match (self, o) { + (x, y) if x == y => true, + (ProxyType::Any, _) => true, + (_, ProxyType::Any) => false, + _ => false, + } + } + } + + impl pallet_proxy::Config for Runtime { + type Event = Event; + type Call = Call; + type Currency = Balances; + type ProxyType = ProxyType; + type ProxyDepositBase = ProxyDepositBase; + type ProxyDepositFactor = ProxyDepositFactor; + type MaxProxies = ConstU32<32>; + type WeightInfo = weights::pallet_proxy::WeightInfo; + type MaxPending = ConstU32<32>; + type CallHasher = BlakeTwo256; + type AnnouncementDepositBase = AnnouncementDepositBase; + type AnnouncementDepositFactor = AnnouncementDepositFactor; + } + + impl pallet_randomness_collective_flip::Config for Runtime {} + + impl pallet_scheduler::Config for Runtime { + type Event = Event; + type Origin = Origin; + type PalletsOrigin = OriginCaller; + type Call = Call; + type MaximumWeight = MaximumSchedulerWeight; + type ScheduleOrigin = EnsureRoot; + type MaxScheduledPerBlock = MaxScheduledPerBlock; + type WeightInfo = weights::pallet_scheduler::WeightInfo; + type OriginPrivilegeCmp = EqualPrivilegeOnly; + type PreimageProvider = Preimage; + type NoPreimagePostponement = NoPreimagePostponement; + } + + impl pallet_timestamp::Config for Runtime { + type MinimumPeriod = MinimumPeriod; + type Moment = u64; + #[cfg(feature = "parachain")] + type OnTimestampSet = (); + #[cfg(not(feature = "parachain"))] + type OnTimestampSet = Aura; + type WeightInfo = weights::pallet_timestamp::WeightInfo; + } + + impl pallet_transaction_payment::Config for Runtime { + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; + type LengthToFee = ConstantMultiplier; + type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; + type OperationalFeeMultiplier = OperationalFeeMultiplier; + type WeightToFee = IdentityFee; + } + + impl pallet_treasury::Config for Runtime { + type ApproveOrigin = EnsureRootOrTwoThirdsCouncil; + type Burn = Burn; + type BurnDestination = (); + type Currency = Balances; + type Event = Event; + type MaxApprovals = MaxApprovals; + type OnSlash = (); + type PalletId = TreasuryPalletId; + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ProposalBondMinimum; + type ProposalBondMaximum = ProposalBondMaximum; + type RejectOrigin = EnsureRootOrTwoThirdsCouncil; + type SpendFunds = (); + type SpendPeriod = SpendPeriod; + type WeightInfo = weights::pallet_treasury::WeightInfo; + } + + impl pallet_utility::Config for Runtime { + type Event = Event; + type Call = Call; + type PalletsOrigin = OriginCaller; + type WeightInfo = weights::pallet_utility::WeightInfo; + } + + impl pallet_vesting::Config for Runtime { + type Event = Event; + type Currency = Balances; + type BlockNumberToBalance = sp_runtime::traits::ConvertInto; + type MinVestedTransfer = MinVestedTransfer; + type WeightInfo = pallet_vesting::weights::SubstrateWeight; // weights::pallet_vesting::WeightInfo; + + // `VestingInfo` encode length is 36bytes. 28 schedules gets encoded as 1009 bytes, which is the + // highest number of schedules that encodes less than 2^10. + const MAX_VESTING_SCHEDULES: u32 = 28; + } + + #[cfg(feature = "parachain")] + impl parachain_info::Config for Runtime {} + + impl zrml_authorized::Config for Runtime { + type Event = Event; + type MarketCommons = MarketCommons; + type PalletId = AuthorizedPalletId; + type WeightInfo = zrml_authorized::weights::WeightInfo; + } + + impl zrml_court::Config for Runtime { + type CourtCaseDuration = CourtCaseDuration; + type Event = Event; + type MarketCommons = MarketCommons; + type PalletId = CourtPalletId; + type Random = RandomnessCollectiveFlip; + type StakeWeight = StakeWeight; + type TreasuryPalletId = TreasuryPalletId; + type WeightInfo = zrml_court::weights::WeightInfo; + } + + impl zrml_liquidity_mining::Config for Runtime { + type Event = Event; + type MarketCommons = MarketCommons; + type MarketId = MarketId; + type PalletId = LiquidityMiningPalletId; + type WeightInfo = zrml_liquidity_mining::weights::WeightInfo; + } + + impl zrml_market_commons::Config for Runtime { + type Currency = Balances; + type MarketId = MarketId; + type Timestamp = Timestamp; + } + + // NoopLiquidityMining implements LiquidityMiningPalletApi with no-ops. + // Has to be public because it will be exposed by Runtime. + pub struct NoopLiquidityMining; + + impl zrml_liquidity_mining::LiquidityMiningPalletApi for NoopLiquidityMining { + type AccountId = AccountId; + type Balance = Balance; + type BlockNumber = BlockNumber; + type MarketId = MarketId; + + fn add_shares(_: Self::AccountId, _: Self::MarketId, _: Self::Balance) {} + + fn distribute_market_incentives( + _: &Self::MarketId, + ) -> frame_support::pallet_prelude::DispatchResult { + Ok(()) + } + + fn remove_shares(_: &Self::AccountId, _: &Self::MarketId, _: Self::Balance) {} + } + + impl zrml_prediction_markets::Config for Runtime { + type AdvisoryBond = AdvisoryBond; + type ApprovalOrigin = EnsureRootOrHalfAdvisoryCommittee; + type Authorized = Authorized; + type Court = Court; + type CloseOrigin = EnsureRootOrTwoThirdsAdvisoryCommittee; + type DestroyOrigin = EnsureRootOrAllAdvisoryCommittee; + type DisputeBond = DisputeBond; + type DisputeFactor = DisputeFactor; + type DisputePeriod = DisputePeriod; + type Event = Event; + // LiquidityMining is currently unstable. + // NoopLiquidityMining will be applied only to mainnet once runtimes are separated. + type LiquidityMining = NoopLiquidityMining; + // type LiquidityMining = LiquidityMining; + type MarketCommons = MarketCommons; + type MaxCategories = MaxCategories; + type MaxDisputes = MaxDisputes; + type MaxSubsidyPeriod = MaxSubsidyPeriod; + type MaxMarketPeriod = MaxMarketPeriod; + type MinCategories = MinCategories; + type MinSubsidyPeriod = MinSubsidyPeriod; + type OracleBond = OracleBond; + type PalletId = PmPalletId; + type ReportingPeriod = ReportingPeriod; + type ResolveOrigin = EnsureRoot; + type AssetManager = AssetManager; + type SimpleDisputes = SimpleDisputes; + type Swaps = Swaps; + type ValidityBond = ValidityBond; + type WeightInfo = zrml_prediction_markets::weights::WeightInfo; + } + + impl zrml_rikiddo::Config for Runtime { + type Timestamp = Timestamp; + type Balance = Balance; + type FixedTypeU = FixedU128; + type FixedTypeS = FixedI128; + type BalanceFractionalDecimals = BalanceFractionalDecimals; + type PoolId = PoolId; + type Rikiddo = RikiddoSigmoidMV< + Self::FixedTypeU, + Self::FixedTypeS, + FeeSigmoid, + EmaMarketVolume, + >; + } + + impl zrml_simple_disputes::Config for Runtime { + type Event = Event; + type MarketCommons = MarketCommons; + type PalletId = SimpleDisputesPalletId; + } + + impl zrml_swaps::Config for Runtime { + type Event = Event; + type ExitFee = ExitFee; + type FixedTypeU = FixedU128; + type FixedTypeS = FixedI128; + // LiquidityMining is currently unstable. + // NoopLiquidityMining will be applied only to mainnet once runtimes are separated. + type LiquidityMining = NoopLiquidityMining; + // type LiquidityMining = LiquidityMining; + type MarketCommons = MarketCommons; + type MarketId = MarketId; + type MinAssets = MinAssets; + type MaxAssets = MaxAssets; + type MaxInRatio = MaxInRatio; + type MaxOutRatio = MaxOutRatio; + type MaxSwapFee = MaxSwapFee; + type MaxTotalWeight = MaxTotalWeight; + type MaxWeight = MaxWeight; + type MinLiquidity = MinLiquidity; + type MinSubsidy = MinSubsidy; + type MinSubsidyPerAccount = MinSubsidyPerAccount; + type MinWeight = MinWeight; + type PalletId = SwapsPalletId; + type RikiddoSigmoidFeeMarketEma = RikiddoSigmoidFeeMarketEma; + type AssetManager = AssetManager; + type WeightInfo = zrml_swaps::weights::WeightInfo; + } + + impl zrml_styx::Config for Runtime { + type Event = Event; + type SetBurnAmountOrigin = EnsureRootOrHalfCouncil; + type Currency = Balances; + type WeightInfo = zrml_styx::weights::WeightInfo; + } + } +} + +// Implement runtime apis +#[macro_export] +macro_rules! create_runtime_api { + ($($additional_apis:tt)*) => { + impl_runtime_apis! { + #[cfg(feature = "parachain")] + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info( + header: &::Header + ) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "parachain")] + // Required to satisify trait bounds at the client implementation. + impl nimbus_primitives::AuthorFilterAPI for Runtime { + fn can_author(_: NimbusId, _: u32, _: &::Header) -> bool { + panic!("AuthorFilterAPI is no longer supported. Please update your client.") + } + } + + #[cfg(feature = "parachain")] + impl nimbus_primitives::NimbusApi for Runtime { + fn can_author( + author: nimbus_primitives::NimbusId, + slot: u32, + parent_header: &::Header + ) -> bool { + + // Ensure that an update is enforced when we are close to maximum block number + let block_number = if let Some(bn) = parent_header.number.checked_add(1) { + bn + } else { + log::error!("ERROR: No block numbers left"); + return false; + }; + + use frame_support::traits::OnInitialize; + System::initialize( + &block_number, + &parent_header.hash(), + &parent_header.digest, + ); + RandomnessCollectiveFlip::on_initialize(block_number); + + // Because the staking solution calculates the next staking set at the beginning + // of the first block in the new round, the only way to accurately predict the + // authors is to compute the selection during prediction. + if parachain_staking::Pallet::::round().should_update(block_number) { + // get author account id + use nimbus_primitives::AccountLookup; + let author_account_id = if let Some(account) = + pallet_author_mapping::Pallet::::lookup_account(&author) { + account + } else { + // return false if author mapping not registered like in can_author impl + return false + }; + // predict eligibility post-selection by computing selection results now + let (eligible, _) = + pallet_author_slot_filter::compute_pseudo_random_subset::( + parachain_staking::Pallet::::compute_top_candidates(), + &slot + ); + eligible.contains(&author_account_id) + } else { + AuthorInherent::can_author(&author, &slot) + } + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{list_benchmark, baseline::Pallet as BaselineBench, Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use orml_benchmarking::list_benchmark as orml_list_benchmark; + + let mut list = Vec::::new(); + + list_benchmark!(list, extra, frame_benchmarking, BaselineBench::); + list_benchmark!(list, extra, frame_system, SystemBench::); + orml_list_benchmark!(list, extra, orml_currencies, crate::benchmarks::currencies); + orml_list_benchmark!(list, extra, orml_tokens, crate::benchmarks::tokens); + list_benchmark!(list, extra, pallet_balances, Balances); + list_benchmark!(list, extra, pallet_collective, AdvisoryCommittee); + list_benchmark!(list, extra, pallet_democracy, Democracy); + list_benchmark!(list, extra, pallet_identity, Identity); + list_benchmark!(list, extra, pallet_membership, AdvisoryCommitteeMembership); + list_benchmark!(list, extra, pallet_multisig, MultiSig); + list_benchmark!(list, extra, pallet_preimage, Preimage); + list_benchmark!(list, extra, pallet_proxy, Proxy); + list_benchmark!(list, extra, pallet_scheduler, Scheduler); + list_benchmark!(list, extra, pallet_timestamp, Timestamp); + list_benchmark!(list, extra, pallet_treasury, Treasury); + list_benchmark!(list, extra, pallet_utility, Utility); + list_benchmark!(list, extra, pallet_vesting, Vesting); + list_benchmark!(list, extra, zrml_swaps, Swaps); + list_benchmark!(list, extra, zrml_authorized, Authorized); + list_benchmark!(list, extra, zrml_court, Court); + list_benchmark!(list, extra, zrml_prediction_markets, PredictionMarkets); + list_benchmark!(list, extra, zrml_liquidity_mining, LiquidityMining); + list_benchmark!(list, extra, zrml_styx, Styx); + + cfg_if::cfg_if! { + if #[cfg(feature = "parachain")] { + list_benchmark!(list, extra, cumulus_pallet_xcmp_queue, XcmpQueue); + list_benchmark!(list, extra, pallet_author_mapping, AuthorMapping); + list_benchmark!(list, extra, pallet_author_slot_filter, AuthorFilter); + list_benchmark!(list, extra, parachain_staking, ParachainStaking); + list_benchmark!(list, extra, pallet_crowdloan_rewards, Crowdloan); + } else { + list_benchmark!(list, extra, pallet_grandpa, Grandpa); + } + } + + (list, AllPalletsWithSystem::storage_info()) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig, + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{ + add_benchmark, baseline::{Pallet as BaselineBench, Config as BaselineConfig}, vec, BenchmarkBatch, Benchmarking, TrackedStorageKey, Vec + }; + use frame_system_benchmarking::Pallet as SystemBench; + use orml_benchmarking::{add_benchmark as orml_add_benchmark}; + + impl frame_system_benchmarking::Config for Runtime {} + impl BaselineConfig for Runtime {} + + let whitelist: Vec = vec![ + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac") + .to_vec() + .into(), + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80") + .to_vec() + .into(), + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a") + .to_vec() + .into(), + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850") + .to_vec() + .into(), + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7") + .to_vec() + .into(), + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da946c154ffd9992e395af90b5b13cc6f295c77033fce8a9045824a6690bbf99c6db269502f0a8d1d2a008542d5690a0749").to_vec().into(), + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + + add_benchmark!(params, batches, frame_benchmarking, BaselineBench::); + add_benchmark!(params, batches, frame_system, SystemBench::); + orml_add_benchmark!(params, batches, orml_currencies, crate::benchmarks::currencies); + orml_add_benchmark!(params, batches, orml_tokens, crate::benchmarks::tokens); + add_benchmark!(params, batches, pallet_balances, Balances); + add_benchmark!(params, batches, pallet_collective, AdvisoryCommittee); + add_benchmark!(params, batches, pallet_democracy, Democracy); + add_benchmark!(params, batches, pallet_identity, Identity); + add_benchmark!(params, batches, pallet_membership, AdvisoryCommitteeMembership); + add_benchmark!(params, batches, pallet_multisig, MultiSig); + add_benchmark!(params, batches, pallet_preimage, Preimage); + add_benchmark!(params, batches, pallet_proxy, Proxy); + add_benchmark!(params, batches, pallet_scheduler, Scheduler); + add_benchmark!(params, batches, pallet_timestamp, Timestamp); + add_benchmark!(params, batches, pallet_treasury, Treasury); + add_benchmark!(params, batches, pallet_utility, Utility); + add_benchmark!(params, batches, pallet_vesting, Vesting); + add_benchmark!(params, batches, zrml_swaps, Swaps); + add_benchmark!(params, batches, zrml_authorized, Authorized); + add_benchmark!(params, batches, zrml_court, Court); + add_benchmark!(params, batches, zrml_prediction_markets, PredictionMarkets); + add_benchmark!(params, batches, zrml_liquidity_mining, LiquidityMining); + add_benchmark!(params, batches, zrml_styx, Styx); + + + cfg_if::cfg_if! { + if #[cfg(feature = "parachain")] { + add_benchmark!(params, batches, cumulus_pallet_xcmp_queue, XcmpQueue); + add_benchmark!(params, batches, pallet_author_mapping, AuthorMapping); + add_benchmark!(params, batches, pallet_author_slot_filter, AuthorFilter); + add_benchmark!(params, batches, parachain_staking, ParachainStaking); + add_benchmark!(params, batches, pallet_crowdloan_rewards, Crowdloan); + } else { + add_benchmark!(params, batches, pallet_grandpa, Grandpa); + } + } + + if batches.is_empty() { + return Err("Benchmark not found for this pallet.".into()); + } + Ok(batches) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Index { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + } + + impl sp_api::Core for Runtime { + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + + fn version() -> RuntimeVersion { + VERSION + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + } + + #[cfg(not(feature = "parachain"))] + impl sp_consensus_aura::AuraApi for Runtime { + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + } + + #[cfg(not(feature = "parachain"))] + impl sp_finality_grandpa::GrandpaApi for Runtime { + fn current_set_id() -> pallet_grandpa::fg_primitives::SetId { + Grandpa::current_set_id() + } + + fn generate_key_ownership_proof( + _set_id: pallet_grandpa::fg_primitives::SetId, + _authority_id: pallet_grandpa::AuthorityId, + ) -> Option { + None + } + + fn grandpa_authorities() -> pallet_grandpa::AuthorityList { + Grandpa::grandpa_authorities() + } + + fn submit_report_equivocation_unsigned_extrinsic( + _equivocation_proof: pallet_grandpa::fg_primitives::EquivocationProof< + ::Hash, + sp_runtime::traits::NumberFor, + >, + _key_owner_proof: pallet_grandpa::fg_primitives::OpaqueKeyOwnershipProof, + ) -> Option<()> { + None + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn decode_session_keys(encoded: Vec) -> Option, KeyTypeId)>> { + opaque::SessionKeys::decode_into_raw_public_keys(&encoded) + } + + fn generate_session_keys(seed: Option>) -> Vec { + opaque::SessionKeys::generate(seed) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl zrml_swaps_runtime_api::SwapsApi + for Runtime + { + fn get_spot_price( + pool_id: PoolId, + asset_in: Asset, + asset_out: Asset, + ) -> SerdeWrapper { + SerdeWrapper(Swaps::get_spot_price(pool_id, asset_in, asset_out).ok().unwrap_or(0)) + } + + fn pool_account_id(pool_id: PoolId) -> AccountId { + Swaps::pool_account_id(pool_id) + } + + fn pool_shares_id(pool_id: PoolId) -> Asset> { + Asset::PoolShare(SerdeWrapper(pool_id)) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade() -> (frame_support::weights::Weight, frame_support::weights::Weight) { + log::info!("try-runtime::on_runtime_upgrade."); + let weight = Executive::try_runtime_upgrade().unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block_no_check(block: Block) -> frame_support::weights::Weight { + Executive::execute_block_no_check(block) + } + } + + $($additional_apis)* + } + + // Check the timestamp and parachain inherents + #[cfg(feature = "parachain")] + struct CheckInherents; + + #[cfg(feature = "parachain")] + impl cumulus_pallet_parachain_system::CheckInherents for CheckInherents { + fn check_inherents( + block: &Block, + relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof, + ) -> sp_inherents::CheckInherentsResult { + let relay_chain_slot = relay_state_proof + .read_slot() + .expect("Could not read the relay chain slot from the proof"); + + let inherent_data = + cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration( + relay_chain_slot, + core::time::Duration::from_secs(6), + ) + .create_inherent_data() + .expect("Could not create the timestamp inherent data"); + + inherent_data.check_extrinsics(block) + } + } + + // Nimbus's Executive wrapper allows relay validators to verify the seal digest + #[cfg(feature = "parachain")] + cumulus_pallet_parachain_system::register_validate_block! { + Runtime = Runtime, + BlockExecutor = pallet_author_inherent::BlockExecutor::, + CheckInherents = CheckInherents, + } + } +} + +#[macro_export] +macro_rules! create_common_benchmark_logic { + {} => { + #[cfg(feature = "runtime-benchmarks")] + pub(crate) mod benchmarks { + pub(crate) mod currencies { + use super::utils::{lookup_of_account, set_balance}; + use crate::{AccountId, Amount, AssetManager, Balance, CurrencyId, Runtime}; + use zeitgeist_primitives::{ + constants::{ExistentialDeposit, GetNativeCurrencyId, BASE}, + types::Asset, + }; + + use frame_benchmarking::{account, whitelisted_caller}; + use frame_system::RawOrigin; + use sp_runtime::traits::UniqueSaturatedInto; + + use orml_benchmarking::runtime_benchmarks; + use orml_traits::MultiCurrency; + + const SEED: u32 = 0; + + const NATIVE: CurrencyId = GetNativeCurrencyId::get(); + const ASSET: CurrencyId = Asset::CategoricalOutcome(0, 0); + + runtime_benchmarks! { + { Runtime, orml_currencies } + + // `transfer` non-native currency + transfer_non_native_currency { + let amount: Balance = 1_000 * BASE; + let from: AccountId = whitelisted_caller(); + set_balance(ASSET, &from, amount); + + let to: AccountId = account("to", 0, SEED); + let to_lookup = lookup_of_account(to.clone()); + }: transfer(RawOrigin::Signed(from), to_lookup, ASSET, amount) + verify { + assert_eq!(>::total_balance(ASSET, &to), amount); + } + + // `transfer` native currency and in worst case + #[extra] + transfer_native_currency_worst_case { + let existential_deposit = ExistentialDeposit::get(); + let amount: Balance = existential_deposit.saturating_mul(1000); + let from: AccountId = whitelisted_caller(); + set_balance(NATIVE, &from, amount); + + let to: AccountId = account("to", 0, SEED); + let to_lookup = lookup_of_account(to.clone()); + }: transfer(RawOrigin::Signed(from), to_lookup, NATIVE, amount) + verify { + assert_eq!(>::total_balance(NATIVE, &to), amount); + } + + // `transfer_native_currency` in worst case + // * will create the `to` account. + // * will kill the `from` account. + transfer_native_currency { + let existential_deposit = ExistentialDeposit::get(); + let amount: Balance = existential_deposit.saturating_mul(1000); + let from: AccountId = whitelisted_caller(); + set_balance(NATIVE, &from, amount); + + let to: AccountId = account("to", 0, SEED); + let to_lookup = lookup_of_account(to.clone()); + }: _(RawOrigin::Signed(from), to_lookup, amount) + verify { + assert_eq!(>::total_balance(NATIVE, &to), amount); + } + + // `update_balance` for non-native currency + update_balance_non_native_currency { + let balance: Balance = 2 * BASE; + let amount: Amount = balance.unique_saturated_into(); + let who: AccountId = account("who", 0, SEED); + let who_lookup = lookup_of_account(who.clone()); + }: update_balance(RawOrigin::Root, who_lookup, ASSET, amount) + verify { + assert_eq!(>::total_balance(ASSET, &who), balance); + } + + // `update_balance` for native currency + // * will create the `who` account. + update_balance_native_currency_creating { + let existential_deposit = ExistentialDeposit::get(); + let balance: Balance = existential_deposit.saturating_mul(1000); + let amount: Amount = balance.unique_saturated_into(); + let who: AccountId = account("who", 0, SEED); + let who_lookup = lookup_of_account(who.clone()); + }: update_balance(RawOrigin::Root, who_lookup, NATIVE, amount) + verify { + assert_eq!(>::total_balance(NATIVE, &who), balance); + } + + // `update_balance` for native currency + // * will kill the `who` account. + update_balance_native_currency_killing { + let existential_deposit = ExistentialDeposit::get(); + let balance: Balance = existential_deposit.saturating_mul(1000); + let amount: Amount = balance.unique_saturated_into(); + let who: AccountId = account("who", 0, SEED); + let who_lookup = lookup_of_account(who.clone()); + set_balance(NATIVE, &who, balance); + }: update_balance(RawOrigin::Root, who_lookup, NATIVE, -amount) + verify { + assert_eq!(>::free_balance(NATIVE, &who), 0); + } + } + + #[cfg(test)] + mod tests { + use super::*; + use crate::benchmarks::utils::tests::new_test_ext; + use orml_benchmarking::impl_benchmark_test_suite; + + impl_benchmark_test_suite!(new_test_ext(),); + } + } + + pub(crate) mod tokens { + use super::utils::{lookup_of_account, set_balance as update_balance}; + use crate::{AccountId, Balance, CurrencyId, Tokens, Runtime}; + use frame_benchmarking::{account, whitelisted_caller}; + use frame_system::RawOrigin; + use orml_benchmarking::runtime_benchmarks; + use orml_traits::MultiCurrency; + use zeitgeist_primitives::{constants::BASE, types::Asset}; + + const SEED: u32 = 0; + const ASSET: CurrencyId = Asset::CategoricalOutcome(0, 0); + + runtime_benchmarks! { + { Runtime, orml_tokens } + + transfer { + let amount: Balance = BASE; + + let from: AccountId = whitelisted_caller(); + update_balance(ASSET, &from, amount); + + let to: AccountId = account("to", 0, SEED); + let to_lookup = lookup_of_account(to.clone()); + }: _(RawOrigin::Signed(from), to_lookup, ASSET, amount) + verify { + assert_eq!(>::total_balance(ASSET, &to), amount); + } + + transfer_all { + let amount: Balance = BASE; + + let from: AccountId = whitelisted_caller(); + update_balance(ASSET, &from, amount); + + let to: AccountId = account("to", 0, SEED); + let to_lookup = lookup_of_account(to); + }: _(RawOrigin::Signed(from.clone()), to_lookup, ASSET, false) + verify { + assert_eq!(>::total_balance(ASSET, &from), 0); + } + + transfer_keep_alive { + let from: AccountId = whitelisted_caller(); + update_balance(ASSET, &from, 2 * BASE); + + let to: AccountId = account("to", 0, SEED); + let to_lookup = lookup_of_account(to.clone()); + }: _(RawOrigin::Signed(from), to_lookup, ASSET, BASE) + verify { + assert_eq!(>::total_balance(ASSET, &to), BASE); + } + + force_transfer { + let from: AccountId = account("from", 0, SEED); + let from_lookup = lookup_of_account(from.clone()); + update_balance(ASSET, &from, 2 * BASE); + + let to: AccountId = account("to", 0, SEED); + let to_lookup = lookup_of_account(to.clone()); + }: _(RawOrigin::Root, from_lookup, to_lookup, ASSET, BASE) + verify { + assert_eq!(>::total_balance(ASSET, &to), BASE); + } + + set_balance { + let who: AccountId = account("who", 0, SEED); + let who_lookup = lookup_of_account(who.clone()); + + }: _(RawOrigin::Root, who_lookup, ASSET, BASE, BASE) + verify { + assert_eq!(>::total_balance(ASSET, &who), 2 * BASE); + } + } + + #[cfg(test)] + mod tests { + use super::*; + use crate::benchmarks::utils::tests::new_test_ext; + use orml_benchmarking::impl_benchmark_test_suite; + + impl_benchmark_test_suite!(new_test_ext(),); + } + } + + pub(crate) mod utils { + use crate::{AccountId, AssetManager, Balance, CurrencyId, Runtime, + }; + use frame_support::assert_ok; + use orml_traits::MultiCurrencyExtended; + use sp_runtime::traits::{SaturatedConversion, StaticLookup}; + + pub fn lookup_of_account( + who: AccountId, + ) -> <::Lookup as StaticLookup>::Source { + ::Lookup::unlookup(who) + } + + pub fn set_balance(currency_id: CurrencyId, who: &AccountId, balance: Balance) { + assert_ok!(>::update_balance( + currency_id, + who, + balance.saturated_into() + )); + } + + #[cfg(test)] + pub mod tests { + pub fn new_test_ext() -> sp_io::TestExternalities { + frame_system::GenesisConfig::default().build_storage::().unwrap().into() + } + } + } + } + } +} + +#[macro_export] +macro_rules! create_common_tests { + {} => { + #[cfg(test)] + mod common_tests { + mod fee_multiplier { + use crate::parameters::{MinimumMultiplier, SlowAdjustingFeeUpdate, TargetBlockFullness}; + use frame_support::{ + parameter_types, + weights::{DispatchClass, Weight}, + }; + use sp_core::H256; + use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, Convert, IdentityLookup}, + Perbill, + }; + + type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; + type Block = frame_system::mocking::MockBlock; + + frame_support::construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event} + } + ); + + parameter_types! { + pub const BlockHashCount: u64 = 250; + pub const AvailableBlockRatio: Perbill = Perbill::one(); + pub BlockLength: frame_system::limits::BlockLength = + frame_system::limits::BlockLength::max(2 * 1024); + pub BlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::simple_max(1024); + } + + impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = BlockWeights; + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Index = u64; + type BlockNumber = u64; + type Call = Call; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; + } + + fn run_with_system_weight(w: Weight, mut assertions: F) + where + F: FnMut(), + { + let mut t: sp_io::TestExternalities = + frame_system::GenesisConfig::default().build_storage::().unwrap().into(); + t.execute_with(|| { + System::set_block_consumed_resources(w, 0); + assertions() + }); + } + + #[test] + fn multiplier_can_grow_from_zero() { + let minimum_multiplier = MinimumMultiplier::get(); + let target = TargetBlockFullness::get() + * BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap(); + // if the min is too small, then this will not change, and we are doomed forever. + // the weight is 1/100th bigger than target. + run_with_system_weight(target * 101 / 100, || { + let next = SlowAdjustingFeeUpdate::::convert(minimum_multiplier); + assert!(next > minimum_multiplier, "{:?} !>= {:?}", next, minimum_multiplier); + }) + } + } + } + } +} diff --git a/runtime/src/weights/cumulus_pallet_xcmp_queue.rs b/runtime/common/src/weights/cumulus_pallet_xcmp_queue.rs similarity index 100% rename from runtime/src/weights/cumulus_pallet_xcmp_queue.rs rename to runtime/common/src/weights/cumulus_pallet_xcmp_queue.rs diff --git a/runtime/src/weights/frame_system.rs b/runtime/common/src/weights/frame_system.rs similarity index 100% rename from runtime/src/weights/frame_system.rs rename to runtime/common/src/weights/frame_system.rs diff --git a/runtime/src/weights/mod.rs b/runtime/common/src/weights/mod.rs similarity index 100% rename from runtime/src/weights/mod.rs rename to runtime/common/src/weights/mod.rs diff --git a/runtime/src/weights/orml_currencies.rs b/runtime/common/src/weights/orml_currencies.rs similarity index 100% rename from runtime/src/weights/orml_currencies.rs rename to runtime/common/src/weights/orml_currencies.rs diff --git a/runtime/src/weights/orml_tokens.rs b/runtime/common/src/weights/orml_tokens.rs similarity index 100% rename from runtime/src/weights/orml_tokens.rs rename to runtime/common/src/weights/orml_tokens.rs diff --git a/runtime/src/weights/pallet_author_mapping.rs b/runtime/common/src/weights/pallet_author_mapping.rs similarity index 100% rename from runtime/src/weights/pallet_author_mapping.rs rename to runtime/common/src/weights/pallet_author_mapping.rs diff --git a/runtime/src/weights/pallet_author_slot_filter.rs b/runtime/common/src/weights/pallet_author_slot_filter.rs similarity index 100% rename from runtime/src/weights/pallet_author_slot_filter.rs rename to runtime/common/src/weights/pallet_author_slot_filter.rs diff --git a/runtime/src/weights/pallet_balances.rs b/runtime/common/src/weights/pallet_balances.rs similarity index 100% rename from runtime/src/weights/pallet_balances.rs rename to runtime/common/src/weights/pallet_balances.rs diff --git a/runtime/src/weights/pallet_collective.rs b/runtime/common/src/weights/pallet_collective.rs similarity index 100% rename from runtime/src/weights/pallet_collective.rs rename to runtime/common/src/weights/pallet_collective.rs diff --git a/runtime/src/weights/pallet_democracy.rs b/runtime/common/src/weights/pallet_democracy.rs similarity index 100% rename from runtime/src/weights/pallet_democracy.rs rename to runtime/common/src/weights/pallet_democracy.rs diff --git a/runtime/src/weights/pallet_grandpa.rs b/runtime/common/src/weights/pallet_grandpa.rs similarity index 100% rename from runtime/src/weights/pallet_grandpa.rs rename to runtime/common/src/weights/pallet_grandpa.rs diff --git a/runtime/src/weights/pallet_identity.rs b/runtime/common/src/weights/pallet_identity.rs similarity index 100% rename from runtime/src/weights/pallet_identity.rs rename to runtime/common/src/weights/pallet_identity.rs diff --git a/runtime/src/weights/pallet_membership.rs b/runtime/common/src/weights/pallet_membership.rs similarity index 100% rename from runtime/src/weights/pallet_membership.rs rename to runtime/common/src/weights/pallet_membership.rs diff --git a/runtime/src/weights/pallet_multisig.rs b/runtime/common/src/weights/pallet_multisig.rs similarity index 100% rename from runtime/src/weights/pallet_multisig.rs rename to runtime/common/src/weights/pallet_multisig.rs diff --git a/runtime/src/weights/pallet_preimage.rs b/runtime/common/src/weights/pallet_preimage.rs similarity index 100% rename from runtime/src/weights/pallet_preimage.rs rename to runtime/common/src/weights/pallet_preimage.rs diff --git a/runtime/src/weights/pallet_proxy.rs b/runtime/common/src/weights/pallet_proxy.rs similarity index 100% rename from runtime/src/weights/pallet_proxy.rs rename to runtime/common/src/weights/pallet_proxy.rs diff --git a/runtime/src/weights/pallet_scheduler.rs b/runtime/common/src/weights/pallet_scheduler.rs similarity index 100% rename from runtime/src/weights/pallet_scheduler.rs rename to runtime/common/src/weights/pallet_scheduler.rs diff --git a/runtime/src/weights/pallet_timestamp.rs b/runtime/common/src/weights/pallet_timestamp.rs similarity index 100% rename from runtime/src/weights/pallet_timestamp.rs rename to runtime/common/src/weights/pallet_timestamp.rs diff --git a/runtime/src/weights/pallet_treasury.rs b/runtime/common/src/weights/pallet_treasury.rs similarity index 100% rename from runtime/src/weights/pallet_treasury.rs rename to runtime/common/src/weights/pallet_treasury.rs diff --git a/runtime/src/weights/pallet_utility.rs b/runtime/common/src/weights/pallet_utility.rs similarity index 100% rename from runtime/src/weights/pallet_utility.rs rename to runtime/common/src/weights/pallet_utility.rs diff --git a/runtime/src/weights/pallet_vesting.rs b/runtime/common/src/weights/pallet_vesting.rs similarity index 100% rename from runtime/src/weights/pallet_vesting.rs rename to runtime/common/src/weights/pallet_vesting.rs diff --git a/runtime/src/weights/parachain_staking.rs b/runtime/common/src/weights/parachain_staking.rs similarity index 100% rename from runtime/src/weights/parachain_staking.rs rename to runtime/common/src/weights/parachain_staking.rs diff --git a/runtime/src/benchmarking/currencies.rs b/runtime/src/benchmarking/currencies.rs deleted file mode 100644 index 9bc6eb42d..000000000 --- a/runtime/src/benchmarking/currencies.rs +++ /dev/null @@ -1,131 +0,0 @@ -// This file was originally fetched from Acala -// https://github.com/AcalaNetwork/Acala/blob/6e0dae03040db2a1ef168a2ecba357c7b628874c/runtime/mandala/src/benchmarking/currencies.rs - -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -use super::utils::{lookup_of_account, set_balance}; -use crate::{ - AccountId, Amount, AssetManager, Balance, CurrencyId, ExistentialDeposit, GetNativeCurrencyId, - Runtime, -}; -use zeitgeist_primitives::{constants::BASE, types::Asset}; - -use frame_benchmarking::{account, whitelisted_caller}; -use frame_system::RawOrigin; -use sp_runtime::traits::UniqueSaturatedInto; - -use orml_benchmarking::runtime_benchmarks; -use orml_traits::MultiCurrency; - -const SEED: u32 = 0; - -const NATIVE: CurrencyId = GetNativeCurrencyId::get(); -const ASSET: CurrencyId = Asset::CategoricalOutcome(0, 0); - -runtime_benchmarks! { - { Runtime, orml_currencies } - - // `transfer` non-native currency - transfer_non_native_currency { - let amount: Balance = 1_000 * BASE; - let from: AccountId = whitelisted_caller(); - set_balance(ASSET, &from, amount); - - let to: AccountId = account("to", 0, SEED); - let to_lookup = lookup_of_account(to.clone()); - }: transfer(RawOrigin::Signed(from), to_lookup, ASSET, amount) - verify { - assert_eq!(>::total_balance(ASSET, &to), amount); - } - - // `transfer` native currency and in worst case - #[extra] - transfer_native_currency_worst_case { - let existential_deposit = ExistentialDeposit::get(); - let amount: Balance = existential_deposit.saturating_mul(1000); - let from: AccountId = whitelisted_caller(); - set_balance(NATIVE, &from, amount); - - let to: AccountId = account("to", 0, SEED); - let to_lookup = lookup_of_account(to.clone()); - }: transfer(RawOrigin::Signed(from), to_lookup, NATIVE, amount) - verify { - assert_eq!(>::total_balance(NATIVE, &to), amount); - } - - // `transfer_native_currency` in worst case - // * will create the `to` account. - // * will kill the `from` account. - transfer_native_currency { - let existential_deposit = ExistentialDeposit::get(); - let amount: Balance = existential_deposit.saturating_mul(1000); - let from: AccountId = whitelisted_caller(); - set_balance(NATIVE, &from, amount); - - let to: AccountId = account("to", 0, SEED); - let to_lookup = lookup_of_account(to.clone()); - }: _(RawOrigin::Signed(from), to_lookup, amount) - verify { - assert_eq!(>::total_balance(NATIVE, &to), amount); - } - - // `update_balance` for non-native currency - update_balance_non_native_currency { - let balance: Balance = 2 * BASE; - let amount: Amount = balance.unique_saturated_into(); - let who: AccountId = account("who", 0, SEED); - let who_lookup = lookup_of_account(who.clone()); - }: update_balance(RawOrigin::Root, who_lookup, ASSET, amount) - verify { - assert_eq!(>::total_balance(ASSET, &who), balance); - } - - // `update_balance` for native currency - // * will create the `who` account. - update_balance_native_currency_creating { - let existential_deposit = ExistentialDeposit::get(); - let balance: Balance = existential_deposit.saturating_mul(1000); - let amount: Amount = balance.unique_saturated_into(); - let who: AccountId = account("who", 0, SEED); - let who_lookup = lookup_of_account(who.clone()); - }: update_balance(RawOrigin::Root, who_lookup, NATIVE, amount) - verify { - assert_eq!(>::total_balance(NATIVE, &who), balance); - } - - // `update_balance` for native currency - // * will kill the `who` account. - update_balance_native_currency_killing { - let existential_deposit = ExistentialDeposit::get(); - let balance: Balance = existential_deposit.saturating_mul(1000); - let amount: Amount = balance.unique_saturated_into(); - let who: AccountId = account("who", 0, SEED); - let who_lookup = lookup_of_account(who.clone()); - set_balance(NATIVE, &who, balance); - }: update_balance(RawOrigin::Root, who_lookup, NATIVE, -amount) - verify { - assert_eq!(>::free_balance(NATIVE, &who), 0); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::benchmarking::utils::tests::new_test_ext; - use orml_benchmarking::impl_benchmark_test_suite; - - impl_benchmark_test_suite!(new_test_ext(),); -} diff --git a/runtime/src/benchmarking/mod.rs b/runtime/src/benchmarking/mod.rs deleted file mode 100644 index f2e62b5ff..000000000 --- a/runtime/src/benchmarking/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -#![cfg(feature = "runtime-benchmarks")] -#![allow(clippy::integer_arithmetic)] - -pub mod currencies; -pub mod tokens; -pub mod utils; diff --git a/runtime/src/benchmarking/tokens.rs b/runtime/src/benchmarking/tokens.rs deleted file mode 100644 index 0d195012d..000000000 --- a/runtime/src/benchmarking/tokens.rs +++ /dev/null @@ -1,99 +0,0 @@ -// This file was originally fetched from Acala -// https://github.com/AcalaNetwork/Acala/blob/6e0dae03040db2a1ef168a2ecba357c7b628874c/runtime/mandala/src/benchmarking/currencies.rs - -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -use super::utils::{lookup_of_account, set_balance as update_balance}; -use crate::{AccountId, Balance, CurrencyId, Runtime, Tokens}; -use frame_benchmarking::{account, whitelisted_caller}; -use frame_system::RawOrigin; -use orml_benchmarking::runtime_benchmarks; -use orml_traits::MultiCurrency; -use zeitgeist_primitives::{constants::BASE, types::Asset}; - -const SEED: u32 = 0; -const ASSET: CurrencyId = Asset::CategoricalOutcome(0, 0); - -runtime_benchmarks! { - { Runtime, orml_tokens } - - transfer { - let amount: Balance = BASE; - - let from: AccountId = whitelisted_caller(); - update_balance(ASSET, &from, amount); - - let to: AccountId = account("to", 0, SEED); - let to_lookup = lookup_of_account(to.clone()); - }: _(RawOrigin::Signed(from), to_lookup, ASSET, amount) - verify { - assert_eq!(>::total_balance(ASSET, &to), amount); - } - - transfer_all { - let amount: Balance = BASE; - - let from: AccountId = whitelisted_caller(); - update_balance(ASSET, &from, amount); - - let to: AccountId = account("to", 0, SEED); - let to_lookup = lookup_of_account(to); - }: _(RawOrigin::Signed(from.clone()), to_lookup, ASSET, false) - verify { - assert_eq!(>::total_balance(ASSET, &from), 0); - } - - transfer_keep_alive { - let from: AccountId = whitelisted_caller(); - update_balance(ASSET, &from, 2 * BASE); - - let to: AccountId = account("to", 0, SEED); - let to_lookup = lookup_of_account(to.clone()); - }: _(RawOrigin::Signed(from), to_lookup, ASSET, BASE) - verify { - assert_eq!(>::total_balance(ASSET, &to), BASE); - } - - force_transfer { - let from: AccountId = account("from", 0, SEED); - let from_lookup = lookup_of_account(from.clone()); - update_balance(ASSET, &from, 2 * BASE); - - let to: AccountId = account("to", 0, SEED); - let to_lookup = lookup_of_account(to.clone()); - }: _(RawOrigin::Root, from_lookup, to_lookup, ASSET, BASE) - verify { - assert_eq!(>::total_balance(ASSET, &to), BASE); - } - - set_balance { - let who: AccountId = account("who", 0, SEED); - let who_lookup = lookup_of_account(who.clone()); - - }: _(RawOrigin::Root, who_lookup, ASSET, BASE, BASE) - verify { - assert_eq!(>::total_balance(ASSET, &who), 2 * BASE); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::benchmarking::utils::tests::new_test_ext; - use orml_benchmarking::impl_benchmark_test_suite; - - impl_benchmark_test_suite!(new_test_ext(),); -} diff --git a/runtime/src/benchmarking/utils.rs b/runtime/src/benchmarking/utils.rs deleted file mode 100644 index 6458526f1..000000000 --- a/runtime/src/benchmarking/utils.rs +++ /dev/null @@ -1,44 +0,0 @@ -// This file was originally fetched from Acala -// https://github.com/AcalaNetwork/Acala/blob/6e0dae03040db2a1ef168a2ecba357c7b628874c/runtime/mandala/src/benchmarking/utils.rs - -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -use crate::{AccountId, AssetManager, Balance, CurrencyId, Runtime}; - -use frame_support::assert_ok; -use orml_traits::MultiCurrencyExtended; -use sp_runtime::traits::{SaturatedConversion, StaticLookup}; - -pub fn lookup_of_account( - who: AccountId, -) -> <::Lookup as StaticLookup>::Source { - ::Lookup::unlookup(who) -} - -pub fn set_balance(currency_id: CurrencyId, who: &AccountId, balance: Balance) { - assert_ok!(>::update_balance( - currency_id, - who, - balance.saturated_into() - )); -} - -#[cfg(test)] -pub mod tests { - pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() - } -} diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs deleted file mode 100644 index b71eebeb4..000000000 --- a/runtime/src/lib.rs +++ /dev/null @@ -1,1472 +0,0 @@ -#![cfg_attr(not(feature = "std"), no_std)] -#![recursion_limit = "256"] - -extern crate alloc; - -#[cfg(feature = "std")] -include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); - -#[cfg(feature = "runtime-benchmarks")] -mod benchmarking; -pub mod opaque; -#[cfg(feature = "parachain")] -mod parachain_params; -mod parameters; -mod tests; -mod weights; -#[cfg(feature = "parachain")] -mod xcm_config; - -pub use frame_system::{ - Call as SystemCall, CheckEra, CheckGenesis, CheckNonZeroSender, CheckNonce, CheckSpecVersion, - CheckTxVersion, CheckWeight, -}; -pub use pallet_transaction_payment::ChargeTransactionPayment; -pub use parameters::*; -#[cfg(feature = "parachain")] -pub use {pallet_author_slot_filter::EligibilityValue, parachain_params::*}; - -use alloc::{boxed::Box, vec, vec::Vec}; -use frame_support::{ - construct_runtime, - traits::{ConstU16, ConstU32, Contains, EnsureOneOf, EqualPrivilegeOnly, InstanceFilter}, - weights::{constants::RocksDbWeight, ConstantMultiplier, IdentityFee}, -}; -use frame_system::EnsureRoot; -use pallet_collective::{EnsureProportionAtLeast, PrimeDefaultVote}; -use sp_api::impl_runtime_apis; -use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; -use sp_runtime::{ - create_runtime_str, generic, - traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT}, - transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, -}; -#[cfg(feature = "std")] -use sp_version::NativeVersion; -use sp_version::RuntimeVersion; -use substrate_fixed::{types::extra::U33, FixedI128, FixedU128}; -use zeitgeist_primitives::{constants::*, types::*}; -use zrml_rikiddo::types::{EmaMarketVolume, FeeSigmoid, RikiddoSigmoidMV}; -#[cfg(feature = "parachain")] -use { - frame_support::traits::{Everything, Nothing}, - frame_system::EnsureSigned, - nimbus_primitives::{CanAuthor, NimbusId}, - xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, - xcm_config::XcmConfig, -}; - -pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("zeitgeist"), - impl_name: create_runtime_str!("zeitgeist"), - authoring_version: 1, - spec_version: 38, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 15, - state_version: 1, -}; - -pub type Block = generic::Block; - -type Address = sp_runtime::MultiAddress; - -type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, - ( - zrml_court::migrations::JurorsCountedStorageMapMigration, - zrml_prediction_markets::migrations::MigrateMarketPoolsBeforeOpen, - zrml_prediction_markets::migrations::CleanUpStorageForResolvedOrClosedMarkets, - ), ->; - -type Header = generic::Header; -type RikiddoSigmoidFeeMarketVolumeEma = zrml_rikiddo::Instance1; -pub type SignedExtra = ( - CheckNonZeroSender, - CheckSpecVersion, - CheckTxVersion, - CheckGenesis, - CheckEra, - CheckNonce, - CheckWeight, - ChargeTransactionPayment, -); -pub type SignedPayload = generic::SignedPayload; -pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; - -// Governance -type AdvisoryCommitteeInstance = pallet_collective::Instance1; -type AdvisoryCommitteeMembershipInstance = pallet_membership::Instance1; -type CouncilInstance = pallet_collective::Instance2; -type CouncilMembershipInstance = pallet_membership::Instance2; -type TechnicalCommitteeInstance = pallet_collective::Instance3; -type TechnicalCommitteeMembershipInstance = pallet_membership::Instance3; - -// Council vote proportions -// At least 50% -type EnsureRootOrHalfCouncil = - EnsureOneOf, EnsureProportionAtLeast>; - -// At least 66% -type EnsureRootOrTwoThirdsCouncil = - EnsureOneOf, EnsureProportionAtLeast>; - -// At least 75% -type EnsureRootOrThreeFourthsCouncil = - EnsureOneOf, EnsureProportionAtLeast>; - -// At least 100% -type EnsureRootOrAllCouncil = - EnsureOneOf, EnsureProportionAtLeast>; - -// Technical committee vote proportions -// At least 50% -#[cfg(feature = "parachain")] -type EnsureRootOrHalfTechnicalCommittee = EnsureOneOf< - EnsureRoot, - EnsureProportionAtLeast, ->; - -// At least 66% -type EnsureRootOrTwoThirdsTechnicalCommittee = EnsureOneOf< - EnsureRoot, - EnsureProportionAtLeast, ->; - -// At least 100% -type EnsureRootOrAllTechnicalCommittee = EnsureOneOf< - EnsureRoot, - EnsureProportionAtLeast, ->; - -// Advisory committee vote proportions -// At least 50% -type EnsureRootOrHalfAdvisoryCommittee = EnsureOneOf< - EnsureRoot, - EnsureProportionAtLeast, ->; - -// Technical committee vote proportions -// At least 66% -type EnsureRootOrTwoThirdsAdvisoryCommittee = EnsureOneOf< - EnsureRoot, - EnsureProportionAtLeast, ->; - -// At least 100% -type EnsureRootOrAllAdvisoryCommittee = EnsureOneOf< - EnsureRoot, - EnsureProportionAtLeast, ->; - -// Construct runtime -macro_rules! create_zeitgeist_runtime { - ($($additional_pallets:tt)*) => { - // Pallets are enumerated based on the dependency graph. - // - // For example, `PredictionMarkets` is pĺaced after `SimpleDisputes` because - // `PredictionMarkets` depends on `SimpleDisputes`. - construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = generic::Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - // System - System: frame_system::{Call, Config, Event, Pallet, Storage} = 0, - Timestamp: pallet_timestamp::{Call, Pallet, Storage, Inherent} = 1, - RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 2, - Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 3, - Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 4, - - // Money - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage} = 10, - TransactionPayment: pallet_transaction_payment::{Config, Pallet, Storage} = 11, - Treasury: pallet_treasury::{Call, Config, Event, Pallet, Storage} = 12, - Vesting: pallet_vesting::{Call, Config, Event, Pallet, Storage} = 13, - MultiSig: pallet_multisig::{Call, Event, Pallet, Storage} = 14, - - // Governance - Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 20, - AdvisoryCommittee: pallet_collective::::{Call, Config, Event, Origin, Pallet, Storage} = 21, - AdvisoryCommitteeMembership: pallet_membership::::{Call, Config, Event, Pallet, Storage} = 22, - Council: pallet_collective::::{Call, Config, Event, Origin, Pallet, Storage} = 23, - CouncilMembership: pallet_membership::::{Call, Config, Event, Pallet, Storage} = 24, - TechnicalCommittee: pallet_collective::::{Call, Config, Event, Origin, Pallet, Storage} = 25, - TechnicalCommitteeMembership: pallet_membership::::{Call, Config, Event, Pallet, Storage} = 26, - - // Other Parity pallets - Identity: pallet_identity::{Call, Event, Pallet, Storage} = 30, - Utility: pallet_utility::{Call, Event, Pallet, Storage} = 31, - Proxy: pallet_proxy::{Call, Event, Pallet, Storage} = 32, - - // Third-party - AssetManager: orml_currencies::{Call, Pallet, Storage} = 40, - Tokens: orml_tokens::{Config, Event, Pallet, Storage} = 41, - - // Zeitgeist - MarketCommons: zrml_market_commons::{Pallet, Storage} = 50, - Authorized: zrml_authorized::{Call, Event, Pallet, Storage} = 51, - Court: zrml_court::{Call, Event, Pallet, Storage} = 52, - LiquidityMining: zrml_liquidity_mining::{Call, Config, Event, Pallet, Storage} = 53, - RikiddoSigmoidFeeMarketEma: zrml_rikiddo::::{Pallet, Storage} = 54, - SimpleDisputes: zrml_simple_disputes::{Event, Pallet, Storage} = 55, - Swaps: zrml_swaps::{Call, Event, Pallet, Storage} = 56, - PredictionMarkets: zrml_prediction_markets::{Call, Event, Pallet, Storage} = 57, - Styx: zrml_styx::{Call, Event, Pallet, Storage} = 58, - - $($additional_pallets)* - } - ); - } -} - -macro_rules! create_zeitgeist_runtime_with_additional_pallets { - ($($additional_pallets:tt)*) => { - #[cfg(feature = "parachain")] - create_zeitgeist_runtime!( - // System - ParachainSystem: cumulus_pallet_parachain_system::{Call, Config, Event, Inherent, Pallet, Storage, ValidateUnsigned} = 100, - ParachainInfo: parachain_info::{Config, Pallet, Storage} = 101, - - // Consensus - ParachainStaking: parachain_staking::{Call, Config, Event, Pallet, Storage} = 110, - AuthorInherent: pallet_author_inherent::{Call, Inherent, Pallet, Storage} = 111, - AuthorFilter: pallet_author_slot_filter::{Call, Config, Event, Pallet, Storage} = 112, - AuthorMapping: pallet_author_mapping::{Call, Config, Event, Pallet, Storage} = 113, - - // XCM - CumulusXcm: cumulus_pallet_xcm::{Event, Origin, Pallet} = 120, - DmpQueue: cumulus_pallet_dmp_queue::{Call, Event, Pallet, Storage} = 121, - PolkadotXcm: pallet_xcm::{Call, Config, Event, Origin, Pallet, Storage} = 122, - XcmpQueue: cumulus_pallet_xcmp_queue::{Call, Event, Pallet, Storage} = 123, - - // Third-party - Crowdloan: pallet_crowdloan_rewards::{Call, Config, Event, Pallet, Storage} = 130, - - // Others - $($additional_pallets)* - ); - - #[cfg(not(feature = "parachain"))] - create_zeitgeist_runtime!( - // Consensus - Aura: pallet_aura::{Config, Pallet, Storage} = 100, - Grandpa: pallet_grandpa::{Call, Config, Event, Pallet, Storage} = 101, - - // Others - $($additional_pallets)* - ); - } -} - -#[cfg(not(feature = "without-sudo"))] -create_zeitgeist_runtime_with_additional_pallets!( - // Others - Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, -); - -#[cfg(feature = "without-sudo")] -create_zeitgeist_runtime_with_additional_pallets!(); - -// Configure Pallets -#[cfg(feature = "parachain")] -impl cumulus_pallet_dmp_queue::Config for Runtime { - type Event = Event; - type ExecuteOverweightOrigin = EnsureRootOrHalfTechnicalCommittee; - type XcmExecutor = xcm_executor::XcmExecutor; -} - -#[cfg(feature = "parachain")] -impl cumulus_pallet_parachain_system::Config for Runtime { - type DmpMessageHandler = DmpQueue; - type Event = Event; - type OnSystemEvent = (); - type OutboundXcmpMessageSource = XcmpQueue; - type ReservedDmpWeight = crate::parachain_params::ReservedDmpWeight; - type ReservedXcmpWeight = crate::parachain_params::ReservedXcmpWeight; - type SelfParaId = parachain_info::Pallet; - type XcmpMessageHandler = XcmpQueue; -} - -#[cfg(feature = "parachain")] -impl cumulus_pallet_xcm::Config for Runtime { - type Event = Event; - type XcmExecutor = xcm_executor::XcmExecutor; -} - -#[cfg(feature = "parachain")] -impl cumulus_pallet_xcmp_queue::Config for Runtime { - type ChannelInfo = ParachainSystem; - type ControllerOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; - type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; - type Event = Event; - type ExecuteOverweightOrigin = EnsureRootOrHalfTechnicalCommittee; - type VersionWrapper = (); - type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; - type XcmExecutor = xcm_executor::XcmExecutor; -} - -#[derive(scale_info::TypeInfo)] -pub struct IsCallable; - -cfg_if::cfg_if! { - if #[cfg(all(feature = "parachain", feature = "txfilter"))] { - // Restricted parachain. - impl Contains for IsCallable { - fn contains(call: &Call) -> bool { - match call { - // Allowed calls: - Call::AdvisoryCommittee(_) - | Call::AdvisoryCommitteeMembership(_) - | Call::AuthorInherent(_) - | Call::AuthorFilter(_) - | Call::AuthorMapping(_) - | Call::Balances(_) - | Call::Council(_) - | Call::CouncilMembership(_) - | Call::Crowdloan(_) - | Call::AssetManager(_) - | Call::Democracy(_) - | Call::DmpQueue(_) - | Call::Identity(_) - | Call::MultiSig(_) - | Call::ParachainStaking(_) - | Call::ParachainSystem(_) - | Call::PolkadotXcm(_) - | Call::Preimage(_) - | Call::Proxy(_) - | Call::Scheduler(_) - | Call::System(_) - | Call::TechnicalCommittee(_) - | Call::TechnicalCommitteeMembership(_) - | Call::Timestamp(_) - | Call::Treasury(_) - | Call::Utility(_) - | Call::Vesting(_) - | Call::XcmpQueue(_) => true, - - #[cfg(not(feature = "without-sudo"))] - Call::Sudo(_) => true, - - // Prohibited calls: - Call::Authorized(_) - | Call::Court(_) - | Call::LiquidityMining(_) - | Call::Swaps(_) - | Call::Styx(_) - | Call::PredictionMarkets(_) => false, - } - } - } - // Restricted standalone chain. - } else if #[cfg(all(feature = "txfilter", not(feature = "parachain")))] { - impl Contains for IsCallable { - fn contains(call: &Call) -> bool { - match call { - // Allowed calls: - Call::AdvisoryCommittee(_) - | Call::AdvisoryCommitteeMembership(_) - | Call::Balances(_) - | Call::Council(_) - | Call::CouncilMembership(_) - | Call::AssetManager(_) - | Call::Democracy(_) - | Call::Grandpa(_) - | Call::Identity(_) - | Call::MultiSig(_) - | Call::Preimage(_) - | Call::Proxy(_) - | Call::Scheduler(_) - | Call::System(_) - | Call::TechnicalCommittee(_) - | Call::TechnicalCommitteeMembership(_) - | Call::Timestamp(_) - | Call::Treasury(_) - | Call::Utility(_) - | Call::Vesting(_) => true, - - #[cfg(not(feature = "without-sudo"))] - Call::Sudo(_) => true, - - // Prohibited calls: - Call::Authorized(_) - | Call::Court(_) - | Call::LiquidityMining(_) - | Call::Swaps(_) - | Call::Styx(_) - | Call::PredictionMarkets(_)=> false, - } - } - } - // Unrestricted (no "txfilter" feature) chains. - // Currently disables Rikiddo and markets using Court or SimpleDisputes dispute mechanism. - // Will be relaxed for testnet once runtimes are separated. - } else { - impl Contains for IsCallable { - fn contains(call: &Call) -> bool { - use zrml_prediction_markets::Call::{create_market, create_cpmm_market_and_deploy_assets}; - use zeitgeist_primitives::types::{ScoringRule::RikiddoSigmoidFeeMarketEma, MarketDisputeMechanism::{Court, SimpleDisputes}}; - - match call { - Call::PredictionMarkets(inner_call) => { - match inner_call { - // Disable Rikiddo markets - create_market { scoring_rule: RikiddoSigmoidFeeMarketEma, .. } => false, - // Disable Court & SimpleDisputes dispute resolution mechanism - create_market { dispute_mechanism: Court | SimpleDisputes, .. } => false, - create_cpmm_market_and_deploy_assets { dispute_mechanism: Court | SimpleDisputes, .. } => false, - _ => true - } - } - Call::LiquidityMining(_) => false, - _ => true - } - } - } - } -} - -impl frame_system::Config for Runtime { - type AccountData = pallet_balances::AccountData; - type AccountId = AccountId; - type BaseCallFilter = IsCallable; - type BlockHashCount = BlockHashCount; - type BlockLength = RuntimeBlockLength; - type BlockNumber = BlockNumber; - type BlockWeights = RuntimeBlockWeights; - type Call = Call; - type DbWeight = RocksDbWeight; - type Event = Event; - type Hash = Hash; - type Hashing = BlakeTwo256; - type Header = generic::Header; - type Index = Index; - type Lookup = AccountIdLookup; - type MaxConsumers = ConstU32<16>; - type OnKilledAccount = (); - type OnNewAccount = (); - #[cfg(feature = "parachain")] - type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; - #[cfg(not(feature = "parachain"))] - type OnSetCode = (); - type Origin = Origin; - type PalletInfo = PalletInfo; - type SS58Prefix = SS58Prefix; - type SystemWeightInfo = weights::frame_system::WeightInfo; - type Version = Version; -} - -#[cfg(not(feature = "parachain"))] -impl pallet_aura::Config for Runtime { - type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; - type DisabledValidators = (); - type MaxAuthorities = MaxAuthorities; -} - -#[cfg(feature = "parachain")] -impl pallet_author_inherent::Config for Runtime { - type AccountLookup = AuthorMapping; - type CanAuthor = AuthorFilter; - type EventHandler = ParachainStaking; - type SlotBeacon = cumulus_pallet_parachain_system::RelaychainBlockNumberProvider; -} - -#[cfg(feature = "parachain")] -impl pallet_author_mapping::Config for Runtime { - type DepositAmount = CollatorDeposit; - type DepositCurrency = Balances; - type Event = Event; - type WeightInfo = weights::pallet_author_mapping::WeightInfo; -} - -#[cfg(feature = "parachain")] -impl pallet_author_slot_filter::Config for Runtime { - type Event = Event; - type RandomnessSource = RandomnessCollectiveFlip; - type PotentialAuthors = ParachainStaking; - type WeightInfo = weights::pallet_author_slot_filter::WeightInfo; -} - -#[cfg(not(feature = "parachain"))] -impl pallet_grandpa::Config for Runtime { - type Event = Event; - type Call = Call; - type KeyOwnerProofSystem = (); - type KeyOwnerProof = - >::Proof; - type KeyOwnerIdentification = - >::IdentificationTuple; - type HandleEquivocation = (); - type MaxAuthorities = MaxAuthorities; - // Currently the benchmark does yield an invalid weight implementation - // type WeightInfo = weights::pallet_grandpa::WeightInfo; - type WeightInfo = (); -} - -#[cfg(feature = "parachain")] -impl pallet_xcm::Config for Runtime { - type Event = Event; - type SendXcmOrigin = EnsureXcmOrigin; - type XcmRouter = XcmRouter; - type ExecuteXcmOrigin = EnsureXcmOrigin; - type XcmExecuteFilter = Nothing; - // ^ Disable dispatchable execute on the XCM pallet. - // Needs to be `Everything` for local testing. - type XcmExecutor = xcm_executor::XcmExecutor; - type XcmTeleportFilter = Everything; - type XcmReserveTransferFilter = Nothing; - type Weigher = FixedWeightBounds; - type LocationInverter = LocationInverter; - type Origin = Origin; - type Call = Call; - - const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; - // ^ Override for AdvertisedXcmVersion default - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; -} - -#[cfg(feature = "parachain")] -impl parachain_staking::Config for Runtime { - type CandidateBondLessDelay = CandidateBondLessDelay; - type Currency = Balances; - type DefaultBlocksPerRound = DefaultBlocksPerRound; - type DefaultCollatorCommission = DefaultCollatorCommission; - type DefaultParachainBondReservePercent = DefaultParachainBondReservePercent; - type DelegationBondLessDelay = DelegationBondLessDelay; - type Event = Event; - type LeaveCandidatesDelay = LeaveCandidatesDelay; - type LeaveDelegatorsDelay = LeaveDelegatorsDelay; - type MaxBottomDelegationsPerCandidate = MaxBottomDelegationsPerCandidate; - type MaxTopDelegationsPerCandidate = MaxTopDelegationsPerCandidate; - type MaxDelegationsPerDelegator = MaxDelegationsPerDelegator; - type MinBlocksPerRound = MinBlocksPerRound; - type MinCandidateStk = MinCollatorStk; - type MinCollatorStk = MinCollatorStk; - type MinDelegation = MinDelegatorStk; - type MinDelegatorStk = MinDelegatorStk; - type MinSelectedCandidates = MinSelectedCandidates; - type MonetaryGovernanceOrigin = EnsureRoot; - type RevokeDelegationDelay = RevokeDelegationDelay; - type RewardPaymentDelay = RewardPaymentDelay; - type WeightInfo = weights::parachain_staking::WeightInfo; -} - -impl orml_currencies::Config for Runtime { - type GetNativeCurrencyId = GetNativeCurrencyId; - type MultiCurrency = Tokens; - type NativeCurrency = BasicCurrencyAdapter; - type WeightInfo = weights::orml_currencies::WeightInfo; -} - -impl orml_tokens::Config for Runtime { - type Amount = Amount; - type Balance = Balance; - type CurrencyId = CurrencyId; - type DustRemovalWhitelist = DustRemovalWhitelist; - type Event = Event; - type ExistentialDeposits = ExistentialDeposits; - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type OnDust = orml_tokens::TransferDust; - type ReserveIdentifier = [u8; 8]; - type WeightInfo = weights::orml_tokens::WeightInfo; - type OnNewTokenAccount = (); - type OnKilledTokenAccount = (); -} - -#[cfg(feature = "parachain")] -impl pallet_crowdloan_rewards::Config for Runtime { - type Event = Event; - type InitializationPayment = InitializationPayment; - type Initialized = Initialized; - type MaxInitContributors = MaxInitContributorsBatchSizes; - type MinimumReward = MinimumReward; - type RelayChainAccountId = AccountId; - type RewardCurrency = Balances; - type RewardAddressAssociateOrigin = EnsureSigned; - type RewardAddressChangeOrigin = frame_system::EnsureSigned; - type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold; - type SignatureNetworkIdentifier = SignatureNetworkIdentifier; - type VestingBlockNumber = cumulus_primitives_core::relay_chain::BlockNumber; - type VestingBlockProvider = - cumulus_pallet_parachain_system::RelaychainBlockNumberProvider; - type WeightInfo = pallet_crowdloan_rewards::weights::SubstrateWeight; -} - -impl pallet_balances::Config for Runtime { - type AccountStore = System; - type Balance = Balance; - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = ExistentialDeposit; - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type WeightInfo = pallet_balances::weights::SubstrateWeight; // weights::pallet_balances::WeightInfo; -} - -impl pallet_collective::Config for Runtime { - type DefaultVote = PrimeDefaultVote; - type Event = Event; - type MaxMembers = AdvisoryCommitteeMaxMembers; - type MaxProposals = AdvisoryCommitteeMaxProposals; - type MotionDuration = AdvisoryCommitteeMotionDuration; - type Origin = Origin; - type Proposal = Call; - type WeightInfo = weights::pallet_collective::WeightInfo; -} - -impl pallet_collective::Config for Runtime { - type DefaultVote = PrimeDefaultVote; - type Event = Event; - type MaxMembers = CouncilMaxMembers; - type MaxProposals = CouncilMaxProposals; - type MotionDuration = CouncilMotionDuration; - type Origin = Origin; - type Proposal = Call; - type WeightInfo = weights::pallet_collective::WeightInfo; -} - -impl pallet_collective::Config for Runtime { - type DefaultVote = PrimeDefaultVote; - type Event = Event; - type MaxMembers = TechnicalCommitteeMaxMembers; - type MaxProposals = TechnicalCommitteeMaxProposals; - type MotionDuration = TechnicalCommitteeMotionDuration; - type Origin = Origin; - type Proposal = Call; - type WeightInfo = weights::pallet_collective::WeightInfo; -} - -impl pallet_democracy::Config for Runtime { - type Proposal = Call; - type Event = Event; - type Currency = Balances; - type EnactmentPeriod = EnactmentPeriod; - type LaunchPeriod = LaunchPeriod; - type VotingPeriod = VotingPeriod; - type VoteLockingPeriod = VoteLockingPeriod; - type MinimumDeposit = MinimumDeposit; - /// Origin that can decide what their next motion is. - type ExternalOrigin = EnsureRootOrHalfCouncil; - /// Origin that can have the next scheduled referendum be a straight majority-carries vote. - type ExternalMajorityOrigin = EnsureRootOrHalfCouncil; - /// Origina that can have the next scheduled referendum be a straight default-carries - /// (NTB) vote. - type ExternalDefaultOrigin = EnsureRootOrAllCouncil; - /// Origin that can have an ExternalMajority/ExternalDefault vote - /// be tabled immediately and with a shorter voting/enactment period. - type FastTrackOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; - /// Origin from which the next majority-carries (or more permissive) referendum may be tabled - /// to vote immediately and asynchronously in a similar manner to the emergency origin. - type InstantOrigin = EnsureRootOrAllTechnicalCommittee; - type InstantAllowed = InstantAllowed; - type FastTrackVotingPeriod = FastTrackVotingPeriod; - /// Origin from which any referendum may be cancelled in an emergency. - type CancellationOrigin = EnsureRootOrThreeFourthsCouncil; - /// Origin from which proposals may be blacklisted. - type BlacklistOrigin = EnsureRootOrAllCouncil; - /// Origin from which a proposal may be cancelled and its backers slashed. - type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee; - /// Origin for anyone able to veto proposals. - type VetoOrigin = pallet_collective::EnsureMember; - type CooloffPeriod = CooloffPeriod; - type PreimageByteDeposit = PreimageByteDeposit; - type OperationalPreimageOrigin = pallet_collective::EnsureMember; - type Slash = Treasury; - type Scheduler = Scheduler; - type PalletsOrigin = OriginCaller; - type MaxVotes = MaxVotes; - type WeightInfo = weights::pallet_democracy::WeightInfo; - type MaxProposals = MaxProposals; -} - -impl pallet_identity::Config for Runtime { - type BasicDeposit = BasicDeposit; - type Currency = Balances; - type Event = Event; - type FieldDeposit = FieldDeposit; - type ForceOrigin = EnsureRootOrTwoThirdsAdvisoryCommittee; - type MaxAdditionalFields = MaxAdditionalFields; - type MaxRegistrars = MaxRegistrars; - type MaxSubAccounts = MaxSubAccounts; - type RegistrarOrigin = EnsureRootOrHalfCouncil; - type Slashed = Treasury; - type SubAccountDeposit = SubAccountDeposit; - type WeightInfo = weights::pallet_identity::WeightInfo; -} - -impl pallet_membership::Config for Runtime { - type AddOrigin = EnsureRootOrTwoThirdsCouncil; - type Event = Event; - type MaxMembers = AdvisoryCommitteeMaxMembers; - type MembershipChanged = AdvisoryCommittee; - type MembershipInitialized = AdvisoryCommittee; - type PrimeOrigin = EnsureRootOrTwoThirdsCouncil; - type RemoveOrigin = EnsureRootOrTwoThirdsCouncil; - type ResetOrigin = EnsureRootOrTwoThirdsCouncil; - type SwapOrigin = EnsureRootOrTwoThirdsCouncil; - type WeightInfo = weights::pallet_membership::WeightInfo; -} - -impl pallet_membership::Config for Runtime { - type AddOrigin = EnsureRootOrThreeFourthsCouncil; - type Event = Event; - type MaxMembers = CouncilMaxMembers; - type MembershipChanged = Council; - type MembershipInitialized = Council; - type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; - type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; - type ResetOrigin = EnsureRootOrThreeFourthsCouncil; - type SwapOrigin = EnsureRootOrThreeFourthsCouncil; - type WeightInfo = weights::pallet_membership::WeightInfo; -} - -impl pallet_membership::Config for Runtime { - type AddOrigin = EnsureRootOrTwoThirdsCouncil; - type Event = Event; - type MaxMembers = TechnicalCommitteeMaxMembers; - type MembershipChanged = TechnicalCommittee; - type MembershipInitialized = TechnicalCommittee; - type PrimeOrigin = EnsureRootOrTwoThirdsCouncil; - type RemoveOrigin = EnsureRootOrTwoThirdsCouncil; - type ResetOrigin = EnsureRootOrTwoThirdsCouncil; - type SwapOrigin = EnsureRootOrTwoThirdsCouncil; - type WeightInfo = weights::pallet_membership::WeightInfo; -} - -impl pallet_multisig::Config for Runtime { - type Event = Event; - type Call = Call; - type Currency = Balances; - type DepositBase = DepositBase; - type DepositFactor = DepositFactor; - type MaxSignatories = ConstU16<100>; - type WeightInfo = weights::pallet_multisig::WeightInfo; -} - -impl pallet_preimage::Config for Runtime { - type WeightInfo = weights::pallet_preimage::WeightInfo; - type Event = Event; - type Currency = Balances; - type ManagerOrigin = EnsureRoot; - type MaxSize = PreimageMaxSize; - type BaseDeposit = PreimageBaseDeposit; - type ByteDeposit = PreimageByteDeposit; -} - -impl InstanceFilter for ProxyType { - fn filter(&self, c: &Call) -> bool { - match self { - ProxyType::Any => true, - ProxyType::CancelProxy => { - matches!(c, Call::Proxy(pallet_proxy::Call::reject_announcement { .. })) - } - ProxyType::Governance => matches!( - c, - Call::Democracy(..) - | Call::Council(..) - | Call::TechnicalCommittee(..) - | Call::AdvisoryCommittee(..) - | Call::Treasury(..) - ), - #[cfg(feature = "parachain")] - ProxyType::Staking => matches!(c, Call::ParachainStaking(..)), - #[cfg(not(feature = "parachain"))] - ProxyType::Staking => false, - } - } - - fn is_superset(&self, o: &Self) -> bool { - match (self, o) { - (x, y) if x == y => true, - (ProxyType::Any, _) => true, - (_, ProxyType::Any) => false, - _ => false, - } - } -} - -impl pallet_proxy::Config for Runtime { - type Event = Event; - type Call = Call; - type Currency = Balances; - type ProxyType = ProxyType; - type ProxyDepositBase = ProxyDepositBase; - type ProxyDepositFactor = ProxyDepositFactor; - type MaxProxies = ConstU32<32>; - type WeightInfo = weights::pallet_proxy::WeightInfo; - type MaxPending = ConstU32<32>; - type CallHasher = BlakeTwo256; - type AnnouncementDepositBase = AnnouncementDepositBase; - type AnnouncementDepositFactor = AnnouncementDepositFactor; -} - -impl pallet_randomness_collective_flip::Config for Runtime {} - -impl pallet_scheduler::Config for Runtime { - type Event = Event; - type Origin = Origin; - type PalletsOrigin = OriginCaller; - type Call = Call; - type MaximumWeight = MaximumSchedulerWeight; - type ScheduleOrigin = EnsureRoot; - type MaxScheduledPerBlock = MaxScheduledPerBlock; - type WeightInfo = weights::pallet_scheduler::WeightInfo; - type OriginPrivilegeCmp = EqualPrivilegeOnly; - type PreimageProvider = Preimage; - type NoPreimagePostponement = NoPreimagePostponement; -} - -#[cfg(not(feature = "without-sudo"))] -impl pallet_sudo::Config for Runtime { - type Call = Call; - type Event = Event; -} - -impl pallet_timestamp::Config for Runtime { - type MinimumPeriod = MinimumPeriod; - type Moment = u64; - #[cfg(feature = "parachain")] - type OnTimestampSet = (); - #[cfg(not(feature = "parachain"))] - type OnTimestampSet = Aura; - type WeightInfo = weights::pallet_timestamp::WeightInfo; -} - -impl pallet_transaction_payment::Config for Runtime { - type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; - type LengthToFee = ConstantMultiplier; - type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; - type OperationalFeeMultiplier = OperationalFeeMultiplier; - type WeightToFee = IdentityFee; -} - -impl pallet_treasury::Config for Runtime { - type ApproveOrigin = EnsureRootOrTwoThirdsCouncil; - type Burn = Burn; - type BurnDestination = (); - type Currency = Balances; - type Event = Event; - type MaxApprovals = MaxApprovals; - type OnSlash = (); - type PalletId = TreasuryPalletId; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; - type RejectOrigin = EnsureRootOrTwoThirdsCouncil; - type SpendFunds = (); - type SpendPeriod = SpendPeriod; - type WeightInfo = weights::pallet_treasury::WeightInfo; -} - -impl pallet_utility::Config for Runtime { - type Event = Event; - type Call = Call; - type PalletsOrigin = OriginCaller; - type WeightInfo = weights::pallet_utility::WeightInfo; -} - -impl pallet_vesting::Config for Runtime { - type Event = Event; - type Currency = Balances; - type BlockNumberToBalance = sp_runtime::traits::ConvertInto; - type MinVestedTransfer = MinVestedTransfer; - type WeightInfo = pallet_vesting::weights::SubstrateWeight; // weights::pallet_vesting::WeightInfo; - - // `VestingInfo` encode length is 36bytes. 28 schedules gets encoded as 1009 bytes, which is the - // highest number of schedules that encodes less than 2^10. - const MAX_VESTING_SCHEDULES: u32 = 28; -} - -#[cfg(feature = "parachain")] -impl parachain_info::Config for Runtime {} - -impl zrml_authorized::Config for Runtime { - type Event = Event; - type MarketCommons = MarketCommons; - type PalletId = AuthorizedPalletId; - type WeightInfo = zrml_authorized::weights::WeightInfo; -} - -impl zrml_court::Config for Runtime { - type CourtCaseDuration = CourtCaseDuration; - type Event = Event; - type MarketCommons = MarketCommons; - type PalletId = CourtPalletId; - type Random = RandomnessCollectiveFlip; - type StakeWeight = StakeWeight; - type TreasuryPalletId = TreasuryPalletId; - type WeightInfo = zrml_court::weights::WeightInfo; -} - -impl zrml_liquidity_mining::Config for Runtime { - type Event = Event; - type MarketCommons = MarketCommons; - type MarketId = MarketId; - type PalletId = LiquidityMiningPalletId; - type WeightInfo = zrml_liquidity_mining::weights::WeightInfo; -} - -impl zrml_market_commons::Config for Runtime { - type Currency = Balances; - type MarketId = MarketId; - type Timestamp = Timestamp; -} - -// NoopLiquidityMining implements LiquidityMiningPalletApi with no-ops. -// Has to be public because it will be exposed by Runtime. -pub struct NoopLiquidityMining; - -impl zrml_liquidity_mining::LiquidityMiningPalletApi for NoopLiquidityMining { - type AccountId = AccountId; - type Balance = Balance; - type BlockNumber = BlockNumber; - type MarketId = MarketId; - - fn add_shares(_: Self::AccountId, _: Self::MarketId, _: Self::Balance) {} - - fn distribute_market_incentives( - _: &Self::MarketId, - ) -> frame_support::pallet_prelude::DispatchResult { - Ok(()) - } - - fn remove_shares(_: &Self::AccountId, _: &Self::MarketId, _: Self::Balance) {} -} - -impl zrml_prediction_markets::Config for Runtime { - type AdvisoryBond = AdvisoryBond; - type ApprovalOrigin = EnsureRootOrHalfAdvisoryCommittee; - type Authorized = Authorized; - type Court = Court; - type CloseOrigin = EnsureRootOrTwoThirdsAdvisoryCommittee; - type DestroyOrigin = EnsureRootOrAllAdvisoryCommittee; - type DisputeBond = DisputeBond; - type DisputeFactor = DisputeFactor; - type DisputePeriod = DisputePeriod; - type Event = Event; - // LiquidityMining is currently unstable. - // NoopLiquidityMining will be applied only to mainnet once runtimes are separated. - type LiquidityMining = NoopLiquidityMining; - // type LiquidityMining = LiquidityMining; - type MarketCommons = MarketCommons; - type MaxCategories = MaxCategories; - type MaxDisputes = MaxDisputes; - type MaxSubsidyPeriod = MaxSubsidyPeriod; - type MaxMarketPeriod = MaxMarketPeriod; - type MinCategories = MinCategories; - type MinSubsidyPeriod = MinSubsidyPeriod; - type OracleBond = OracleBond; - type PalletId = PmPalletId; - type ReportingPeriod = ReportingPeriod; - type ResolveOrigin = EnsureRoot; - type AssetManager = AssetManager; - type SimpleDisputes = SimpleDisputes; - type Swaps = Swaps; - type ValidityBond = ValidityBond; - type WeightInfo = zrml_prediction_markets::weights::WeightInfo; -} - -impl zrml_rikiddo::Config for Runtime { - type Timestamp = Timestamp; - type Balance = Balance; - type FixedTypeU = FixedU128; - type FixedTypeS = FixedI128; - type BalanceFractionalDecimals = BalanceFractionalDecimals; - type PoolId = PoolId; - type Rikiddo = RikiddoSigmoidMV< - Self::FixedTypeU, - Self::FixedTypeS, - FeeSigmoid, - EmaMarketVolume, - >; -} - -impl zrml_simple_disputes::Config for Runtime { - type Event = Event; - type MarketCommons = MarketCommons; - type PalletId = SimpleDisputesPalletId; -} - -impl zrml_swaps::Config for Runtime { - type Event = Event; - type ExitFee = ExitFee; - type FixedTypeU = FixedU128; - type FixedTypeS = FixedI128; - // LiquidityMining is currently unstable. - // NoopLiquidityMining will be applied only to mainnet once runtimes are separated. - type LiquidityMining = NoopLiquidityMining; - // type LiquidityMining = LiquidityMining; - type MarketCommons = MarketCommons; - type MarketId = MarketId; - type MinAssets = MinAssets; - type MaxAssets = MaxAssets; - type MaxInRatio = MaxInRatio; - type MaxOutRatio = MaxOutRatio; - type MaxSwapFee = MaxSwapFee; - type MaxTotalWeight = MaxTotalWeight; - type MaxWeight = MaxWeight; - type MinLiquidity = MinLiquidity; - type MinSubsidy = MinSubsidy; - type MinSubsidyPerAccount = MinSubsidyPerAccount; - type MinWeight = MinWeight; - type PalletId = SwapsPalletId; - type RikiddoSigmoidFeeMarketEma = RikiddoSigmoidFeeMarketEma; - type AssetManager = AssetManager; - type WeightInfo = zrml_swaps::weights::WeightInfo; -} - -impl zrml_styx::Config for Runtime { - type Event = Event; - type SetBurnAmountOrigin = EnsureRootOrHalfCouncil; - type Currency = Balances; - type WeightInfo = zrml_styx::weights::WeightInfo; -} - -// Implementation of runtime's apis -impl_runtime_apis! { - #[cfg(feature = "parachain")] - impl cumulus_primitives_core::CollectCollationInfo for Runtime { - fn collect_collation_info( - header: &::Header - ) -> cumulus_primitives_core::CollationInfo { - ParachainSystem::collect_collation_info(header) - } - } - - #[cfg(feature = "parachain")] - // Required to satisify trait bounds at the client implementation. - impl nimbus_primitives::AuthorFilterAPI for Runtime { - fn can_author(_: NimbusId, _: u32, _: &::Header) -> bool { - panic!("AuthorFilterAPI is no longer supported. Please update your client.") - } - } - - #[cfg(feature = "parachain")] - impl nimbus_primitives::NimbusApi for Runtime { - fn can_author( - author: nimbus_primitives::NimbusId, - slot: u32, - parent_header: &::Header - ) -> bool { - - // Ensure that an update is enforced when we are close to maximum block number - let block_number = if let Some(bn) = parent_header.number.checked_add(1) { - bn - } else { - log::error!("ERROR: No block numbers left"); - return false; - }; - - use frame_support::traits::OnInitialize; - System::initialize( - &block_number, - &parent_header.hash(), - &parent_header.digest, - ); - RandomnessCollectiveFlip::on_initialize(block_number); - - // Because the staking solution calculates the next staking set at the beginning - // of the first block in the new round, the only way to accurately predict the - // authors is to compute the selection during prediction. - if parachain_staking::Pallet::::round().should_update(block_number) { - // get author account id - use nimbus_primitives::AccountLookup; - let author_account_id = if let Some(account) = - pallet_author_mapping::Pallet::::lookup_account(&author) { - account - } else { - // return false if author mapping not registered like in can_author impl - return false - }; - // predict eligibility post-selection by computing selection results now - let (eligible, _) = - pallet_author_slot_filter::compute_pseudo_random_subset::( - parachain_staking::Pallet::::compute_top_candidates(), - &slot - ); - eligible.contains(&author_account_id) - } else { - AuthorInherent::can_author(&author, &slot) - } - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{list_benchmark, baseline::Pallet as BaselineBench, Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use orml_benchmarking::list_benchmark as orml_list_benchmark; - - let mut list = Vec::::new(); - - list_benchmark!(list, extra, frame_benchmarking, BaselineBench::); - list_benchmark!(list, extra, frame_system, SystemBench::); - orml_list_benchmark!(list, extra, orml_currencies, benchmarking::currencies); - orml_list_benchmark!(list, extra, orml_tokens, benchmarking::tokens); - list_benchmark!(list, extra, pallet_balances, Balances); - list_benchmark!(list, extra, pallet_collective, AdvisoryCommittee); - list_benchmark!(list, extra, pallet_democracy, Democracy); - list_benchmark!(list, extra, pallet_identity, Identity); - list_benchmark!(list, extra, pallet_membership, AdvisoryCommitteeMembership); - list_benchmark!(list, extra, pallet_multisig, MultiSig); - list_benchmark!(list, extra, pallet_preimage, Preimage); - list_benchmark!(list, extra, pallet_proxy, Proxy); - list_benchmark!(list, extra, pallet_scheduler, Scheduler); - list_benchmark!(list, extra, pallet_timestamp, Timestamp); - list_benchmark!(list, extra, pallet_treasury, Treasury); - list_benchmark!(list, extra, pallet_utility, Utility); - list_benchmark!(list, extra, pallet_vesting, Vesting); - list_benchmark!(list, extra, zrml_swaps, Swaps); - list_benchmark!(list, extra, zrml_authorized, Authorized); - list_benchmark!(list, extra, zrml_court, Court); - list_benchmark!(list, extra, zrml_prediction_markets, PredictionMarkets); - list_benchmark!(list, extra, zrml_liquidity_mining, LiquidityMining); - list_benchmark!(list, extra, zrml_styx, Styx); - - cfg_if::cfg_if! { - if #[cfg(feature = "parachain")] { - list_benchmark!(list, extra, cumulus_pallet_xcmp_queue, XcmpQueue); - list_benchmark!(list, extra, pallet_author_mapping, AuthorMapping); - list_benchmark!(list, extra, pallet_author_slot_filter, AuthorFilter); - list_benchmark!(list, extra, parachain_staking, ParachainStaking); - list_benchmark!(list, extra, pallet_crowdloan_rewards, Crowdloan); - } else { - list_benchmark!(list, extra, pallet_grandpa, Grandpa); - } - } - - (list, AllPalletsWithSystem::storage_info()) - } - - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig, - ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{ - add_benchmark, baseline::{Pallet as BaselineBench, Config as BaselineConfig}, vec, BenchmarkBatch, Benchmarking, TrackedStorageKey, Vec - }; - use frame_system_benchmarking::Pallet as SystemBench; - use orml_benchmarking::{add_benchmark as orml_add_benchmark}; - - impl frame_system_benchmarking::Config for Runtime {} - impl BaselineConfig for Runtime {} - - let whitelist: Vec = vec![ - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac") - .to_vec() - .into(), - hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80") - .to_vec() - .into(), - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a") - .to_vec() - .into(), - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850") - .to_vec() - .into(), - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7") - .to_vec() - .into(), - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da946c154ffd9992e395af90b5b13cc6f295c77033fce8a9045824a6690bbf99c6db269502f0a8d1d2a008542d5690a0749").to_vec().into(), - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(), - ]; - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - - add_benchmark!(params, batches, frame_benchmarking, BaselineBench::); - add_benchmark!(params, batches, frame_system, SystemBench::); - orml_add_benchmark!(params, batches, orml_currencies, benchmarking::currencies); - orml_add_benchmark!(params, batches, orml_tokens, benchmarking::tokens); - add_benchmark!(params, batches, pallet_balances, Balances); - add_benchmark!(params, batches, pallet_collective, AdvisoryCommittee); - add_benchmark!(params, batches, pallet_democracy, Democracy); - add_benchmark!(params, batches, pallet_identity, Identity); - add_benchmark!(params, batches, pallet_membership, AdvisoryCommitteeMembership); - add_benchmark!(params, batches, pallet_multisig, MultiSig); - add_benchmark!(params, batches, pallet_preimage, Preimage); - add_benchmark!(params, batches, pallet_proxy, Proxy); - add_benchmark!(params, batches, pallet_scheduler, Scheduler); - add_benchmark!(params, batches, pallet_timestamp, Timestamp); - add_benchmark!(params, batches, pallet_treasury, Treasury); - add_benchmark!(params, batches, pallet_utility, Utility); - add_benchmark!(params, batches, pallet_vesting, Vesting); - add_benchmark!(params, batches, zrml_swaps, Swaps); - add_benchmark!(params, batches, zrml_authorized, Authorized); - add_benchmark!(params, batches, zrml_court, Court); - add_benchmark!(params, batches, zrml_prediction_markets, PredictionMarkets); - add_benchmark!(params, batches, zrml_liquidity_mining, LiquidityMining); - add_benchmark!(params, batches, zrml_styx, Styx); - - - cfg_if::cfg_if! { - if #[cfg(feature = "parachain")] { - add_benchmark!(params, batches, cumulus_pallet_xcmp_queue, XcmpQueue); - add_benchmark!(params, batches, pallet_author_mapping, AuthorMapping); - add_benchmark!(params, batches, pallet_author_slot_filter, AuthorFilter); - add_benchmark!(params, batches, parachain_staking, ParachainStaking); - add_benchmark!(params, batches, pallet_crowdloan_rewards, Crowdloan); - } else { - add_benchmark!(params, batches, pallet_grandpa, Grandpa); - } - } - - if batches.is_empty() { - return Err("Benchmark not found for this pallet.".into()); - } - Ok(batches) - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } - - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - } - - impl sp_api::Core for Runtime { - fn execute_block(block: Block) { - Executive::execute_block(block) - } - - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) - } - - fn version() -> RuntimeVersion { - VERSION - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - } - - #[cfg(not(feature = "parachain"))] - impl sp_consensus_aura::AuraApi for Runtime { - fn authorities() -> Vec { - Aura::authorities().into_inner() - } - - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) - } - } - - #[cfg(not(feature = "parachain"))] - impl sp_finality_grandpa::GrandpaApi for Runtime { - fn current_set_id() -> pallet_grandpa::fg_primitives::SetId { - Grandpa::current_set_id() - } - - fn generate_key_ownership_proof( - _set_id: pallet_grandpa::fg_primitives::SetId, - _authority_id: pallet_grandpa::AuthorityId, - ) -> Option { - None - } - - fn grandpa_authorities() -> pallet_grandpa::AuthorityList { - Grandpa::grandpa_authorities() - } - - fn submit_report_equivocation_unsigned_extrinsic( - _equivocation_proof: pallet_grandpa::fg_primitives::EquivocationProof< - ::Hash, - sp_runtime::traits::NumberFor, - >, - _key_owner_proof: pallet_grandpa::fg_primitives::OpaqueKeyOwnershipProof, - ) -> Option<()> { - None - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_session::SessionKeys for Runtime { - fn decode_session_keys(encoded: Vec) -> Option, KeyTypeId)>> { - opaque::SessionKeys::decode_into_raw_public_keys(&encoded) - } - - fn generate_session_keys(seed: Option>) -> Vec { - opaque::SessionKeys::generate(seed) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl zrml_swaps_runtime_api::SwapsApi - for Runtime - { - fn get_spot_price( - pool_id: PoolId, - asset_in: Asset, - asset_out: Asset, - ) -> SerdeWrapper { - SerdeWrapper(Swaps::get_spot_price(pool_id, asset_in, asset_out).ok().unwrap_or(0)) - } - - fn pool_account_id(pool_id: PoolId) -> AccountId { - Swaps::pool_account_id(pool_id) - } - - fn pool_shares_id(pool_id: PoolId) -> Asset> { - Asset::PoolShare(SerdeWrapper(pool_id)) - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade() -> (frame_support::weights::Weight, frame_support::weights::Weight) { - log::info!("try-runtime::on_runtime_upgrade."); - let weight = Executive::try_runtime_upgrade().unwrap(); - (weight, RuntimeBlockWeights::get().max_block) - } - - fn execute_block_no_check(block: Block) -> frame_support::weights::Weight { - Executive::execute_block_no_check(block) - } - } -} - -// Check the timestamp and parachain inherents -#[cfg(feature = "parachain")] -struct CheckInherents; - -#[cfg(feature = "parachain")] -impl cumulus_pallet_parachain_system::CheckInherents for CheckInherents { - fn check_inherents( - block: &Block, - relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof, - ) -> sp_inherents::CheckInherentsResult { - let relay_chain_slot = relay_state_proof - .read_slot() - .expect("Could not read the relay chain slot from the proof"); - - let inherent_data = - cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration( - relay_chain_slot, - core::time::Duration::from_secs(6), - ) - .create_inherent_data() - .expect("Could not create the timestamp inherent data"); - - inherent_data.check_extrinsics(block) - } -} - -// Nimbus's Executive wrapper allows relay validators to verify the seal digest -#[cfg(feature = "parachain")] -cumulus_pallet_parachain_system::register_validate_block! { - Runtime = Runtime, - BlockExecutor = pallet_author_inherent::BlockExecutor::, - CheckInherents = CheckInherents, -} - -#[cfg(feature = "std")] -pub fn native_version() -> NativeVersion { - NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } -} - -// Accounts protected from being deleted due to a too low amount of funds. -pub struct DustRemovalWhitelist; - -impl Contains for DustRemovalWhitelist -where - frame_support::PalletId: AccountIdConversion, -{ - fn contains(ai: &AccountId) -> bool { - let pallets = vec![ - AuthorizedPalletId::get(), - CourtPalletId::get(), - LiquidityMiningPalletId::get(), - PmPalletId::get(), - SimpleDisputesPalletId::get(), - SwapsPalletId::get(), - ]; - - if let Some(pallet_id) = frame_support::PalletId::try_from_sub_account::(ai) { - return pallets.contains(&pallet_id.0); - } - - for pallet_id in pallets { - let pallet_acc: AccountId = pallet_id.into_account(); - - if pallet_acc == *ai { - return true; - } - } - - false - } -} diff --git a/runtime/src/opaque.rs b/runtime/src/opaque.rs deleted file mode 100644 index eb7f0aa9f..000000000 --- a/runtime/src/opaque.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! 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. - -use crate::Header; -use alloc::vec::Vec; -use sp_runtime::{generic, impl_opaque_keys}; - -pub type Block = generic::Block; - -#[cfg(feature = "parachain")] -impl_opaque_keys! { - pub struct SessionKeys { - pub nimbus: crate::AuthorInherent, - } -} - -#[cfg(not(feature = "parachain"))] -impl_opaque_keys! { - pub struct SessionKeys { - pub aura: crate::Aura, - pub grandpa: crate::Grandpa, - } -} diff --git a/runtime/src/tests/mod.rs b/runtime/src/tests/mod.rs deleted file mode 100644 index 22ea2d40e..000000000 --- a/runtime/src/tests/mod.rs +++ /dev/null @@ -1 +0,0 @@ -mod multiplier; diff --git a/runtime/src/tests/multiplier.rs b/runtime/src/tests/multiplier.rs deleted file mode 100644 index b56cd3432..000000000 --- a/runtime/src/tests/multiplier.rs +++ /dev/null @@ -1,88 +0,0 @@ -#[cfg(test)] -mod multiplier_tests { - use crate::parameters::{MinimumMultiplier, SlowAdjustingFeeUpdate, TargetBlockFullness}; - use frame_support::{ - parameter_types, - weights::{DispatchClass, Weight}, - }; - use sp_core::H256; - use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, Convert, IdentityLookup}, - Perbill, - }; - - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; - type Block = frame_system::mocking::MockBlock; - - frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event} - } - ); - - parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const AvailableBlockRatio: Perbill = Perbill::one(); - pub BlockLength: frame_system::limits::BlockLength = - frame_system::limits::BlockLength::max(2 * 1024); - pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); - } - - impl frame_system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; - type BlockWeights = BlockWeights; - type BlockLength = (); - type DbWeight = (); - type Origin = Origin; - type Index = u64; - type BlockNumber = u64; - type Call = Call; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; - } - - fn run_with_system_weight(w: Weight, mut assertions: F) - where - F: FnMut(), - { - let mut t: sp_io::TestExternalities = - frame_system::GenesisConfig::default().build_storage::().unwrap().into(); - t.execute_with(|| { - System::set_block_consumed_resources(w, 0); - assertions() - }); - } - - #[test] - fn multiplier_can_grow_from_zero() { - let minimum_multiplier = MinimumMultiplier::get(); - let target = TargetBlockFullness::get() - * BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap(); - // if the min is too small, then this will not change, and we are doomed forever. - // the weight is 1/100th bigger than target. - run_with_system_weight(target * 101 / 100, || { - let next = SlowAdjustingFeeUpdate::::convert(minimum_multiplier); - assert!(next > minimum_multiplier, "{:?} !>= {:?}", next, minimum_multiplier); - }) - } -} diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml new file mode 100644 index 000000000..6f7dbbdd8 --- /dev/null +++ b/runtime/zeitgeist/Cargo.toml @@ -0,0 +1,337 @@ +[build-dependencies] +substrate-wasm-builder = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } + +[dependencies] +frame-executive = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +frame-system-rpc-runtime-api = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +orml-benchmarking = { branch = "2022-06-v0.9.19", default-features = false, optional = true, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-currencies = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-tokens = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-traits = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +pallet-balances = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-collective = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-democracy = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-identity = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-membership = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-multisig = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-preimage = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-proxy = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-randomness-collective-flip = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-scheduler = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-timestamp = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-transaction-payment = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-transaction-payment-rpc-runtime-api = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-treasury = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-utility = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-vesting = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +parity-scale-codec = { default-features = false, features = ["derive", "max-encoded-len"], version = "3.0.0" } +scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +sp-api = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-block-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-core = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-inherents = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-offchain = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-session = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-transaction-pool = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-version = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +substrate-fixed = { default-features = false, features = ["serde"], git = "https://github.com/encointer/substrate-fixed" } + +# Try-Runtime + +frame-try-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, optional = true, git = "https://github.com/purestake/substrate"} + +# Benchmark + +frame-benchmarking = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate", optional = true } +frame-system-benchmarking = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate", optional = true } + +# Cumulus + +cumulus-pallet-dmp-queue = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } +cumulus-pallet-parachain-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } +cumulus-pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } +cumulus-pallet-xcmp-queue = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } +cumulus-primitives-core = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } +cumulus-primitives-timestamp = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } +cumulus-primitives-utility = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } +parachain-info = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } + +# Parachain + +nimbus-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/nimbus", optional = true } +pallet-author-inherent = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/nimbus", optional = true } +pallet-author-mapping = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", default-features = false, git = "https://github.com/purestake/moonbeam", optional = true } +pallet-author-slot-filter = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/nimbus", optional = true } +pallet-crowdloan-rewards = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/crowdloan-rewards", optional = true } +parachain-staking = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", default-features = false, git = "https://github.com/purestake/moonbeam", optional = true } + +# Polkadot + +pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-parachain = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +xcm-executor = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } + +# Standalone + +pallet-aura = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +pallet-grandpa = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-consensus-aura = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +sp-finality-grandpa = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } + +# Utility +cfg-if = { version = "1.0.0" } +hex-literal = { default-features = false, optional = true, version = "0.3.4" } +log = { version = "0.4.8", default-features = false, optional = true } + +# Zeitgeist + +common-runtime = { default-features = false, path = "../common" } +zeitgeist-primitives = { default-features = false, path = "../../primitives" } +zrml-authorized = { default-features = false, path = "../../zrml/authorized" } +zrml-court = { default-features = false, path = "../../zrml/court" } +zrml-liquidity-mining = { default-features = false, path = "../../zrml/liquidity-mining" } +zrml-market-commons = { default-features = false, path = "../../zrml/market-commons" } +zrml-prediction-markets = { default-features = false, path = "../../zrml/prediction-markets" } +zrml-rikiddo = { default-features = false, path = "../../zrml/rikiddo" } +zrml-simple-disputes = { default-features = false, path = "../../zrml/simple-disputes" } +zrml-styx = { default-features = false, path = "../../zrml/styx" } +zrml-swaps = { default-features = false, path = "../../zrml/swaps" } +zrml-swaps-runtime-api = { default-features = false, path = "../../zrml/swaps/runtime-api" } + +[dev-dependencies] +sp-io = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } + +[features] +default = ["std"] +parachain = [ + # Cumulus + + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-xcm", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-timestamp", + "cumulus-primitives-utility", + "parachain-info", + + # Parachain + + "nimbus-primitives", + "pallet-author-inherent", + "pallet-author-mapping", + "pallet-author-slot-filter", + "pallet-crowdloan-rewards", + "parachain-staking", + + # Polkadot + + "pallet-xcm", + "polkadot-parachain", + "xcm-builder", + "xcm-executor", + "xcm", + + # Misc + + "common-runtime/parachain", + "log", +] +runtime-benchmarks = [ + "cumulus-pallet-xcmp-queue/runtime-benchmarks", + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system-benchmarking", + "frame-system/runtime-benchmarks", + "hex-literal", + "orml-tokens/runtime-benchmarks", + "orml-benchmarking", + "pallet-author-mapping/runtime-benchmarks", + "pallet-author-slot-filter/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-collective/runtime-benchmarks", + "pallet-crowdloan-rewards/runtime-benchmarks", + "pallet-democracy/runtime-benchmarks", + "pallet-grandpa/runtime-benchmarks", + "pallet-identity/runtime-benchmarks", + "pallet-membership/runtime-benchmarks", + "pallet-multisig/runtime-benchmarks", + "pallet-preimage/runtime-benchmarks", + "pallet-proxy/runtime-benchmarks", + "pallet-scheduler/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-treasury/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "pallet-vesting/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "parachain-staking/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "zrml-authorized/runtime-benchmarks", + "zrml-court/runtime-benchmarks", + "zrml-liquidity-mining/runtime-benchmarks", + "zrml-prediction-markets/runtime-benchmarks", + "zrml-simple-disputes/runtime-benchmarks", + "zrml-styx/runtime-benchmarks", + "zrml-swaps/runtime-benchmarks", +] +std = [ + "frame-executive/std", + "frame-support/std", + "frame-system-rpc-runtime-api/std", + "frame-system/std", + "hex-literal", + "log/std", + "orml-benchmarking/std", + "orml-currencies/std", + "orml-tokens/std", + "orml-traits/std", + "pallet-balances/std", + "pallet-collective/std", + "pallet-democracy/std", + "pallet-identity/std", + "pallet-membership/std", + "pallet-multisig/std", + "pallet-preimage/std", + "pallet-proxy/std", + "pallet-randomness-collective-flip/std", + "pallet-scheduler/std", + "pallet-timestamp/std", + "pallet-transaction-payment-rpc-runtime-api/std", + "pallet-transaction-payment/std", + "pallet-treasury/std", + "pallet-utility/std", + "pallet-vesting/std", + "parity-scale-codec/std", + "scale-info/std", + "sp-api/std", + "sp-block-builder/std", + "sp-core/std", + "sp-inherents/std", + "sp-offchain/std", + "sp-runtime/std", + "sp-session/std", + "sp-transaction-pool/std", + "sp-version/std", + "substrate-fixed/std", + + # Try-Runtime + "frame-try-runtime/std", + + # Benchmark + + "frame-benchmarking?/std", + "frame-system-benchmarking?/std", + + # Cumulus + + "cumulus-pallet-dmp-queue?/std", + "cumulus-pallet-parachain-system?/std", + "cumulus-pallet-xcm?/std", + "cumulus-pallet-xcmp-queue?/std", + "cumulus-primitives-core?/std", + "cumulus-primitives-timestamp?/std", + "cumulus-primitives-utility?/std", + "parachain-info?/std", + + # Parachain + + "nimbus-primitives?/std", + "pallet-author-inherent?/std", + "pallet-author-mapping?/std", + "pallet-author-slot-filter?/std", + "pallet-crowdloan-rewards?/std", + "parachain-staking?/std", + + # Polkadot + + "pallet-xcm?/std", + "polkadot-parachain?/std", + "xcm-builder?/std", + "xcm-executor?/std", + "xcm?/std", + + # Standalone + + "pallet-aura/std", + "pallet-grandpa/std", + "sp-consensus-aura/std", + "sp-finality-grandpa/std", + + # Zeitgeist + + "zeitgeist-primitives/std", + "zrml-authorized/std", + "zrml-court/std", + "zrml-liquidity-mining/std", + "zrml-market-commons/std", + "zrml-prediction-markets/std", + "zrml-rikiddo/std", + "zrml-simple-disputes/std", + "zrml-swaps-runtime-api/std", + "zrml-styx/std", + "zrml-swaps/std", +] +try-runtime = [ + "frame-executive/try-runtime", + "frame-try-runtime", + + # For every pallet in the runtime include try-runtime + + # System runtime pallets + "frame-system/try-runtime", + "pallet-timestamp/try-runtime", + "pallet-randomness-collective-flip/try-runtime", + "pallet-scheduler/try-runtime", + "pallet-preimage/try-runtime", + + # Money runtime pallets + "pallet-balances/try-runtime", + "pallet-transaction-payment/try-runtime", + "pallet-treasury/try-runtime", + "pallet-vesting/try-runtime", + "pallet-multisig/try-runtime", + + # Governance runtime pallets + "pallet-democracy/try-runtime", + "pallet-collective/try-runtime", + "pallet-membership/try-runtime", + + # Other Parity runtime pallets + "pallet-identity/try-runtime", + "pallet-utility/try-runtime", + + # ORML runtime pallets + "orml-currencies/try-runtime", + "orml-tokens/try-runtime", + + # Zeitgeist runtime pallets + "zrml-authorized/try-runtime", + "zrml-court/try-runtime", + "zrml-liquidity-mining/try-runtime", + "zrml-market-commons/try-runtime", + "zrml-prediction-markets/try-runtime", + "zrml-rikiddo/try-runtime", + "zrml-simple-disputes/try-runtime", + "zrml-styx/try-runtime", + "zrml-swaps/try-runtime", + + # Parachain + "pallet-author-mapping?/try-runtime", + "pallet-author-slot-filter?/try-runtime", + "parachain-staking?/try-runtime", +] + +[package] +authors = ["Zeitgeist PM "] +edition = "2021" +name = "zeitgeist-runtime" +version = "0.3.4" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] diff --git a/runtime/zeitgeist/build.rs b/runtime/zeitgeist/build.rs new file mode 100644 index 000000000..5327cc889 --- /dev/null +++ b/runtime/zeitgeist/build.rs @@ -0,0 +1,5 @@ +use substrate_wasm_builder::WasmBuilder; + +fn main() { + WasmBuilder::new().with_current_project().export_heap_base().import_memory().build() +} diff --git a/runtime/zeitgeist/src/lib.rs b/runtime/zeitgeist/src/lib.rs new file mode 100644 index 000000000..33edc4b20 --- /dev/null +++ b/runtime/zeitgeist/src/lib.rs @@ -0,0 +1,117 @@ +#![cfg_attr(not(feature = "std"), no_std)] +#![recursion_limit = "256"] + +extern crate alloc; + +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +use common_runtime::{ + create_common_benchmark_logic, create_common_tests, create_runtime, create_runtime_api, + create_runtime_with_additional_pallets, decl_common_types, impl_config_traits, +}; +pub use frame_system::{ + Call as SystemCall, CheckEra, CheckGenesis, CheckNonZeroSender, CheckNonce, CheckSpecVersion, + CheckTxVersion, CheckWeight, +}; +#[cfg(feature = "parachain")] +pub use pallet_author_slot_filter::EligibilityValue; + +#[cfg(feature = "parachain")] +pub use crate::parachain_params::*; +pub use crate::parameters::*; +use alloc::vec; +use frame_support::{ + traits::{ConstU16, ConstU32, Contains, EnsureOneOf, EqualPrivilegeOnly, InstanceFilter}, + weights::{constants::RocksDbWeight, ConstantMultiplier, IdentityFee}, +}; +use frame_system::EnsureRoot; +use pallet_collective::{EnsureProportionAtLeast, PrimeDefaultVote}; +use pallet_transaction_payment::ChargeTransactionPayment; +use sp_runtime::traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256}; +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use substrate_fixed::{types::extra::U33, FixedI128, FixedU128}; +use zeitgeist_primitives::{constants::*, types::*}; +use zrml_rikiddo::types::{EmaMarketVolume, FeeSigmoid, RikiddoSigmoidMV}; +#[cfg(feature = "parachain")] +use { + frame_support::traits::{Everything, Nothing}, + frame_system::EnsureSigned, + xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, + xcm_config::XcmConfig, +}; + +use frame_support::construct_runtime; + +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + create_runtime_str, + traits::Block as BlockT, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, +}; + +#[cfg(feature = "parachain")] +use nimbus_primitives::{CanAuthor, NimbusId}; +use sp_version::RuntimeVersion; + +#[cfg(feature = "parachain")] +pub mod parachain_params; +pub mod parameters; +#[cfg(feature = "parachain")] +pub mod xcm_config; + +pub const VERSION: RuntimeVersion = RuntimeVersion { + spec_name: create_runtime_str!("zeitgeist"), + impl_name: create_runtime_str!("zeitgeist"), + authoring_version: 1, + spec_version: 38, + impl_version: 1, + apis: RUNTIME_API_VERSIONS, + transaction_version: 15, + state_version: 1, +}; + +#[derive(scale_info::TypeInfo)] +pub struct IsCallable; + +// Currently disables Court, Rikiddo and creation of markets using Court or SimpleDisputes +// dispute mechanism. +impl Contains for IsCallable { + fn contains(call: &Call) -> bool { + use zeitgeist_primitives::types::{ + MarketDisputeMechanism::{Court, SimpleDisputes}, + ScoringRule::RikiddoSigmoidFeeMarketEma, + }; + use zrml_prediction_markets::Call::{create_cpmm_market_and_deploy_assets, create_market}; + + #[allow(clippy::match_like_matches_macro)] + match call { + Call::Court(_) => false, + Call::LiquidityMining(_) => false, + Call::PredictionMarkets(inner_call) => { + match inner_call { + // Disable Rikiddo markets + create_market { scoring_rule: RikiddoSigmoidFeeMarketEma, .. } => false, + // Disable Court & SimpleDisputes dispute resolution mechanism + create_market { dispute_mechanism: Court | SimpleDisputes, .. } => false, + create_cpmm_market_and_deploy_assets { + dispute_mechanism: Court | SimpleDisputes, + .. + } => false, + _ => true, + } + } + _ => true, + } + } +} + +decl_common_types!(); +create_runtime_with_additional_pallets!(); +impl_config_traits!(); +create_runtime_api!(); +create_common_benchmark_logic!(); +create_common_tests!(); diff --git a/runtime/zeitgeist/src/parachain_params.rs b/runtime/zeitgeist/src/parachain_params.rs new file mode 100644 index 000000000..b1331b3bc --- /dev/null +++ b/runtime/zeitgeist/src/parachain_params.rs @@ -0,0 +1,160 @@ +#![allow( + // Constants parameters inside `parameter_types!` already check + // arithmetic operations at compile time + clippy::integer_arithmetic +)] +#![cfg(feature = "parachain")] + +use super::{ + parameters::MAXIMUM_BLOCK_WEIGHT, AccountId, Balances, Origin, ParachainInfo, ParachainSystem, + XcmpQueue, +}; +use frame_support::{match_types, parameter_types, traits::Everything, weights::Weight}; +use pallet_xcm::XcmPassthrough; +use polkadot_parachain::primitives::Sibling; +use sp_runtime::{Perbill, Percent, SaturatedConversion}; +use xcm::latest::{BodyId, Junction, Junctions, MultiLocation, NetworkId}; +use xcm_builder::{ + AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter, + IsConcrete, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, +}; +use zeitgeist_primitives::{ + constants::{BASE, BLOCKS_PER_MINUTE, MICRO}, + types::Balance, +}; + +match_types! { + pub type ParentOrParentsUnitPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Junctions::Here } | + // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } + }; +} +parameter_types! { + // Author-Mapping + /// The amount that should be taken as a security deposit when registering a NimbusId. + pub const CollatorDeposit: Balance = 2 * BASE; + + // Crowdloan + pub const InitializationPayment: Perbill = Perbill::from_percent(30); + pub const Initialized: bool = false; + pub const MaxInitContributorsBatchSizes: u32 = 500; + pub const MinimumReward: Balance = 0; + pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100); + pub const SignatureNetworkIdentifier: &'static [u8] = b"zeitgeist-"; + + // Cumulus and Polkadot + pub Ancestry: MultiLocation = Junction::Parachain(ParachainInfo::parachain_id().into()).into(); + pub const RelayLocation: MultiLocation = MultiLocation::parent(); + // Have to change "Any" to "Kusama" for mainnet once we have separate runtimes + pub const RelayNetwork: NetworkId = NetworkId::Any; + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); + pub UnitWeightCost: Weight = MICRO.saturated_into(); + + // Staking + /// Rounds before the candidate bond increase/decrease can be executed + pub const CandidateBondLessDelay: u32 = 2; + /// Default fixed percent a collator takes off the top of due rewards + pub const DefaultCollatorCommission: Perbill = Perbill::from_percent(20); + /// Blocks per round + pub const DefaultBlocksPerRound: u32 = 2 * BLOCKS_PER_MINUTE as u32; + /// Default percent of inflation set aside for parachain bond every round + pub const DefaultParachainBondReservePercent: Percent = Percent::from_percent(30); + /// Rounds before the delegator bond increase/decrease can be executed + pub const DelegationBondLessDelay: u32 = 2; + /// Rounds before the collator leaving the candidates request can be executed + pub const LeaveCandidatesDelay: u32 = 2; + /// Rounds before the delegator exit can be executed + pub const LeaveDelegatorsDelay: u32 = 2; + /// Maximum bottom delegations per candidate + pub const MaxBottomDelegationsPerCandidate: u32 = 50; + /// Maximum delegations per delegator + pub const MaxDelegationsPerDelegator: u32 = 100; + /// Maximum top delegations per candidate + pub const MaxTopDelegationsPerCandidate: u32 = 300; + /// Minimum round length is 2 minutes + pub const MinBlocksPerRound: u32 = 2 * BLOCKS_PER_MINUTE as u32; + /// Minimum stake required to become a collator + pub const MinCollatorStk: u128 = 64 * BASE; + /// Minimum stake required to be reserved to be a delegator + pub const MinDelegatorStk: u128 = BASE / 2; + /// Minimum collators selected per round, default at genesis and minimum forever after + pub const MinSelectedCandidates: u32 = 8; + /// Rounds before the delegator revocation can be executed + pub const RevokeDelegationDelay: u32 = 2; + /// Rounds before the reward is paid + pub const RewardPaymentDelay: u32 = 2; + + // XCM + pub const MaxInstructions: u32 = 100; +} + +pub type Barrier = ( + TakeWeightCredit, + AllowTopLevelPaidExecutionFrom, + AllowUnpaidExecutionFrom, + // ^^^ Parent and its exec plurality get free execution +); + +/// 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, + // 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. + (), +>; + +/// No local origins on this chain are allowed to dispatch XCM sends/executions. +pub type LocalOriginToLocation = SignedToAccountId32; + +/// 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, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, +); + +/// 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, + // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // recognized. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognized. + SiblingParachainAsNative, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `Origin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = ( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +); diff --git a/runtime/zeitgeist/src/parameters.rs b/runtime/zeitgeist/src/parameters.rs new file mode 100644 index 000000000..de9ad30be --- /dev/null +++ b/runtime/zeitgeist/src/parameters.rs @@ -0,0 +1,158 @@ +#![allow( + // Constants parameters inside `parameter_types!` already check + // arithmetic operations at compile time + clippy::integer_arithmetic +)] + +use super::VERSION; +use frame_support::{ + parameter_types, + weights::{ + constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, + DispatchClass, Weight, + }, + PalletId, +}; +use frame_system::limits::{BlockLength, BlockWeights}; +use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; +use sp_runtime::{traits::AccountIdConversion, FixedPointNumber, Perbill, Permill, Perquintill}; +use sp_version::RuntimeVersion; +use zeitgeist_primitives::{constants::*, types::*}; + +pub(crate) const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); +pub(crate) const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2; +pub(crate) const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); + +parameter_types! { + // Authority + pub const MaxAuthorities: u32 = 32; + + // Collective + // Note: MaxMembers does not influence the pallet logic, but the worst-case weight estimation. + pub const AdvisoryCommitteeMaxMembers: u32 = 100; + pub const AdvisoryCommitteeMaxProposals: u32 = 300; + pub const AdvisoryCommitteeMotionDuration: BlockNumber = 3 * BLOCKS_PER_DAY; + pub const CouncilMaxMembers: u32 = 100; + pub const CouncilMaxProposals: u32 = 100; + pub const CouncilMotionDuration: BlockNumber = 7 * BLOCKS_PER_DAY; + pub const TechnicalCommitteeMaxMembers: u32 = 100; + pub const TechnicalCommitteeMaxProposals: u32 = 64; + pub const TechnicalCommitteeMotionDuration: BlockNumber = 7 * BLOCKS_PER_DAY; + + // Democracy + /// How often (in blocks) new public referenda are launched. + pub const LaunchPeriod: BlockNumber = 5 * BLOCKS_PER_DAY; + /// How often (in blocks) to check for new votes. + pub const VotingPeriod: BlockNumber = 5 * BLOCKS_PER_DAY; + /// Minimum voting period allowed for a fast-track referendum. + pub const FastTrackVotingPeriod: BlockNumber = 3 * BLOCKS_PER_HOUR; + /// The minimum amount to be used as a deposit for a public referendum proposal. + pub const MinimumDeposit: Balance = 100 * BASE; + /// The period between a proposal being approved and enacted. + /// It should generally be a little more than the unstake period to ensure that voting stakers + /// have an opportunity to remove themselves from the system in the case where they are on the + /// losing side of a vote. + pub const EnactmentPeriod: BlockNumber = 2 * BLOCKS_PER_DAY; + /// The minimum period of vote locking. + /// It should be no shorter than enactment period to ensure that in the case of an approval, + /// those successful voters are locked into the consequences that their votes entail. + pub const VoteLockingPeriod: BlockNumber = VotingPeriod::get() + EnactmentPeriod::get(); + /// Period in blocks where an external proposal may not be re-submitted after being vetoed. + pub const CooloffPeriod: BlockNumber = 7 * BLOCKS_PER_DAY; + /// Indicator for whether an emergency origin is even allowed to happen. + pub const InstantAllowed: bool = true; + /// The maximum number of votes for an account. Also used to compute weight, an overly big value + /// can lead to extrinsic with very big weight: see delegate for instance. + pub const MaxVotes: u32 = 100; + /// The maximum number of public proposals that can exist at any time. + pub const MaxProposals: u32 = 100; + + // Identity + pub const BasicDeposit: Balance = 8 * BASE; + pub const FieldDeposit: Balance = 256 * CENT; + pub const MaxAdditionalFields: u32 = 64; + pub const MaxRegistrars: u32 = 8; + pub const MaxSubAccounts: u32 = 64; + pub const SubAccountDeposit: Balance = 2 * BASE; + + // Multisig + // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. + pub const DepositBase: Balance = deposit(1, 88); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); + + // ORML + pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); + + // Preimage + pub const PreimageMaxSize: u32 = 4096 * 1024; + pub PreimageBaseDeposit: Balance = deposit(2, 64); + pub PreimageByteDeposit: Balance = deposit(0, 1); + + // Proxy + // One storage item; key size 32, value size 8; . + pub const ProxyDepositBase: Balance = deposit(1, 8); + // Additional storage item size of 33 bytes. + pub const ProxyDepositFactor: Balance = deposit(0, 33); + pub const AnnouncementDepositBase: Balance = deposit(1, 8); + pub const AnnouncementDepositFactor: Balance = deposit(0, 66); + + // Scheduler + pub MaximumSchedulerWeight: Weight = + Perbill::from_percent(10) * RuntimeBlockWeights::get().max_block; + // No hard limit, used for worst-case weight estimation + pub const MaxScheduledPerBlock: u32 = 50; + pub const NoPreimagePostponement: Option = Some(5 * BLOCKS_PER_MINUTE); + // System + pub const SS58Prefix: u8 = 73; + pub const Version: RuntimeVersion = VERSION; + 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); + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + + // Transaction payment + pub const OperationalFeeMultiplier: u8 = 5; + pub const TransactionByteFee: Balance = 100 * MICRO; + pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(10); + // With a target block time of 12 seconds (7200 blocks per day) + // the weight fees can increase by at most ~21.46% per day, given extreme congestion. + // See https://paritytech.github.io/substrate/master/pallet_transaction_payment/struct.TargetedFeeAdjustment.html for details. + pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(3, 100_000); + // Minimum amount of the multiplier. The test `multiplier_can_grow_from_zero` ensures + // that this value is not too low. + pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000u128); + + // Treasury + pub const Burn: Permill = Permill::from_percent(50); + pub const MaxApprovals: u32 = 100; + pub const ProposalBond: Permill = Permill::from_percent(5); + pub const ProposalBondMinimum: Balance = 10 * BASE; + pub const ProposalBondMaximum: Balance = 500 * BASE; + pub const SpendPeriod: BlockNumber = 24 * BLOCKS_PER_DAY; + pub const TreasuryPalletId: PalletId = PalletId(*b"zge/tsry"); + + // Vesting + pub const MinVestedTransfer: Balance = CENT; +} + +// Parameterized slow adjusting fee updated based on +// https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html#-2.-slow-adjusting-mechanism +pub type SlowAdjustingFeeUpdate = + TargetedFeeAdjustment; diff --git a/runtime/zeitgeist/src/xcm_config.rs b/runtime/zeitgeist/src/xcm_config.rs new file mode 100644 index 000000000..6409c2a80 --- /dev/null +++ b/runtime/zeitgeist/src/xcm_config.rs @@ -0,0 +1,26 @@ +use super::{ + AccountId, Ancestry, Balance, Balances, Barrier, Call, LocalAssetTransactor, MaxInstructions, + PolkadotXcm, RelayLocation, UnitWeightCost, XcmOriginToTransactDispatchOrigin, XcmRouter, +}; +use frame_support::weights::IdentityFee; +use xcm_builder::{FixedWeightBounds, LocationInverter, NativeAsset, UsingComponents}; +use xcm_executor::Config; + +pub struct XcmConfig; + +impl Config for XcmConfig { + type AssetClaims = PolkadotXcm; + type AssetTransactor = LocalAssetTransactor; + type AssetTrap = PolkadotXcm; + type Barrier = Barrier; + type Call = Call; + type IsReserve = NativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + type OriginConverter = XcmOriginToTransactDispatchOrigin; + type ResponseHandler = PolkadotXcm; + type SubscriptionService = PolkadotXcm; + type Trader = UsingComponents, RelayLocation, AccountId, Balances, ()>; + type Weigher = FixedWeightBounds; + type XcmSender = XcmRouter; +} diff --git a/scripts/tests/misc.sh b/scripts/tests/misc.sh index 2233d7957..38abf6e13 100755 --- a/scripts/tests/misc.sh +++ b/scripts/tests/misc.sh @@ -13,7 +13,7 @@ test_package_with_feature primitives std no_runtime_benchmarks=('court' 'market-commons' 'rikiddo') -cargo test --package zeitgeist-runtime --lib -- tests::multiplier::multiplier_tests --nocapture +cargo test --package zeitgeist-runtime --lib -- --nocapture for package in zrml/* do diff --git a/scripts/tests/parachain.sh b/scripts/tests/parachain.sh index 0bd959407..47ea3f798 100755 --- a/scripts/tests/parachain.sh +++ b/scripts/tests/parachain.sh @@ -6,6 +6,7 @@ set -euxo pipefail . "$(dirname "$0")/aux-functions.sh" --source-only -check_package_with_feature runtime std,parachain +check_package_with_feature runtime/battery-station std,parachain +check_package_with_feature runtime/zeitgeist std,parachain check_package_with_feature node default,parachain diff --git a/scripts/tests/standalone.sh b/scripts/tests/standalone.sh index c3f064f1c..def013e50 100755 --- a/scripts/tests/standalone.sh +++ b/scripts/tests/standalone.sh @@ -6,8 +6,11 @@ set -euxo pipefail . "$(dirname "$0")/aux-functions.sh" --source-only -check_package_with_feature runtime std -check_package_with_feature runtime std,runtime-benchmarks +check_package_with_feature runtime/battery-station std +check_package_with_feature runtime/battery-station std,runtime-benchmarks -# check_package_with_feature node default -# check_package_with_feature node default,runtime-benchmarks +check_package_with_feature runtime/zeitgeist std +check_package_with_feature runtime/zeitgeist std,runtime-benchmarks + +check_package_with_feature node default +check_package_with_feature node default,runtime-benchmarks