git.delta.rocks / unique-network / refs/commits / a64769ff6bff

difftreelog

refactor upgrade code for new substrate

Yaroslav Bolyukin2023-10-02parent: #c318883.patch.diff
in: master

39 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -153,11 +153,12 @@
 	) => {{
 		use $runtime::*;
 
-		GenesisConfig {
+		RuntimeGenesisConfig {
 			system: SystemConfig {
 				code: WASM_BINARY
 					.expect("WASM binary was not build, please build it!")
 					.to_vec(),
+				..Default::default()
 			},
 			balances: BalancesConfig {
 				balances: $endowed_accounts
@@ -167,10 +168,6 @@
 					.map(|k| (k, 1 << 100))
 					.collect(),
 			},
-			common: Default::default(),
-			configuration: Default::default(),
-			nonfungible: Default::default(),
-			treasury: Default::default(),
 			tokens: TokensConfig { balances: vec![] },
 			sudo: SudoConfig {
 				key: Some($root_key),
@@ -179,8 +176,8 @@
 			vesting: VestingConfig { vesting: vec![] },
 			parachain_info: ParachainInfoConfig {
 				parachain_id: $id.into(),
+				..Default::default()
 			},
-			parachain_system: Default::default(),
 			collator_selection: CollatorSelectionConfig {
 				invulnerables: $initial_invulnerables
 					.iter()
@@ -200,14 +197,10 @@
 					})
 					.collect(),
 			},
-			aura: Default::default(),
-			aura_ext: Default::default(),
 			evm: EVMConfig {
 				accounts: BTreeMap::new(),
+				..Default::default()
 			},
-			ethereum: EthereumConfig {},
-			polkadot_xcm: Default::default(),
-			transaction_payment: Default::default(),
 			..Default::default()
 		}
 	}};
@@ -224,15 +217,13 @@
 	) => {{
 		use $runtime::*;
 
-		GenesisConfig {
+		RuntimeGenesisConfig {
 			system: SystemConfig {
 				code: WASM_BINARY
 					.expect("WASM binary was not build, please build it!")
 					.to_vec(),
+				..Default::default()
 			},
-			common: Default::default(),
-			configuration: Default::default(),
-			nonfungible: Default::default(),
 			balances: BalancesConfig {
 				balances: $endowed_accounts
 					.iter()
@@ -241,7 +232,6 @@
 					.map(|k| (k, 1 << 100))
 					.collect(),
 			},
-			treasury: Default::default(),
 			tokens: TokensConfig { balances: vec![] },
 			sudo: SudoConfig {
 				key: Some($root_key),
@@ -249,21 +239,19 @@
 			vesting: VestingConfig { vesting: vec![] },
 			parachain_info: ParachainInfoConfig {
 				parachain_id: $id.into(),
+				Default::default()
 			},
-			parachain_system: Default::default(),
 			aura: AuraConfig {
 				authorities: $initial_invulnerables
 					.into_iter()
 					.map(|(_, aura)| aura)
 					.collect(),
 			},
-			aura_ext: Default::default(),
 			evm: EVMConfig {
 				accounts: BTreeMap::new(),
+				..Default::default()
 			},
-			ethereum: EthereumConfig {},
-			polkadot_xcm: Default::default(),
-			transaction_payment: Default::default(),
+			..Default::default()
 		}
 	}};
 }
modifiednode/cli/src/command.rsdiffbeforeafterboth
--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -135,19 +135,6 @@
 	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
 		load_spec(id)
 	}
-
-	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
-		match chain_spec.runtime_id() {
-			#[cfg(feature = "unique-runtime")]
-			RuntimeId::Unique => &unique_runtime::VERSION,
-
-			#[cfg(feature = "quartz-runtime")]
-			RuntimeId::Quartz => &quartz_runtime::VERSION,
-
-			RuntimeId::Opal => &opal_runtime::VERSION,
-			runtime_id => panic!("{}", no_runtime_err!(runtime_id)),
-		}
-	}
 }
 
 impl SubstrateCli for RelayChainCli {
@@ -184,25 +171,21 @@
 
 	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
 		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)
-	}
-
-	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
-		polkadot_cli::Cli::native_runtime_version(chain_spec)
 	}
 }
 
 macro_rules! async_run_with_runtime {
 	(
-		$runtime_api:path, $executor:path,
+		$runtime:path, $runtime_api:path, $executor:path,
 		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
 		$( $code:tt )*
 	) => {
 		$runner.async_run(|$config| {
 			let $components = new_partial::<
-				$runtime_api, $executor, _
+				$runtime, $runtime_api, $executor, _
 			>(
 				&$config,
-				crate::service::parachain_build_import_queue,
+				crate::service::parachain_build_import_queue::<$runtime, _, _>,
 			)?;
 			let task_manager = $components.task_manager;
 
@@ -218,18 +201,18 @@
 		match runner.config().chain_spec.runtime_id() {
 			#[cfg(feature = "unique-runtime")]
 			RuntimeId::Unique => async_run_with_runtime!(
-				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
+				unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
 			#[cfg(feature = "quartz-runtime")]
 			RuntimeId::Quartz => async_run_with_runtime!(
-				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
+				quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
 			RuntimeId::Opal => async_run_with_runtime!(
-				opal_runtime::RuntimeApi, OpalRuntimeExecutor,
+				opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
@@ -240,11 +223,18 @@
 
 macro_rules! sync_run_with_runtime {
 	(
-		$runtime_api:path, $executor:path,
+		$runtime:path, $runtime_api:path, $executor:path,
 		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
 		$( $code:tt )*
 	) => {
 		$runner.sync_run(|$config| {
+			let $components = new_partial::<
+				$runtime, $runtime_api, $executor, _
+			>(
+				&$config,
+				crate::service::parachain_build_import_queue::<$runtime, _, _>,
+			)?;
+
 			$( $code )*
 		})
 	};
@@ -257,18 +247,18 @@
 		match runner.config().chain_spec.runtime_id() {
 			#[cfg(feature = "unique-runtime")]
 			RuntimeId::Unique => sync_run_with_runtime!(
-				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
+				unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
 			#[cfg(feature = "quartz-runtime")]
 			RuntimeId::Quartz => sync_run_with_runtime!(
-				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
+				quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
 			RuntimeId::Opal => sync_run_with_runtime!(
-				opal_runtime::RuntimeApi, OpalRuntimeExecutor,
+				opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,
 				runner, $components, $cli, $cmd, $config, $( $code )*
 			),
 
@@ -362,12 +352,11 @@
 		Some(Subcommand::ExportGenesisState(cmd)) => {
 			construct_sync_run!(|components, cli, cmd, _config| {
 				let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
-				let state_version = Cli::native_runtime_version(&spec).state_version();
-				cmd.run::<Block>(&*spec, state_version)
+				cmd.run(&*spec, &*components.client)
 			})
 		}
 		Some(Subcommand::ExportGenesisWasm(cmd)) => {
-			construct_sync_run!(|components, cli, cmd, _config| {
+			construct_sync_run!(|_components, cli, cmd, _config| {
 				let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
 				cmd.run(&*spec)
 			})
@@ -411,6 +400,7 @@
 		#[cfg(feature = "try-runtime")]
 		Some(Subcommand::TryRuntime(cmd)) => {
 			use std::{future::Future, pin::Pin};
+
 			use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};
 			use try_runtime_cli::block_building_info::timestamp_with_aura_info;
 
@@ -506,12 +496,6 @@
 					AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(
 						&para_id,
 					);
-
-				let state_version = Cli::native_runtime_version(&config.chain_spec).state_version();
-				let block: Block = generate_genesis_block(&*config.chain_spec, state_version)
-					.map_err(|e| format!("{e:?}"))?;
-				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
-				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));
 
 				let polkadot_config = SubstrateCli::create_configuration(
 					&polkadot_cli,
@@ -522,9 +506,6 @@
 
 				info!("Parachain id: {:?}", para_id);
 				info!("Parachain Account: {}", parachain_account);
-				info!("Parachain genesis state: {}", genesis_state);
-				info!("Parachain genesis hash: {}", genesis_hash);
-				debug!("Parachain genesis block: {:?}", block);
 				info!(
 					"Is collating: {}",
 					if config.role.is_authority() {
modifiednode/cli/src/service.rsdiffbeforeafterboth
before · node/cli/src/service.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// std18use std::sync::Arc;19use std::sync::Mutex;20use std::collections::BTreeMap;21use std::time::Duration;22use std::pin::Pin;23use fc_mapping_sync::EthereumBlockNotificationSinks;24use fc_rpc::EthBlockDataCacheTask;25use fc_rpc::EthTask;26use fc_rpc_core::types::FeeHistoryCache;27use futures::{28	Stream, StreamExt,29	stream::select,30	task::{Context, Poll},31};32use sc_rpc::SubscriptionTaskExecutor;33use sp_keystore::KeystorePtr;34use tokio::time::Interval;35use jsonrpsee::RpcModule;3637use serde::{Serialize, Deserialize};3839// Cumulus Imports40use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};41use cumulus_client_consensus_common::{42	ParachainConsensus, ParachainBlockImport as TParachainBlockImport,43};44use cumulus_client_service::{45	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,46};47use cumulus_client_cli::CollatorOptions;48use cumulus_client_network::BlockAnnounceValidator;49use cumulus_primitives_core::ParaId;50use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;51use cumulus_relay_chain_interface::{RelayChainInterface, RelayChainResult};52use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;5354// Substrate Imports55use sp_api::{BlockT, HeaderT, ProvideRuntimeApi, StateBackend};56use sc_executor::NativeElseWasmExecutor;57use sc_executor::NativeExecutionDispatch;58use sc_network::NetworkBlock;59use sc_network_sync::SyncingService;60use sc_service::{Configuration, PartialComponents, TaskManager};61use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};62use sp_runtime::traits::BlakeTwo256;63use substrate_prometheus_endpoint::Registry;64use sc_client_api::{BlockchainEvents, BlockOf, Backend, AuxStore, StorageProvider};65use sp_blockchain::{HeaderBackend, HeaderMetadata, Error as BlockChainError};66use sc_consensus::ImportQueue;67use sp_core::H256;68use sp_block_builder::BlockBuilder;6970use polkadot_service::CollatorPair;7172// Frontier Imports73use fc_rpc_core::types::FilterPool;74use fc_mapping_sync::{kv::MappingSyncWorker, SyncStrategy};75use fc_rpc::{76	StorageOverride, OverrideHandle, SchemaV1Override, SchemaV2Override, SchemaV3Override,77	RuntimeApiStorageOverride,78};79use fp_rpc::EthereumRuntimeRPCApi;80use fp_storage::EthereumStorageSchema;8182use up_common::types::opaque::*;8384use crate::chain_spec::RuntimeIdentification;8586/// Unique native executor instance.87#[cfg(feature = "unique-runtime")]88pub struct UniqueRuntimeExecutor;8990#[cfg(feature = "quartz-runtime")]91/// Quartz native executor instance.92pub struct QuartzRuntimeExecutor;9394/// Opal native executor instance.95pub struct OpalRuntimeExecutor;9697#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]98pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;99100#[cfg(all(101	not(feature = "unique-runtime"),102	feature = "quartz-runtime",103	feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;106107#[cfg(all(108	not(feature = "unique-runtime"),109	not(feature = "quartz-runtime"),110	feature = "runtime-benchmarks"111))]112pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;113114#[cfg(feature = "unique-runtime")]115impl NativeExecutionDispatch for UniqueRuntimeExecutor {116	/// Only enable the benchmarking host functions when we actually want to benchmark.117	#[cfg(feature = "runtime-benchmarks")]118	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;119	/// Otherwise we only use the default Substrate host functions.120	#[cfg(not(feature = "runtime-benchmarks"))]121	type ExtendHostFunctions = ();122123	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {124		unique_runtime::api::dispatch(method, data)125	}126127	fn native_version() -> sc_executor::NativeVersion {128		unique_runtime::native_version()129	}130}131132#[cfg(feature = "quartz-runtime")]133impl NativeExecutionDispatch for QuartzRuntimeExecutor {134	/// Only enable the benchmarking host functions when we actually want to benchmark.135	#[cfg(feature = "runtime-benchmarks")]136	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;137	/// Otherwise we only use the default Substrate host functions.138	#[cfg(not(feature = "runtime-benchmarks"))]139	type ExtendHostFunctions = ();140141	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {142		quartz_runtime::api::dispatch(method, data)143	}144145	fn native_version() -> sc_executor::NativeVersion {146		quartz_runtime::native_version()147	}148}149150impl NativeExecutionDispatch for OpalRuntimeExecutor {151	/// Only enable the benchmarking host functions when we actually want to benchmark.152	#[cfg(feature = "runtime-benchmarks")]153	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;154	/// Otherwise we only use the default Substrate host functions.155	#[cfg(not(feature = "runtime-benchmarks"))]156	type ExtendHostFunctions = ();157158	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {159		opal_runtime::api::dispatch(method, data)160	}161162	fn native_version() -> sc_executor::NativeVersion {163		opal_runtime::native_version()164	}165}166167pub struct AutosealInterval {168	interval: Interval,169}170171impl AutosealInterval {172	pub fn new(config: &Configuration, interval: u64) -> Self {173		let _tokio_runtime = config.tokio_handle.enter();174		let interval = tokio::time::interval(Duration::from_millis(interval));175176		Self { interval }177	}178}179180impl Stream for AutosealInterval {181	type Item = tokio::time::Instant;182183	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {184		self.interval.poll_tick(cx).map(Some)185	}186}187188pub fn open_frontier_backend<Block: BlockT, C: HeaderBackend<Block>>(189	client: Arc<C>,190	config: &Configuration,191) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {192	let config_dir = config.base_path.config_dir(config.chain_spec.id());193	let database_dir = config_dir.join("frontier").join("db");194195	Ok(Arc::new(fc_db::kv::Backend::<Block>::new(196		client,197		&fc_db::kv::DatabaseSettings {198			source: fc_db::DatabaseSource::RocksDb {199				path: database_dir,200				cache_size: 0,201			},202		},203	)?))204}205206type FullClient<RuntimeApi, ExecutorDispatch> =207	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;208type FullBackend = sc_service::TFullBackend<Block>;209type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;210type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =211	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;212213/// Starts a `ServiceBuilder` for a full service.214///215/// Use this macro if you don't actually need the full service, but just the builder in order to216/// be able to perform chain operations.217#[allow(clippy::type_complexity)]218pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(219	config: &Configuration,220	build_import_queue: BIQ,221) -> Result<222	PartialComponents<223		FullClient<RuntimeApi, ExecutorDispatch>,224		FullBackend,225		FullSelectChain,226		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,227		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,228		OtherPartial,229	>,230	sc_service::Error,231>232where233	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,234	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>235		+ Send236		+ Sync237		+ 'static,238	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,239	ExecutorDispatch: NativeExecutionDispatch + 'static,240	BIQ: FnOnce(241		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,242		Arc<FullBackend>,243		&Configuration,244		Option<TelemetryHandle>,245		&TaskManager,246	) -> Result<247		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,248		sc_service::Error,249	>,250{251	let telemetry = config252		.telemetry_endpoints253		.clone()254		.filter(|x| !x.is_empty())255		.map(|endpoints| -> Result<_, sc_telemetry::Error> {256			let worker = TelemetryWorker::new(16)?;257			let telemetry = worker.handle().new_telemetry(endpoints);258			Ok((worker, telemetry))259		})260		.transpose()?;261262	let executor = sc_service::new_native_or_wasm_executor(config);263264	let (client, backend, keystore_container, task_manager) =265		sc_service::new_full_parts::<Block, RuntimeApi, _>(266			config,267			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),268			executor,269		)?;270	let client = Arc::new(client);271272	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());273274	let telemetry = telemetry.map(|(worker, telemetry)| {275		task_manager276			.spawn_handle()277			.spawn("telemetry", None, worker.run());278		telemetry279	});280281	let select_chain = sc_consensus::LongestChain::new(backend.clone());282283	let transaction_pool = sc_transaction_pool::BasicPool::new_full(284		config.transaction_pool.clone(),285		config.role.is_authority().into(),286		config.prometheus_registry(),287		task_manager.spawn_essential_handle(),288		client.clone(),289	);290291	let eth_filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));292293	let eth_backend = open_frontier_backend(client.clone(), config)?;294295	let import_queue = build_import_queue(296		client.clone(),297		backend.clone(),298		config,299		telemetry.as_ref().map(|telemetry| telemetry.handle()),300		&task_manager,301	)?;302303	let params = PartialComponents {304		backend,305		client,306		import_queue,307		keystore_container,308		task_manager,309		transaction_pool,310		select_chain,311		other: OtherPartial {312			telemetry,313			eth_filter_pool,314			eth_backend,315			telemetry_worker_handle,316		},317	};318319	Ok(params)320}321322async fn build_relay_chain_interface(323	polkadot_config: Configuration,324	parachain_config: &Configuration,325	telemetry_worker_handle: Option<TelemetryWorkerHandle>,326	task_manager: &mut TaskManager,327	collator_options: CollatorOptions,328	hwbench: Option<sc_sysinfo::HwBench>,329) -> RelayChainResult<(330	Arc<(dyn RelayChainInterface + 'static)>,331	Option<CollatorPair>,332)> {333	if collator_options.relay_chain_rpc_urls.is_empty() {334		build_inprocess_relay_chain(335			polkadot_config,336			parachain_config,337			telemetry_worker_handle,338			task_manager,339			hwbench,340		)341	} else {342		build_minimal_relay_chain_node(343			polkadot_config,344			task_manager,345			collator_options.relay_chain_rpc_urls,346		)347		.await348	}349}350351macro_rules! clone {352    ($($i:ident),* $(,)?) => {353		$(354			let $i = $i.clone();355		)*356    };357}358359/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.360///361/// This is the actual implementation that is abstract over the executor and the runtime api.362#[sc_tracing::logging::prefix_logs_with("Parachain")]363async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(364	parachain_config: Configuration,365	polkadot_config: Configuration,366	collator_options: CollatorOptions,367	id: ParaId,368	build_import_queue: BIQ,369	build_consensus: BIC,370	hwbench: Option<sc_sysinfo::HwBench>,371) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>372where373	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,374	Runtime: RuntimeInstance + Send + Sync + 'static,375	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,376	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,377	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>378		+ Send379		+ Sync380		+ 'static,381	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>382		+ fp_rpc::EthereumRuntimeRPCApi<Block>383		+ fp_rpc::ConvertTransactionRuntimeApi<Block>384		+ sp_session::SessionKeys<Block>385		+ sp_block_builder::BlockBuilder<Block>386		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>387		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>388		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>389		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>390		+ up_pov_estimate_rpc::PovEstimateApi<Block>391		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>392		+ sp_api::Metadata<Block>393		+ sp_offchain::OffchainWorkerApi<Block>394		+ cumulus_primitives_core::CollectCollationInfo<Block>,395	ExecutorDispatch: NativeExecutionDispatch + 'static,396	BIQ: FnOnce(397		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,398		Arc<FullBackend>,399		&Configuration,400		Option<TelemetryHandle>,401		&TaskManager,402	) -> Result<403		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,404		sc_service::Error,405	>,406	BIC: FnOnce(407		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,408		Arc<FullBackend>,409		Option<&Registry>,410		Option<TelemetryHandle>,411		&TaskManager,412		Arc<dyn RelayChainInterface>,413		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,414		Arc<SyncingService<Block>>,415		KeystorePtr,416		bool,417	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,418{419	let parachain_config = prepare_node_config(parachain_config);420421	let params =422		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;423	let OtherPartial {424		mut telemetry,425		telemetry_worker_handle,426		eth_filter_pool,427		eth_backend,428	} = params.other;429	let net_config = sc_network::config::FullNetworkConfiguration::new(&parachain_config.network);430431	let client = params.client.clone();432	let backend = params.backend.clone();433	let mut task_manager = params.task_manager;434435	let (relay_chain_interface, collator_key) = build_relay_chain_interface(436		polkadot_config,437		&parachain_config,438		telemetry_worker_handle,439		&mut task_manager,440		collator_options.clone(),441		hwbench.clone(),442	)443	.await444	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;445446	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);447448	let force_authoring = parachain_config.force_authoring;449	let validator = parachain_config.role.is_authority();450	let prometheus_registry = parachain_config.prometheus_registry().cloned();451	let transaction_pool = params.transaction_pool.clone();452	let import_queue_service = params.import_queue.service();453454	let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =455		sc_service::build_network(sc_service::BuildNetworkParams {456			config: &parachain_config,457			net_config,458			client: client.clone(),459			transaction_pool: transaction_pool.clone(),460			spawn_handle: task_manager.spawn_handle(),461			import_queue: params.import_queue,462			block_announce_validator_builder: Some(Box::new(|_| {463				Box::new(block_announce_validator)464			})),465			warp_sync_params: None,466		})?;467468	let select_chain = params.select_chain.clone();469470	let runtime_id = parachain_config.chain_spec.runtime_id();471472	// Frontier473	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));474	let fee_history_limit = 2048;475476	let eth_pubsub_notification_sinks: Arc<477		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,478	> = Default::default();479480	let overrides = overrides_handle(client.clone());481	let eth_block_data_cache = spawn_frontier_tasks(482		FrontierTaskParams {483			client: client.clone(),484			substrate_backend: backend.clone(),485			eth_filter_pool: eth_filter_pool.clone(),486			eth_backend: eth_backend.clone(),487			fee_history_limit,488			fee_history_cache: fee_history_cache.clone(),489			task_manager: &task_manager,490			prometheus_registry: prometheus_registry.clone(),491			overrides: overrides.clone(),492			sync_strategy: SyncStrategy::Parachain,493		},494		sync_service.clone(),495		eth_pubsub_notification_sinks.clone(),496	);497498	// Rpc499	let rpc_builder = Box::new({500		clone!(501			client,502			backend,503			eth_backend,504			eth_pubsub_notification_sinks,505			fee_history_cache,506			eth_block_data_cache,507			overrides,508			transaction_pool,509			network,510			sync_service,511		);512		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {513			clone!(514				backend,515				eth_block_data_cache,516				client,517				eth_backend,518				eth_filter_pool,519				eth_pubsub_notification_sinks,520				fee_history_cache,521				eth_block_data_cache,522				network,523				runtime_id,524				transaction_pool,525				select_chain,526				overrides,527			);528529			#[cfg(not(feature = "pov-estimate"))]530			let _ = backend;531532			let mut rpc_handle = RpcModule::new(());533534			let full_deps = unique_rpc::FullDeps {535				client: client.clone(),536				runtime_id,537538				#[cfg(feature = "pov-estimate")]539				exec_params: uc_rpc::pov_estimate::ExecutorParams {540					wasm_method: parachain_config.wasm_method,541					default_heap_pages: parachain_config.default_heap_pages,542					max_runtime_instances: parachain_config.max_runtime_instances,543					runtime_cache_size: parachain_config.runtime_cache_size,544				},545546				#[cfg(feature = "pov-estimate")]547				backend,548549				deny_unsafe,550				pool: transaction_pool.clone(),551				select_chain,552			};553554			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;555556			let eth_deps = unique_rpc::EthDeps {557				client,558				graph: transaction_pool.pool().clone(),559				pool: transaction_pool,560				is_authority: validator,561				network,562				eth_backend,563				// TODO: Unhardcode564				max_past_logs: 10000,565				fee_history_limit,566				fee_history_cache,567				eth_block_data_cache,568				// TODO: Unhardcode569				enable_dev_signer: false,570				eth_filter_pool,571				eth_pubsub_notification_sinks,572				overrides,573				sync: sync_service.clone(),574			};575576			unique_rpc::create_eth(577				&mut rpc_handle,578				eth_deps,579				subscription_task_executor.clone(),580			)?;581582			Ok(rpc_handle)583		}584	});585586	sc_service::spawn_tasks(sc_service::SpawnTasksParams {587		rpc_builder,588		client: client.clone(),589		transaction_pool: transaction_pool.clone(),590		task_manager: &mut task_manager,591		config: parachain_config,592		keystore: params.keystore_container.keystore(),593		backend: backend.clone(),594		network: network.clone(),595		sync_service: sync_service.clone(),596		system_rpc_tx,597		telemetry: telemetry.as_mut(),598		tx_handler_controller,599	})?;600601	if let Some(hwbench) = hwbench {602		sc_sysinfo::print_hwbench(&hwbench);603604		if let Some(ref mut telemetry) = telemetry {605			let telemetry_handle = telemetry.handle();606			task_manager.spawn_handle().spawn(607				"telemetry_hwbench",608				None,609				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),610			);611		}612	}613614	let announce_block = {615		let sync_service = sync_service.clone();616		Arc::new(Box::new(move |hash, data| {617			sync_service.announce_block(hash, data)618		}))619	};620621	let relay_chain_slot_duration = Duration::from_secs(6);622623	let overseer_handle = relay_chain_interface624		.overseer_handle()625		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;626627	if validator {628		let parachain_consensus = build_consensus(629			client.clone(),630			backend.clone(),631			prometheus_registry.as_ref(),632			telemetry.as_ref().map(|t| t.handle()),633			&task_manager,634			relay_chain_interface.clone(),635			transaction_pool,636			sync_service.clone(),637			params.keystore_container.keystore(),638			force_authoring,639		)?;640641		let spawner = task_manager.spawn_handle();642643		let params = StartCollatorParams {644			para_id: id,645			block_status: client.clone(),646			announce_block,647			client: client.clone(),648			task_manager: &mut task_manager,649			spawner,650			parachain_consensus,651			import_queue: import_queue_service,652			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),653			relay_chain_interface,654			relay_chain_slot_duration,655			recovery_handle: Box::new(overseer_handle),656			sync_service,657		};658659		start_collator(params).await?;660	} else {661		let params = StartFullNodeParams {662			client: client.clone(),663			announce_block,664			task_manager: &mut task_manager,665			para_id: id,666			import_queue: import_queue_service,667			relay_chain_interface,668			relay_chain_slot_duration,669			recovery_handle: Box::new(overseer_handle),670			sync_service,671		};672673		start_full_node(params)?;674	}675676	start_network.start_network();677678	Ok((task_manager, client))679}680681/// Build the import queue for the the parachain runtime.682pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(683	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,684	backend: Arc<FullBackend>,685	config: &Configuration,686	telemetry: Option<TelemetryHandle>,687	task_manager: &TaskManager,688) -> Result<689	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,690	sc_service::Error,691>692where693	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>694		+ Send695		+ Sync696		+ 'static,697	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>698		+ sp_block_builder::BlockBuilder<Block>699		+ sp_consensus_aura::AuraApi<Block, AuraId>700		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,701	ExecutorDispatch: NativeExecutionDispatch + 'static,702{703	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;704705	let block_import = ParachainBlockImport::new(client.clone(), backend);706707	cumulus_client_consensus_aura::import_queue::<708		sp_consensus_aura::sr25519::AuthorityPair,709		_,710		_,711		_,712		_,713		_,714	>(cumulus_client_consensus_aura::ImportQueueParams {715		block_import,716		client,717		create_inherent_data_providers: move |_, _| async move {718			let time = sp_timestamp::InherentDataProvider::from_system_time();719720			let slot =721				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(722					*time,723					slot_duration,724				);725726			Ok((slot, time))727		},728		registry: config.prometheus_registry(),729		spawner: &task_manager.spawn_essential_handle(),730		telemetry,731	})732	.map_err(Into::into)733}734735/// Start a normal parachain node.736pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(737	parachain_config: Configuration,738	polkadot_config: Configuration,739	collator_options: CollatorOptions,740	id: ParaId,741	hwbench: Option<sc_sysinfo::HwBench>,742) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>743where744	Runtime: RuntimeInstance + Send + Sync + 'static,745	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,746	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,747	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>748		+ Send749		+ Sync750		+ 'static,751	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>752		+ fp_rpc::EthereumRuntimeRPCApi<Block>753		+ fp_rpc::ConvertTransactionRuntimeApi<Block>754		+ sp_session::SessionKeys<Block>755		+ sp_block_builder::BlockBuilder<Block>756		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>757		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>758		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>759		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>760		+ up_pov_estimate_rpc::PovEstimateApi<Block>761		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>762		+ sp_api::Metadata<Block>763		+ sp_offchain::OffchainWorkerApi<Block>764		+ cumulus_primitives_core::CollectCollationInfo<Block>765		+ sp_consensus_aura::AuraApi<Block, AuraId>,766	ExecutorDispatch: NativeExecutionDispatch + 'static,767{768	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(769		parachain_config,770		polkadot_config,771		collator_options,772		id,773		parachain_build_import_queue,774		|client,775		 backend,776		 prometheus_registry,777		 telemetry,778		 task_manager,779		 relay_chain_interface,780		 transaction_pool,781		 sync_oracle,782		 keystore,783		 force_authoring| {784			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;785786			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(787				task_manager.spawn_handle(),788				client.clone(),789				transaction_pool,790				prometheus_registry,791				telemetry.clone(),792			);793794			let block_import = ParachainBlockImport::new(client.clone(), backend);795796			Ok(AuraConsensus::build::<797				sp_consensus_aura::sr25519::AuthorityPair,798				_,799				_,800				_,801				_,802				_,803				_,804			>(BuildAuraConsensusParams {805				proposer_factory,806				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {807					let relay_chain_interface = relay_chain_interface.clone();808					async move {809						let parachain_inherent =810						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(811							relay_parent,812							&relay_chain_interface,813							&validation_data,814							id,815						).await;816817						let time = sp_timestamp::InherentDataProvider::from_system_time();818819						let slot =820						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(821							*time,822							slot_duration,823						);824825						let parachain_inherent = parachain_inherent.ok_or_else(|| {826							Box::<dyn std::error::Error + Send + Sync>::from(827								"Failed to create parachain inherent",828							)829						})?;830						Ok((slot, time, parachain_inherent))831					}832				},833				block_import,834				para_client: client,835				backoff_authoring_blocks: Option::<()>::None,836				sync_oracle,837				keystore,838				force_authoring,839				slot_duration,840				// We got around 500ms for proposing841				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),842				telemetry,843				max_block_proposal_slot_portion: None,844			}))845		},846		hwbench,847	)848	.await849}850851fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(852	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,853	_: Arc<FullBackend>,854	config: &Configuration,855	_: Option<TelemetryHandle>,856	task_manager: &TaskManager,857) -> Result<858	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,859	sc_service::Error,860>861where862	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>863		+ Send864		+ Sync865		+ 'static,866	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>867		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,868	ExecutorDispatch: NativeExecutionDispatch + 'static,869{870	Ok(sc_consensus_manual_seal::import_queue(871		Box::new(client),872		&task_manager.spawn_essential_handle(),873		config.prometheus_registry(),874	))875}876877pub struct OtherPartial {878	pub telemetry: Option<Telemetry>,879	pub telemetry_worker_handle: Option<TelemetryWorkerHandle>,880	pub eth_filter_pool: Option<FilterPool>,881	pub eth_backend: Arc<fc_db::kv::Backend<Block>>,882}883884/// Builds a new development service. This service uses instant seal, and mocks885/// the parachain inherent886pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(887	config: Configuration,888	autoseal_interval: u64,889	autoseal_finalize_delay: Option<u64>,890	disable_autoseal_on_tx: bool,891) -> sc_service::error::Result<TaskManager>892where893	Runtime: RuntimeInstance + Send + Sync + 'static,894	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,895	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,896	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>897		+ Send898		+ Sync899		+ 'static,900	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>901		+ fp_rpc::EthereumRuntimeRPCApi<Block>902		+ fp_rpc::ConvertTransactionRuntimeApi<Block>903		+ sp_session::SessionKeys<Block>904		+ sp_block_builder::BlockBuilder<Block>905		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>906		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>907		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>908		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>909		+ up_pov_estimate_rpc::PovEstimateApi<Block>910		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>911		+ sp_api::Metadata<Block>912		+ sp_offchain::OffchainWorkerApi<Block>913		+ cumulus_primitives_core::CollectCollationInfo<Block>914		+ sp_consensus_aura::AuraApi<Block, AuraId>,915	ExecutorDispatch: NativeExecutionDispatch + 'static,916{917	use sc_consensus_manual_seal::{918		run_manual_seal, run_delayed_finalize, EngineCommand, ManualSealParams,919		DelayedFinalizeParams,920	};921	use fc_consensus::FrontierBlockImport;922923	let sc_service::PartialComponents {924		client,925		backend,926		mut task_manager,927		import_queue,928		keystore_container,929		select_chain: maybe_select_chain,930		transaction_pool,931		other:932			OtherPartial {933				telemetry,934				eth_filter_pool,935				eth_backend,936				telemetry_worker_handle: _,937			},938	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(939		&config,940		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,941	)?;942	let net_config = sc_network::config::FullNetworkConfiguration::new(&config.network);943	let prometheus_registry = config.prometheus_registry().cloned();944945	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =946		sc_service::build_network(sc_service::BuildNetworkParams {947			config: &config,948			net_config,949			client: client.clone(),950			transaction_pool: transaction_pool.clone(),951			spawn_handle: task_manager.spawn_handle(),952			import_queue,953			block_announce_validator_builder: None,954			warp_sync_params: None,955		})?;956957	if config.offchain_worker.enabled {958		sc_service::build_offchain_workers(959			&config,960			task_manager.spawn_handle(),961			client.clone(),962			network.clone(),963		);964	}965966	let collator = config.role.is_authority();967968	let select_chain = maybe_select_chain;969970	if collator {971		let block_import = FrontierBlockImport::new(client.clone(), client.clone());972973		let env = sc_basic_authorship::ProposerFactory::new(974			task_manager.spawn_handle(),975			client.clone(),976			transaction_pool.clone(),977			prometheus_registry.as_ref(),978			telemetry.as_ref().map(|x| x.handle()),979		);980981		let transactions_commands_stream: Box<982			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,983		> = Box::new(984			transaction_pool985				.pool()986				.validated_pool()987				.import_notification_stream()988				.filter(move |_| futures::future::ready(!disable_autoseal_on_tx))989				.map(|_| EngineCommand::SealNewBlock {990					create_empty: true,991					finalize: false,992					parent_hash: None,993					sender: None,994				}),995		);996997		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));998999		let idle_commands_stream: Box<1000			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,1001		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {1002			create_empty: true,1003			finalize: false,1004			parent_hash: None,1005			sender: None,1006		}));10071008		let commands_stream = select(transactions_commands_stream, idle_commands_stream);10091010		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;1011		let client_set_aside_for_cidp = client.clone();10121013		if let Some(delay_sec) = autoseal_finalize_delay {1014			let spawn_handle = task_manager.spawn_handle();10151016			task_manager.spawn_essential_handle().spawn_blocking(1017				"finalization_task",1018				Some("block-authoring"),1019				run_delayed_finalize(DelayedFinalizeParams {1020					client: client.clone(),1021					delay_sec,1022					spawn_handle,1023				}),1024			);1025		}10261027		task_manager.spawn_essential_handle().spawn_blocking(1028			"authorship_task",1029			Some("block-authoring"),1030			run_manual_seal(ManualSealParams {1031				block_import,1032				env,1033				client: client.clone(),1034				pool: transaction_pool.clone(),1035				commands_stream,1036				select_chain: select_chain.clone(),1037				consensus_data_provider: None,1038				create_inherent_data_providers: move |block: Hash, ()| {1039					let current_para_block = client_set_aside_for_cidp1040						.number(block)1041						.expect("Header lookup should succeed")1042						.expect("Header passed in as parent should be present in backend.");10431044					let client_for_xcm = client_set_aside_for_cidp.clone();1045					async move {1046						let time = sp_timestamp::InherentDataProvider::from_system_time();10471048						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {1049							current_para_block,1050							relay_offset: 1000,1051							relay_blocks_per_para_block: 2,1052							para_blocks_per_relay_epoch: 0,1053							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(1054								&*client_for_xcm,1055								block,1056								Default::default(),1057								Default::default(),1058							),1059							relay_randomness_config: (),1060							raw_downward_messages: vec![],1061							raw_horizontal_messages: vec![],1062						};10631064						let slot =1065						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(1066							*time,1067							slot_duration,1068						);10691070						Ok((time, slot, mocked_parachain))1071					}1072				},1073			}),1074		);1075	}10761077	#[cfg(feature = "pov-estimate")]1078	let rpc_backend = backend.clone();10791080	let runtime_id = config.chain_spec.runtime_id();10811082	// Frontier1083	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));1084	let fee_history_limit = 2048;10851086	let eth_pubsub_notification_sinks: Arc<1087		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,1088	> = Default::default();10891090	let overrides = overrides_handle(client.clone());1091	let eth_block_data_cache = spawn_frontier_tasks(1092		FrontierTaskParams {1093			client: client.clone(),1094			substrate_backend: backend.clone(),1095			eth_filter_pool: eth_filter_pool.clone(),1096			eth_backend: eth_backend.clone(),1097			fee_history_limit,1098			fee_history_cache: fee_history_cache.clone(),1099			task_manager: &task_manager,1100			prometheus_registry,1101			overrides: overrides.clone(),1102			sync_strategy: SyncStrategy::Normal,1103		},1104		sync_service.clone(),1105		eth_pubsub_notification_sinks.clone(),1106	);11071108	// Rpc1109	let rpc_builder = Box::new({1110		clone!(1111			client,1112			backend,1113			eth_backend,1114			eth_pubsub_notification_sinks,1115			fee_history_cache,1116			eth_block_data_cache,1117			overrides,1118			transaction_pool,1119			network,1120			sync_service,1121		);1122		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {1123			clone!(1124				backend,1125				eth_block_data_cache,1126				client,1127				eth_backend,1128				eth_filter_pool,1129				eth_pubsub_notification_sinks,1130				fee_history_cache,1131				eth_block_data_cache,1132				network,1133				runtime_id,1134				transaction_pool,1135				select_chain,1136				overrides,1137			);11381139			#[cfg(not(feature = "pov-estimate"))]1140			let _ = backend;11411142			let mut rpc_module = RpcModule::new(());11431144			let full_deps = unique_rpc::FullDeps {1145				runtime_id,11461147				#[cfg(feature = "pov-estimate")]1148				exec_params: uc_rpc::pov_estimate::ExecutorParams {1149					wasm_method: config.wasm_method,1150					default_heap_pages: config.default_heap_pages,1151					max_runtime_instances: config.max_runtime_instances,1152					runtime_cache_size: config.runtime_cache_size,1153				},11541155				#[cfg(feature = "pov-estimate")]1156				backend,1157				// eth_backend,1158				deny_unsafe,1159				client: client.clone(),1160				pool: transaction_pool.clone(),1161				select_chain,1162			};11631164			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;11651166			let eth_deps = unique_rpc::EthDeps {1167				client,1168				graph: transaction_pool.pool().clone(),1169				pool: transaction_pool,1170				is_authority: true,1171				network,1172				eth_backend,1173				// TODO: Unhardcode1174				max_past_logs: 10000,1175				fee_history_limit,1176				fee_history_cache,1177				eth_block_data_cache,1178				// TODO: Unhardcode1179				enable_dev_signer: false,1180				eth_filter_pool,1181				eth_pubsub_notification_sinks,1182				overrides,1183				sync: sync_service.clone(),1184			};11851186			unique_rpc::create_eth(1187				&mut rpc_module,1188				eth_deps,1189				subscription_task_executor.clone(),1190			)?;11911192			Ok(rpc_module)1193		}1194	});11951196	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1197		network,1198		sync_service,1199		client,1200		keystore: keystore_container.keystore(),1201		task_manager: &mut task_manager,1202		transaction_pool,1203		rpc_builder,1204		backend,1205		system_rpc_tx,1206		config,1207		telemetry: None,1208		tx_handler_controller,1209	})?;12101211	network_starter.start_network();1212	Ok(task_manager)1213}12141215fn overrides_handle<C, BE>(client: Arc<C>) -> Arc<OverrideHandle<Block>>1216where1217	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,1218	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,1219	C: Send + Sync + 'static,1220	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,1221	BE: Backend<Block> + 'static,1222	BE::State: StateBackend<BlakeTwo256>,1223{1224	let mut overrides_map = BTreeMap::new();1225	overrides_map.insert(1226		EthereumStorageSchema::V1,1227		Box::new(SchemaV1Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1228	);1229	overrides_map.insert(1230		EthereumStorageSchema::V2,1231		Box::new(SchemaV2Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1232	);1233	overrides_map.insert(1234		EthereumStorageSchema::V3,1235		Box::new(SchemaV3Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1236	);12371238	Arc::new(OverrideHandle {1239		schemas: overrides_map,1240		fallback: Box::new(RuntimeApiStorageOverride::new(client)),1241	})1242}12431244pub struct FrontierTaskParams<'a, B: BlockT, C, BE> {1245	pub task_manager: &'a TaskManager,1246	pub client: Arc<C>,1247	pub substrate_backend: Arc<BE>,1248	pub eth_backend: Arc<fc_db::kv::Backend<B>>,1249	pub eth_filter_pool: Option<FilterPool>,1250	pub overrides: Arc<OverrideHandle<B>>,1251	pub fee_history_limit: u64,1252	pub fee_history_cache: FeeHistoryCache,1253	pub sync_strategy: SyncStrategy,1254	pub prometheus_registry: Option<Registry>,1255}12561257pub fn spawn_frontier_tasks<B, C, BE>(1258	params: FrontierTaskParams<B, C, BE>,1259	sync: Arc<SyncingService<B>>,1260	pubsub_notification_sinks: Arc<1261		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<B>>,1262	>,1263) -> Arc<EthBlockDataCacheTask<B>>1264where1265	C: ProvideRuntimeApi<B> + BlockOf,1266	C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,1267	C: BlockchainEvents<B> + StorageProvider<B, BE>,1268	C: Send + Sync + 'static,1269	C::Api: EthereumRuntimeRPCApi<B>,1270	C::Api: BlockBuilder<B>,1271	B: BlockT<Hash = H256> + Send + Sync + 'static,1272	B::Header: HeaderT<Number = u32>,1273	BE: Backend<B> + 'static,1274	BE::State: StateBackend<BlakeTwo256>,1275{1276	let FrontierTaskParams {1277		task_manager,1278		client,1279		substrate_backend,1280		eth_backend,1281		eth_filter_pool,1282		overrides,1283		fee_history_limit,1284		fee_history_cache,1285		sync_strategy,1286		prometheus_registry,1287	} = params;1288	// Frontier offchain DB task. Essential.1289	// Maps emulated ethereum data to substrate native data.1290	params.task_manager.spawn_essential_handle().spawn(1291		"frontier-mapping-sync-worker",1292		Some("frontier"),1293		MappingSyncWorker::new(1294			client.import_notification_stream(),1295			Duration::new(6, 0),1296			client.clone(),1297			substrate_backend,1298			overrides.clone(),1299			eth_backend,1300			3,1301			0,1302			sync_strategy,1303			sync,1304			pubsub_notification_sinks,1305		)1306		.for_each(|()| futures::future::ready(())),1307	);13081309	// Frontier `EthFilterApi` maintenance.1310	// Manages the pool of user-created Filters.1311	if let Some(eth_filter_pool) = eth_filter_pool {1312		// Each filter is allowed to stay in the pool for 100 blocks.1313		const FILTER_RETAIN_THRESHOLD: u64 = 100;1314		params.task_manager.spawn_essential_handle().spawn(1315			"frontier-filter-pool",1316			Some("frontier"),1317			EthTask::filter_pool_task(client.clone(), eth_filter_pool, FILTER_RETAIN_THRESHOLD),1318		);1319	}13201321	// Spawn Frontier FeeHistory cache maintenance task.1322	params.task_manager.spawn_essential_handle().spawn(1323		"frontier-fee-history",1324		Some("frontier"),1325		EthTask::fee_history_task(1326			client,1327			overrides.clone(),1328			fee_history_cache,1329			fee_history_limit,1330		),1331	);13321333	Arc::new(EthBlockDataCacheTask::new(1334		task_manager.spawn_handle(),1335		overrides,1336		50,1337		50,1338		prometheus_registry,1339	))1340}
after · node/cli/src/service.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// std18use std::sync::Arc;19use std::sync::Mutex;20use std::collections::BTreeMap;21use std::time::Duration;22use std::pin::Pin;23use fc_mapping_sync::EthereumBlockNotificationSinks;24use fc_rpc::EthBlockDataCacheTask;25use fc_rpc::EthTask;26use fc_rpc_core::types::FeeHistoryCache;27use futures::{28	Stream, StreamExt,29	stream::select,30	task::{Context, Poll},31};32use sc_rpc::SubscriptionTaskExecutor;33use sp_keystore::KeystorePtr;34use tokio::time::Interval;35use jsonrpsee::RpcModule;3637use serde::{Serialize, Deserialize};3839// Cumulus Imports40use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};41use cumulus_client_consensus_common::{42	ParachainConsensus, ParachainBlockImport as TParachainBlockImport,43};44use cumulus_client_service::{45	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,46};47use cumulus_client_cli::CollatorOptions;48use cumulus_client_network::BlockAnnounceValidator;49use cumulus_primitives_core::ParaId;50use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;51use cumulus_relay_chain_interface::{RelayChainInterface, RelayChainResult};52use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;5354// Substrate Imports55use sp_api::{BlockT, HeaderT, ProvideRuntimeApi, StateBackend};56use sc_executor::NativeElseWasmExecutor;57use sc_executor::NativeExecutionDispatch;58use sc_network::NetworkBlock;59use sc_network_sync::SyncingService;60use sc_service::{Configuration, PartialComponents, TaskManager};61use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};62use sp_runtime::traits::BlakeTwo256;63use substrate_prometheus_endpoint::Registry;64use sc_client_api::{BlockchainEvents, BlockOf, Backend, AuxStore, StorageProvider};65use sp_blockchain::{HeaderBackend, HeaderMetadata, Error as BlockChainError};66use sc_consensus::ImportQueue;67use sp_core::H256;68use sp_block_builder::BlockBuilder;6970use polkadot_service::CollatorPair;7172// Frontier Imports73use fc_rpc_core::types::FilterPool;74use fc_mapping_sync::{kv::MappingSyncWorker, SyncStrategy};75use fc_rpc::{76	StorageOverride, OverrideHandle, SchemaV1Override, SchemaV2Override, SchemaV3Override,77	RuntimeApiStorageOverride,78};79use fp_rpc::EthereumRuntimeRPCApi;80use fp_storage::EthereumStorageSchema;8182use up_common::types::opaque::*;8384use crate::chain_spec::RuntimeIdentification;8586/// Unique native executor instance.87#[cfg(feature = "unique-runtime")]88pub struct UniqueRuntimeExecutor;8990#[cfg(feature = "quartz-runtime")]91/// Quartz native executor instance.92pub struct QuartzRuntimeExecutor;9394/// Opal native executor instance.95pub struct OpalRuntimeExecutor;9697#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]98pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;99100#[cfg(all(101	not(feature = "unique-runtime"),102	feature = "quartz-runtime",103	feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;106107#[cfg(all(108	not(feature = "unique-runtime"),109	not(feature = "quartz-runtime"),110	feature = "runtime-benchmarks"111))]112pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;113114#[cfg(feature = "unique-runtime")]115impl NativeExecutionDispatch for UniqueRuntimeExecutor {116	/// Only enable the benchmarking host functions when we actually want to benchmark.117	#[cfg(feature = "runtime-benchmarks")]118	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;119	/// Otherwise we only use the default Substrate host functions.120	#[cfg(not(feature = "runtime-benchmarks"))]121	type ExtendHostFunctions = ();122123	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {124		unique_runtime::api::dispatch(method, data)125	}126127	fn native_version() -> sc_executor::NativeVersion {128		unique_runtime::native_version()129	}130}131132#[cfg(feature = "quartz-runtime")]133impl NativeExecutionDispatch for QuartzRuntimeExecutor {134	/// Only enable the benchmarking host functions when we actually want to benchmark.135	#[cfg(feature = "runtime-benchmarks")]136	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;137	/// Otherwise we only use the default Substrate host functions.138	#[cfg(not(feature = "runtime-benchmarks"))]139	type ExtendHostFunctions = ();140141	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {142		quartz_runtime::api::dispatch(method, data)143	}144145	fn native_version() -> sc_executor::NativeVersion {146		quartz_runtime::native_version()147	}148}149150impl NativeExecutionDispatch for OpalRuntimeExecutor {151	/// Only enable the benchmarking host functions when we actually want to benchmark.152	#[cfg(feature = "runtime-benchmarks")]153	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;154	/// Otherwise we only use the default Substrate host functions.155	#[cfg(not(feature = "runtime-benchmarks"))]156	type ExtendHostFunctions = ();157158	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {159		opal_runtime::api::dispatch(method, data)160	}161162	fn native_version() -> sc_executor::NativeVersion {163		opal_runtime::native_version()164	}165}166167pub struct AutosealInterval {168	interval: Interval,169}170171impl AutosealInterval {172	pub fn new(config: &Configuration, interval: u64) -> Self {173		let _tokio_runtime = config.tokio_handle.enter();174		let interval = tokio::time::interval(Duration::from_millis(interval));175176		Self { interval }177	}178}179180impl Stream for AutosealInterval {181	type Item = tokio::time::Instant;182183	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {184		self.interval.poll_tick(cx).map(Some)185	}186}187188pub fn open_frontier_backend<C: HeaderBackend<Block>>(189	client: Arc<C>,190	config: &Configuration,191) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {192	let config_dir = config.base_path.config_dir(config.chain_spec.id());193	let database_dir = config_dir.join("frontier").join("db");194195	Ok(Arc::new(fc_db::kv::Backend::<Block>::new(196		client,197		&fc_db::kv::DatabaseSettings {198			source: fc_db::DatabaseSource::RocksDb {199				path: database_dir,200				cache_size: 0,201			},202		},203	)?))204}205206type FullClient<RuntimeApi, ExecutorDispatch> =207	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;208type FullBackend = sc_service::TFullBackend<Block>;209type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;210type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =211	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;212213/// Generate a supertrait based on bounds, and blanket impl for it.214macro_rules! ez_bounds {215	($vis:vis trait $name:ident$(<$($gen:ident $(: $($(+)? $bound:path)*)?),* $(,)?>)? $(:)? $($(+)? $super:path)* {}) => {216		$vis trait $name $(<$($gen $(: $($bound+)*)?,)*>)?: $($super +)* {}217		impl<T, $($($gen $(: $($bound+)*)?,)*)?> $name$(<$($gen,)*>)? for T218		where T: $($super +)* {}219	}220}221ez_bounds!(222	pub trait RuntimeApiDep<Runtime: RuntimeInstance>:223		sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>224		+ sp_consensus_aura::AuraApi<Block, AuraId>225		+ fp_rpc::EthereumRuntimeRPCApi<Block>226		+ sp_session::SessionKeys<Block>227		+ sp_block_builder::BlockBuilder<Block>228		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>229		+ sp_api::ApiExt<Block>230		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>231		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>232		+ up_pov_estimate_rpc::PovEstimateApi<Block>233		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>234		+ sp_api::Metadata<Block>235		+ sp_offchain::OffchainWorkerApi<Block>236		+ cumulus_primitives_core::CollectCollationInfo<Block>237		// Deprecated, not used.238		+ fp_rpc::ConvertTransactionRuntimeApi<Block>239	{240	}241);242243/// Starts a `ServiceBuilder` for a full service.244///245/// Use this macro if you don't actually need the full service, but just the builder in order to246/// be able to perform chain operations.247#[allow(clippy::type_complexity)]248pub fn new_partial<Runtime, RuntimeApi, ExecutorDispatch, BIQ>(249	config: &Configuration,250	build_import_queue: BIQ,251) -> Result<252	PartialComponents<253		FullClient<RuntimeApi, ExecutorDispatch>,254		FullBackend,255		FullSelectChain,256		sc_consensus::DefaultImportQueue<Block>,257		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,258		OtherPartial,259	>,260	sc_service::Error,261>262where263	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,264	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>265		+ Send266		+ Sync267		+ 'static,268	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,269	Runtime: RuntimeInstance,270	ExecutorDispatch: NativeExecutionDispatch + 'static,271	BIQ: FnOnce(272		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,273		Arc<FullBackend>,274		&Configuration,275		Option<TelemetryHandle>,276		&TaskManager,277	) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>,278{279	let telemetry = config280		.telemetry_endpoints281		.clone()282		.filter(|x| !x.is_empty())283		.map(|endpoints| -> Result<_, sc_telemetry::Error> {284			let worker = TelemetryWorker::new(16)?;285			let telemetry = worker.handle().new_telemetry(endpoints);286			Ok((worker, telemetry))287		})288		.transpose()?;289290	let executor = sc_service::new_native_or_wasm_executor(config);291292	let (client, backend, keystore_container, task_manager) =293		sc_service::new_full_parts::<Block, RuntimeApi, _>(294			config,295			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),296			executor,297		)?;298	let client = Arc::new(client);299300	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());301302	let telemetry = telemetry.map(|(worker, telemetry)| {303		task_manager304			.spawn_handle()305			.spawn("telemetry", None, worker.run());306		telemetry307	});308309	let select_chain = sc_consensus::LongestChain::new(backend.clone());310311	let transaction_pool = sc_transaction_pool::BasicPool::new_full(312		config.transaction_pool.clone(),313		config.role.is_authority().into(),314		config.prometheus_registry(),315		task_manager.spawn_essential_handle(),316		client.clone(),317	);318319	let eth_filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));320321	let eth_backend = open_frontier_backend(client.clone(), config)?;322323	let import_queue = build_import_queue(324		client.clone(),325		backend.clone(),326		config,327		telemetry.as_ref().map(|telemetry| telemetry.handle()),328		&task_manager,329	)?;330331	let params = PartialComponents {332		backend,333		client,334		import_queue,335		keystore_container,336		task_manager,337		transaction_pool,338		select_chain,339		other: OtherPartial {340			telemetry,341			eth_filter_pool,342			eth_backend,343			telemetry_worker_handle,344		},345	};346347	Ok(params)348}349350macro_rules! clone {351    ($($i:ident),* $(,)?) => {352		$(353			let $i = $i.clone();354		)*355    };356}357358/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.359///360/// This is the actual implementation that is abstract over the executor and the runtime api.361#[sc_tracing::logging::prefix_logs_with("Parachain")]362pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(363	parachain_config: Configuration,364	polkadot_config: Configuration,365	collator_options: CollatorOptions,366	para_id: ParaId,367	hwbench: Option<sc_sysinfo::HwBench>,368) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>369where370	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,371	Runtime: RuntimeInstance + Send + Sync + 'static,372	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,373	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,374	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>375		+ Send376		+ Sync377		+ 'static,378	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,379	Runtime: RuntimeInstance,380	ExecutorDispatch: NativeExecutionDispatch + 'static,381{382	let parachain_config = prepare_node_config(parachain_config);383384	let params = new_partial::<Runtime, RuntimeApi, ExecutorDispatch, _>(385		&parachain_config,386		parachain_build_import_queue,387	)?;388	let OtherPartial {389		mut telemetry,390		telemetry_worker_handle,391		eth_filter_pool,392		eth_backend,393	} = params.other;394	let net_config = sc_network::config::FullNetworkConfiguration::new(&parachain_config.network);395396	let client = params.client.clone();397	let backend = params.backend.clone();398	let mut task_manager = params.task_manager;399400	let (relay_chain_interface, collator_key) = build_relay_chain_interface(401		polkadot_config,402		&parachain_config,403		telemetry_worker_handle,404		&mut task_manager,405		collator_options.clone(),406		hwbench.clone(),407	)408	.await409	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;410411	let block_announce_validator =412		RequireSecondedInBlockAnnounce::new(relay_chain_interface.clone(), para_id);413414	let validator = parachain_config.role.is_authority();415	let prometheus_registry = parachain_config.prometheus_registry().cloned();416	let transaction_pool = params.transaction_pool.clone();417	let import_queue_service = params.import_queue.service();418419	let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =420		sc_service::build_network(sc_service::BuildNetworkParams {421			config: &parachain_config,422			net_config,423			client: client.clone(),424			transaction_pool: transaction_pool.clone(),425			spawn_handle: task_manager.spawn_handle(),426			import_queue: params.import_queue,427			block_announce_validator_builder: Some(Box::new(|_| {428				Box::new(block_announce_validator)429			})),430			warp_sync_params: None,431		})?;432433	let select_chain = params.select_chain.clone();434435	let runtime_id = parachain_config.chain_spec.runtime_id();436437	// Frontier438	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));439	let fee_history_limit = 2048;440441	let eth_pubsub_notification_sinks: Arc<442		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,443	> = Default::default();444445	let overrides = overrides_handle(client.clone());446	let eth_block_data_cache = spawn_frontier_tasks(447		FrontierTaskParams {448			client: client.clone(),449			substrate_backend: backend.clone(),450			eth_filter_pool: eth_filter_pool.clone(),451			eth_backend: eth_backend.clone(),452			fee_history_limit,453			fee_history_cache: fee_history_cache.clone(),454			task_manager: &task_manager,455			prometheus_registry: prometheus_registry.clone(),456			overrides: overrides.clone(),457			sync_strategy: SyncStrategy::Parachain,458		},459		sync_service.clone(),460		eth_pubsub_notification_sinks.clone(),461	);462463	// Rpc464	let rpc_builder = Box::new({465		clone!(466			client,467			backend,468			eth_backend,469			eth_pubsub_notification_sinks,470			fee_history_cache,471			eth_block_data_cache,472			overrides,473			transaction_pool,474			network,475			sync_service,476		);477		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {478			clone!(479				backend,480				eth_block_data_cache,481				client,482				eth_backend,483				eth_filter_pool,484				eth_pubsub_notification_sinks,485				fee_history_cache,486				eth_block_data_cache,487				network,488				runtime_id,489				transaction_pool,490				select_chain,491				overrides,492			);493494			#[cfg(not(feature = "pov-estimate"))]495			let _ = backend;496497			let mut rpc_handle = RpcModule::new(());498499			let full_deps = FullDeps {500				client: client.clone(),501				runtime_id,502503				#[cfg(feature = "pov-estimate")]504				exec_params: uc_rpc::pov_estimate::ExecutorParams {505					wasm_method: parachain_config.wasm_method,506					default_heap_pages: parachain_config.default_heap_pages,507					max_runtime_instances: parachain_config.max_runtime_instances,508					runtime_cache_size: parachain_config.runtime_cache_size,509				},510511				#[cfg(feature = "pov-estimate")]512				backend,513514				deny_unsafe,515				pool: transaction_pool.clone(),516				select_chain,517			};518519			create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;520521			let eth_deps = EthDeps {522				client,523				graph: transaction_pool.pool().clone(),524				pool: transaction_pool,525				is_authority: validator,526				network,527				eth_backend,528				// TODO: Unhardcode529				max_past_logs: 10000,530				fee_history_limit,531				fee_history_cache,532				eth_block_data_cache,533				// TODO: Unhardcode534				enable_dev_signer: false,535				eth_filter_pool,536				eth_pubsub_notification_sinks,537				overrides,538				sync: sync_service.clone(),539				pending_create_inherent_data_providers: |_, ()| async move { Ok(()) },540			};541542			create_eth::<543				_,544				_,545				_,546				_,547				_,548				_,549				DefaultEthConfig<FullClient<RuntimeApi, ExecutorDispatch>>,550			>(551				&mut rpc_handle,552				eth_deps,553				subscription_task_executor.clone(),554			)?;555556			Ok(rpc_handle)557		}558	});559560	sc_service::spawn_tasks(sc_service::SpawnTasksParams {561		rpc_builder,562		client: client.clone(),563		transaction_pool: transaction_pool.clone(),564		task_manager: &mut task_manager,565		config: parachain_config,566		keystore: params.keystore_container.keystore(),567		backend: backend.clone(),568		network: network.clone(),569		sync_service: sync_service.clone(),570		system_rpc_tx,571		telemetry: telemetry.as_mut(),572		tx_handler_controller,573	})?;574575	if let Some(hwbench) = hwbench {576		sc_sysinfo::print_hwbench(&hwbench);577578		if let Some(ref mut telemetry) = telemetry {579			let telemetry_handle = telemetry.handle();580			task_manager.spawn_handle().spawn(581				"telemetry_hwbench",582				None,583				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),584			);585		}586	}587588	let announce_block = {589		let sync_service = sync_service.clone();590		Arc::new(Box::new(move |hash, data| {591			sync_service.announce_block(hash, data)592		}))593	};594595	let relay_chain_slot_duration = Duration::from_secs(6);596597	let overseer_handle = relay_chain_interface598		.overseer_handle()599		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;600601	start_relay_chain_tasks(StartRelayChainTasksParams {602		client: client.clone(),603		announce_block: announce_block.clone(),604		para_id,605		relay_chain_interface: relay_chain_interface.clone(),606		task_manager: &mut task_manager,607		da_recovery_profile: if validator {608			DARecoveryProfile::Collator609		} else {610			DARecoveryProfile::FullNode611		},612		import_queue: import_queue_service,613		relay_chain_slot_duration,614		recovery_handle: Box::new(overseer_handle.clone()),615		sync_service: sync_service.clone(),616	})?;617618	if validator {619		start_consensus(620			client.clone(),621			backend.clone(),622			prometheus_registry.as_ref(),623			telemetry.as_ref().map(|t| t.handle()),624			&task_manager,625			relay_chain_interface.clone(),626			transaction_pool,627			sync_service.clone(),628			params.keystore_container.keystore(),629			overseer_handle,630			relay_chain_slot_duration,631			para_id,632			collator_key.expect("cli args do not allow this"),633			announce_block,634		)?;635	}636637	start_network.start_network();638639	Ok((task_manager, client))640}641642/// Build the import queue for the the parachain runtime.643pub fn parachain_build_import_queue<Runtime, RuntimeApi, ExecutorDispatch>(644	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,645	backend: Arc<FullBackend>,646	config: &Configuration,647	telemetry: Option<TelemetryHandle>,648	task_manager: &TaskManager,649) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>650where651	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>652		+ Send653		+ Sync654		+ 'static,655	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,656	Runtime: RuntimeInstance,657	ExecutorDispatch: NativeExecutionDispatch + 'static,658{659	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;660661	let block_import = ParachainBlockImport::new(client.clone(), backend);662663	cumulus_client_consensus_aura::import_queue::<664		sp_consensus_aura::sr25519::AuthorityPair,665		_,666		_,667		_,668		_,669		_,670	>(cumulus_client_consensus_aura::ImportQueueParams {671		block_import,672		client,673		create_inherent_data_providers: move |_, _| async move {674			let time = sp_timestamp::InherentDataProvider::from_system_time();675676			let slot =677				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(678					*time,679					slot_duration,680				);681682			Ok((slot, time))683		},684		registry: config.prometheus_registry(),685		spawner: &task_manager.spawn_essential_handle(),686		telemetry,687	})688	.map_err(Into::into)689}690691pub fn start_consensus<ExecutorDispatch, RuntimeApi, Runtime>(692	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,693	backend: Arc<FullBackend>,694	prometheus_registry: Option<&Registry>,695	telemetry: Option<TelemetryHandle>,696	task_manager: &TaskManager,697	relay_chain_interface: Arc<dyn RelayChainInterface>,698	transaction_pool: Arc<699		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,700	>,701	sync_oracle: Arc<SyncingService<Block>>,702	keystore: KeystorePtr,703	overseer_handle: OverseerHandle,704	relay_chain_slot_duration: Duration,705	para_id: ParaId,706	collator_key: CollatorPair,707	announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,708) -> Result<(), sc_service::Error>709where710	ExecutorDispatch: NativeExecutionDispatch + 'static,711	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>712		+ Send713		+ Sync714		+ 'static,715	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,716	Runtime: RuntimeInstance,717{718	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;719720	let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(721		task_manager.spawn_handle(),722		client.clone(),723		transaction_pool,724		prometheus_registry,725		telemetry.clone(),726	);727	let proposer = Proposer::new(proposer_factory);728729	let collator_service = CollatorService::new(730		client.clone(),731		Arc::new(task_manager.spawn_handle()),732		announce_block,733		client.clone(),734	);735736	let block_import = ParachainBlockImport::new(client.clone(), backend);737738	let params = BuildAuraConsensusParams {739		create_inherent_data_providers: move |_, ()| async move { Ok(()) },740		block_import,741		para_client: client,742		#[cfg(feature = "lookahead")]743		para_backend: backend,744		para_id,745		relay_client: relay_chain_interface,746		sync_oracle,747		keystore,748		slot_duration,749		proposer,750		collator_service,751		// With async-baking, we allowed to be both slower (longer authoring) and faster (multiple para blocks per relay block)752		authoring_duration: Duration::from_millis(500),753		overseer_handle,754		#[cfg(feature = "lookahead")]755		code_hash_provider: || {},756		collator_key,757		relay_chain_slot_duration,758	};759760	task_manager.spawn_essential_handle().spawn(761		"aura",762		None,763		run_aura::<_, AuraAuthorityPair, _, _, _, _, _, _, _>(params),764	);765	Ok(())766}767768fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(769	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,770	_: Arc<FullBackend>,771	config: &Configuration,772	_: Option<TelemetryHandle>,773	task_manager: &TaskManager,774) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>775where776	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>777		+ Send778		+ Sync779		+ 'static,780	RuntimeApi::RuntimeApi:781		sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> + sp_api::ApiExt<Block>,782	ExecutorDispatch: NativeExecutionDispatch + 'static,783{784	Ok(sc_consensus_manual_seal::import_queue(785		Box::new(client),786		&task_manager.spawn_essential_handle(),787		config.prometheus_registry(),788	))789}790791pub struct OtherPartial {792	pub telemetry: Option<Telemetry>,793	pub telemetry_worker_handle: Option<TelemetryWorkerHandle>,794	pub eth_filter_pool: Option<FilterPool>,795	pub eth_backend: Arc<fc_db::kv::Backend<Block>>,796}797798struct DefaultEthConfig<C>(PhantomData<C>);799impl<C> EthConfig<Block, C> for DefaultEthConfig<C>800where801	C: StorageProvider<Block, FullBackend> + Sync + Send + 'static,802{803	type EstimateGasAdapter = ();804	type RuntimeStorageOverride = SystemAccountId32StorageOverride<Block, C, FullBackend>;805}806807/// Builds a new development service. This service uses instant seal, and mocks808/// the parachain inherent809pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(810	config: Configuration,811	autoseal_interval: u64,812	autoseal_finalize_delay: Option<u64>,813	disable_autoseal_on_tx: bool,814) -> sc_service::error::Result<TaskManager>815where816	Runtime: RuntimeInstance + Send + Sync + 'static,817	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,818	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,819	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>820		+ Send821		+ Sync822		+ 'static,823	RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,824	ExecutorDispatch: NativeExecutionDispatch + 'static,825{826	use fc_consensus::FrontierBlockImport;827	use sc_consensus_manual_seal::{828		run_manual_seal, run_delayed_finalize, EngineCommand, ManualSealParams,829		DelayedFinalizeParams,830	};831832	let sc_service::PartialComponents {833		client,834		backend,835		mut task_manager,836		import_queue,837		keystore_container,838		select_chain: maybe_select_chain,839		transaction_pool,840		other:841			OtherPartial {842				telemetry,843				eth_filter_pool,844				eth_backend,845				telemetry_worker_handle: _,846			},847	} = new_partial::<Runtime, RuntimeApi, ExecutorDispatch, _>(848		&config,849		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,850	)?;851	let net_config = sc_network::config::FullNetworkConfiguration::new(&config.network);852	let prometheus_registry = config.prometheus_registry().cloned();853854	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =855		sc_service::build_network(sc_service::BuildNetworkParams {856			config: &config,857			net_config,858			client: client.clone(),859			transaction_pool: transaction_pool.clone(),860			spawn_handle: task_manager.spawn_handle(),861			import_queue,862			block_announce_validator_builder: None,863			warp_sync_params: None,864		})?;865866	let collator = config.role.is_authority();867868	let select_chain = maybe_select_chain;869870	if collator {871		let block_import = FrontierBlockImport::new(client.clone(), client.clone());872873		let env = sc_basic_authorship::ProposerFactory::new(874			task_manager.spawn_handle(),875			client.clone(),876			transaction_pool.clone(),877			prometheus_registry.as_ref(),878			telemetry.as_ref().map(|x| x.handle()),879		);880881		let transactions_commands_stream: Box<882			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,883		> = Box::new(884			transaction_pool885				.pool()886				.validated_pool()887				.import_notification_stream()888				.filter(move |_| futures::future::ready(!disable_autoseal_on_tx))889				.map(|_| EngineCommand::SealNewBlock {890					create_empty: true,891					finalize: false,892					parent_hash: None,893					sender: None,894				}),895		);896897		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));898899		let idle_commands_stream: Box<900			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,901		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {902			create_empty: true,903			finalize: false,904			parent_hash: None,905			sender: None,906		}));907908		let commands_stream = select(transactions_commands_stream, idle_commands_stream);909910		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;911		let client_set_aside_for_cidp = client.clone();912913		if let Some(delay_sec) = autoseal_finalize_delay {914			let spawn_handle = task_manager.spawn_handle();915916			task_manager.spawn_essential_handle().spawn_blocking(917				"finalization_task",918				Some("block-authoring"),919				run_delayed_finalize(DelayedFinalizeParams {920					client: client.clone(),921					delay_sec,922					spawn_handle,923				}),924			);925		}926927		task_manager.spawn_essential_handle().spawn_blocking(928			"authorship_task",929			Some("block-authoring"),930			run_manual_seal(ManualSealParams {931				block_import,932				env,933				client: client.clone(),934				pool: transaction_pool.clone(),935				commands_stream,936				select_chain: select_chain.clone(),937				consensus_data_provider: None,938				create_inherent_data_providers: move |block: Hash, ()| {939					let current_para_block = client_set_aside_for_cidp940						.number(block)941						.expect("Header lookup should succeed")942						.expect("Header passed in as parent should be present in backend.");943944					let client_for_xcm = client_set_aside_for_cidp.clone();945					async move {946						let time = sp_timestamp::InherentDataProvider::from_system_time();947948						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {949							current_para_block,950							relay_offset: 1000,951							relay_blocks_per_para_block: 2,952							para_blocks_per_relay_epoch: 0,953							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(954								&*client_for_xcm,955								block,956								Default::default(),957								Default::default(),958							),959							relay_randomness_config: (),960							raw_downward_messages: vec![],961							raw_horizontal_messages: vec![],962						};963964						let slot =965						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(966							*time,967							slot_duration,968						);969970						Ok((time, slot, mocked_parachain))971					}972				},973			}),974		);975	}976977	#[cfg(feature = "pov-estimate")]978	let rpc_backend = backend.clone();979980	let runtime_id = config.chain_spec.runtime_id();981982	// Frontier983	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));984	let fee_history_limit = 2048;985986	let eth_pubsub_notification_sinks: Arc<987		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,988	> = Default::default();989990	let overrides = overrides_handle(client.clone());991	let eth_block_data_cache = spawn_frontier_tasks(992		FrontierTaskParams {993			client: client.clone(),994			substrate_backend: backend.clone(),995			eth_filter_pool: eth_filter_pool.clone(),996			eth_backend: eth_backend.clone(),997			fee_history_limit,998			fee_history_cache: fee_history_cache.clone(),999			task_manager: &task_manager,1000			prometheus_registry,1001			overrides: overrides.clone(),1002			sync_strategy: SyncStrategy::Normal,1003		},1004		sync_service.clone(),1005		eth_pubsub_notification_sinks.clone(),1006	);10071008	// Rpc1009	let rpc_builder = Box::new({1010		clone!(1011			client,1012			backend,1013			eth_backend,1014			eth_pubsub_notification_sinks,1015			fee_history_cache,1016			eth_block_data_cache,1017			overrides,1018			transaction_pool,1019			network,1020			sync_service,1021		);1022		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {1023			clone!(1024				backend,1025				eth_block_data_cache,1026				client,1027				eth_backend,1028				eth_filter_pool,1029				eth_pubsub_notification_sinks,1030				fee_history_cache,1031				eth_block_data_cache,1032				network,1033				runtime_id,1034				transaction_pool,1035				select_chain,1036				overrides,1037			);10381039			#[cfg(not(feature = "pov-estimate"))]1040			let _ = backend;10411042			let mut rpc_module = RpcModule::new(());10431044			let full_deps = FullDeps {1045				runtime_id,10461047				#[cfg(feature = "pov-estimate")]1048				exec_params: uc_rpc::pov_estimate::ExecutorParams {1049					wasm_method: config.wasm_method,1050					default_heap_pages: config.default_heap_pages,1051					max_runtime_instances: config.max_runtime_instances,1052					runtime_cache_size: config.runtime_cache_size,1053				},10541055				#[cfg(feature = "pov-estimate")]1056				backend,1057				// eth_backend,1058				deny_unsafe,1059				client: client.clone(),1060				pool: transaction_pool.clone(),1061				select_chain,1062			};10631064			create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;10651066			let eth_deps = EthDeps {1067				client,1068				graph: transaction_pool.pool().clone(),1069				pool: transaction_pool,1070				is_authority: true,1071				network,1072				eth_backend,1073				// TODO: Unhardcode1074				max_past_logs: 10000,1075				fee_history_limit,1076				fee_history_cache,1077				eth_block_data_cache,1078				// TODO: Unhardcode1079				enable_dev_signer: false,1080				eth_filter_pool,1081				eth_pubsub_notification_sinks,1082				overrides,1083				sync: sync_service.clone(),1084				// We don't have any inherents except parachain built-ins, which we can't even extract from inside `run_aura`.1085				pending_create_inherent_data_providers: |_, ()| async move { Ok(()) },1086			};10871088			create_eth::<1089				_,1090				_,1091				_,1092				_,1093				_,1094				_,1095				DefaultEthConfig<FullClient<RuntimeApi, ExecutorDispatch>>,1096			>(1097				&mut rpc_module,1098				eth_deps,1099				subscription_task_executor.clone(),1100			)?;11011102			Ok(rpc_module)1103		}1104	});11051106	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1107		network,1108		sync_service,1109		client,1110		keystore: keystore_container.keystore(),1111		task_manager: &mut task_manager,1112		transaction_pool,1113		rpc_builder,1114		backend,1115		system_rpc_tx,1116		config,1117		telemetry: None,1118		tx_handler_controller,1119	})?;11201121	network_starter.start_network();1122	Ok(task_manager)1123}11241125fn overrides_handle<C, BE>(client: Arc<C>) -> Arc<OverrideHandle<Block>>1126where1127	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,1128	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,1129	C: Send + Sync + 'static,1130	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,1131	BE: Backend<Block> + 'static,1132	BE::State: StateBackend<BlakeTwo256>,1133{1134	let mut overrides_map = BTreeMap::new();1135	overrides_map.insert(1136		EthereumStorageSchema::V1,1137		Box::new(SchemaV1Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1138	);1139	overrides_map.insert(1140		EthereumStorageSchema::V2,1141		Box::new(SchemaV2Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1142	);1143	overrides_map.insert(1144		EthereumStorageSchema::V3,1145		Box::new(SchemaV3Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1146	);11471148	Arc::new(OverrideHandle {1149		schemas: overrides_map,1150		fallback: Box::new(RuntimeApiStorageOverride::new(client)),1151	})1152}11531154pub struct FrontierTaskParams<'a, C, B> {1155	pub task_manager: &'a TaskManager,1156	pub client: Arc<C>,1157	pub substrate_backend: Arc<B>,1158	pub eth_backend: Arc<fc_db::kv::Backend<Block>>,1159	pub eth_filter_pool: Option<FilterPool>,1160	pub overrides: Arc<OverrideHandle<Block>>,1161	pub fee_history_limit: u64,1162	pub fee_history_cache: FeeHistoryCache,1163	pub sync_strategy: SyncStrategy,1164	pub prometheus_registry: Option<Registry>,1165}11661167pub fn spawn_frontier_tasks<C, B>(1168	params: FrontierTaskParams<C, B>,1169	sync: Arc<SyncingService<Block>>,1170	pubsub_notification_sinks: Arc<1171		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,1172	>,1173) -> Arc<EthBlockDataCacheTask<Block>>1174where1175	C: ProvideRuntimeApi<Block> + BlockOf,1176	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,1177	C: BlockchainEvents<Block> + StorageProvider<Block, B>,1178	C: Send + Sync + 'static,1179	C::Api: EthereumRuntimeRPCApi<Block>,1180	C::Api: BlockBuilder<Block>,1181	B: Backend<Block> + 'static,1182	B::State: StateBackend<BlakeTwo256>,1183{1184	let FrontierTaskParams {1185		task_manager,1186		client,1187		substrate_backend,1188		eth_backend,1189		eth_filter_pool,1190		overrides,1191		fee_history_limit,1192		fee_history_cache,1193		sync_strategy,1194		prometheus_registry,1195	} = params;1196	// Frontier offchain DB task. Essential.1197	// Maps emulated ethereum data to substrate native data.1198	params.task_manager.spawn_essential_handle().spawn(1199		"frontier-mapping-sync-worker",1200		Some("frontier"),1201		MappingSyncWorker::new(1202			client.import_notification_stream(),1203			Duration::new(6, 0),1204			client.clone(),1205			substrate_backend,1206			overrides.clone(),1207			eth_backend,1208			3,1209			0,1210			sync_strategy,1211			sync,1212			pubsub_notification_sinks,1213		)1214		.for_each(|()| futures::future::ready(())),1215	);12161217	// Frontier `EthFilterApi` maintenance.1218	// Manages the pool of user-created Filters.1219	if let Some(eth_filter_pool) = eth_filter_pool {1220		// Each filter is allowed to stay in the pool for 100 blocks.1221		const FILTER_RETAIN_THRESHOLD: u64 = 100;1222		params.task_manager.spawn_essential_handle().spawn(1223			"frontier-filter-pool",1224			Some("frontier"),1225			EthTask::filter_pool_task(client.clone(), eth_filter_pool, FILTER_RETAIN_THRESHOLD),1226		);1227	}12281229	// Spawn Frontier FeeHistory cache maintenance task.1230	params.task_manager.spawn_essential_handle().spawn(1231		"frontier-fee-history",1232		Some("frontier"),1233		EthTask::fee_history_task(1234			client,1235			overrides.clone(),1236			fee_history_cache,1237			fee_history_limit,1238		),1239	);12401241	Arc::new(EthBlockDataCacheTask::new(1242		task_manager.spawn_handle(),1243		overrides,1244		50,1245		50,1246		prometheus_registry,1247	))1248}
modifiedpallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -32,7 +32,7 @@
 fn set_admin<T>() -> Result<T::AccountId, sp_runtime::DispatchError>
 where
 	T: Config + pallet_unique::Config + pallet_evm_migration::Config,
-	T::BlockNumber: From<u32> + Into<u32>,
+	BlockNumberFor<T>: From<u32> + Into<u32>,
 	BalanceOf<T>: Sum + From<u128>,
 {
 	let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
@@ -53,7 +53,7 @@
 benchmarks! {
 	where_clause{
 		where T:  Config + pallet_unique::Config + pallet_evm_migration::Config ,
-		T::BlockNumber: From<u32> + Into<u32>,
+		BlockNumberFor<T>: From<u32> + Into<u32>,
 		BalanceOf<T>: Sum + From<u128>
 	}
 
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -125,11 +125,11 @@
 
 		/// In relay blocks.
 		#[pallet::constant]
-		type RecalculationInterval: Get<Self::BlockNumber>;
+		type RecalculationInterval: Get<BlockNumberFor<Self>>;
 
 		/// In parachain blocks.
 		#[pallet::constant]
-		type PendingInterval: Get<Self::BlockNumber>;
+		type PendingInterval: Get<BlockNumberFor<Self>>;
 
 		/// Rate of return for interval in blocks defined in `RecalculationInterval`.
 		#[pallet::constant]
@@ -146,7 +146,7 @@
 		type WeightInfo: WeightInfo;
 
 		// The relay block number provider
-		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
+		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
 
 		/// Events compatible with [`frame_system::Config::Event`].
 		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
@@ -230,9 +230,9 @@
 	pub type Staked<T: Config> = StorageNMap<
 		Key = (
 			Key<Blake2_128Concat, T::AccountId>,
-			Key<Twox64Concat, T::BlockNumber>,
+			Key<Twox64Concat, BlockNumberFor<T>>,
 		),
-		Value = (BalanceOf<T>, T::BlockNumber),
+		Value = (BalanceOf<T>, BlockNumberFor<T>),
 		QueryKind = ValueQuery,
 	>;
 
@@ -252,7 +252,7 @@
 	pub type PendingUnstake<T: Config> = StorageMap<
 		_,
 		Twox64Concat,
-		T::BlockNumber,
+		BlockNumberFor<T>,
 		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,
 		ValueQuery,
 	>;
@@ -262,16 +262,16 @@
 	#[pallet::storage]
 	#[pallet::getter(fn get_next_calculated_record)]
 	pub type PreviousCalculatedRecord<T: Config> =
-		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;
+		StorageValue<Value = (T::AccountId, BlockNumberFor<T>), QueryKind = OptionQuery>;
 
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
 		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize
 		/// implies the execution of a strictly limited number of relatively lightweight operations.
 		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.
-		fn on_initialize(current_block_number: T::BlockNumber) -> Weight
+		fn on_initialize(current_block_number: BlockNumberFor<T>) -> Weight
 		where
-			<T as frame_system::Config>::BlockNumber: From<u32>,
+			BlockNumberFor<T>: From<u32>,
 		{
 			if T::IsMaintenanceModeEnabled::get() {
 				return T::DbWeight::get().reads_writes(1, 0);
@@ -302,7 +302,7 @@
 	#[pallet::call]
 	impl<T: Config> Pallet<T>
 	where
-		T::BlockNumber: From<u32> + Into<u32>,
+		BlockNumberFor<T>: From<u32> + Into<u32>,
 		<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,
 	{
 		/// Sets an address as the the admin.
@@ -369,7 +369,7 @@
 
 			// Calculation of the number of recalculation periods,
 			// after how much the first interest calculation should be performed for the stake
-			let recalculate_after_interval: T::BlockNumber =
+			let recalculate_after_interval: BlockNumberFor<T> =
 				if block_number % config.recalculation_interval == 0u32.into() {
 					1u32.into()
 				} else {
@@ -705,7 +705,7 @@
 		#[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]
 		pub fn force_unstake(
 			origin: OriginFor<T>,
-			pending_blocks: Vec<T::BlockNumber>,
+			pending_blocks: Vec<BlockNumberFor<T>>,
 		) -> DispatchResult {
 			ensure_root(origin)?;
 
@@ -917,7 +917,7 @@
 	/// - `staker`: staker account.
 	pub fn total_staked_by_id_per_block(
 		staker: impl EncodeLike<T::AccountId>,
-	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {
+	) -> Option<Vec<(BlockNumberFor<T>, BalanceOf<T>)>> {
 		let mut staked = Staked::<T>::iter_prefix((staker,))
 			.map(|(block, (amount, _))| (block, amount))
 			.collect::<Vec<_>>();
@@ -944,14 +944,14 @@
 	/// - `staker`: staker account.
 	pub fn cross_id_total_staked_per_block(
 		staker: T::CrossAccountId,
-	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {
+	) -> Vec<(BlockNumberFor<T>, BalanceOf<T>)> {
 		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()
 	}
 
 	fn recalculate_and_insert_stake(
 		staker: &T::AccountId,
-		staked_block: T::BlockNumber,
-		next_recalc_block: T::BlockNumber,
+		staked_block: BlockNumberFor<T>,
+		next_recalc_block: BlockNumberFor<T>,
 		base: BalanceOf<T>,
 		iters: u32,
 		income_acc: &mut BalanceOf<T>,
@@ -979,9 +979,9 @@
 	/// Get relay block number rounded down to multiples of config.recalculation_interval.
 	/// We need it to reward stakers in integer parts of recalculation_interval
 	fn get_current_recalc_block(
-		current_relay_block: T::BlockNumber,
+		current_relay_block: BlockNumberFor<T>,
 		config: &PalletConfiguration<T>,
-	) -> T::BlockNumber {
+	) -> BlockNumberFor<T> {
 		(current_relay_block / config.recalculation_interval) * config.recalculation_interval
 	}
 
@@ -1028,7 +1028,7 @@
 	/// - `staker`: staker account.
 	pub fn cross_id_pending_unstake_per_block(
 		staker: T::CrossAccountId,
-	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {
+	) -> Vec<(BlockNumberFor<T>, BalanceOf<T>)> {
 		let mut unsorted_res = vec![];
 		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {
 			pendings.into_iter().for_each(|(id, amount)| {
modifiedpallets/app-promotion/src/types.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -114,9 +114,9 @@
 }
 pub(crate) struct PalletConfiguration<T: crate::Config> {
 	/// In relay blocks.
-	pub recalculation_interval: T::BlockNumber,
+	pub recalculation_interval: BlockNumberFor<T>,
 	/// In parachain blocks.
-	pub pending_interval: T::BlockNumber,
+	pub pending_interval: BlockNumberFor<T>,
 	/// Value for `RecalculationInterval` based on 0.05% per 24h.
 	pub interval_income: Perbill,
 	/// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.
modifiedpallets/collator-selection/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/benchmarking.rs
+++ b/pallets/collator-selection/src/benchmarking.rs
@@ -51,6 +51,10 @@
 use pallet_session::{self as session, SessionManager};
 use sp_std::prelude::*;
 
+use super::*;
+#[allow(unused)]
+use crate::{BalanceOf, Pallet as CollatorSelection};
+
 const SEED: u32 = 0;
 
 // TODO: remove if this is given in substrate commit.
@@ -317,7 +321,7 @@
 			balance_unit::<T>() * 4u32.into(),
 		);
 		let author = account("author", 0, SEED);
-		let new_block: T::BlockNumber = 10u32.into();
+		let new_block: BlockNumberFor<T>= 10u32.into();
 
 		frame_system::Pallet::<T>::set_block_number(new_block);
 		assert!(T::Currency::balance(&author) == 0u32.into());
@@ -338,7 +342,7 @@
 		register_validators::<T>(c);
 		register_candidates::<T>(c);
 
-		let new_block: T::BlockNumber = 1800u32.into();
+		let new_block: BlockNumberFor<T>= 1800u32.into();
 		let zero_block: T::BlockNumber = 0u32.into();
 		let candidates = <Candidates<T>>::get();
 
modifiedpallets/collator-selection/src/lib.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/lib.rs
+++ b/pallets/collator-selection/src/lib.rs
@@ -131,8 +131,11 @@
 	pub trait Config: frame_system::Config {
 		/// Overarching event type.
 		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+		/// Overarching hold reason.
+		type RuntimeHoldReason: From<HoldReason>;
+
 		type Currency: Mutate<Self::AccountId>
-			+ MutateHold<Self::AccountId>
+			+ MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
 			+ BalancedHold<Self::AccountId>;
 
 		/// Origin that can dictate updating parameters of this pallet.
@@ -164,14 +167,17 @@
 		/// The weight information of this pallet.
 		type WeightInfo: WeightInfo;
 
-		#[pallet::constant]
-		type LicenceBondIdentifier: Get<<Self::Currency as InspectHold<Self::AccountId>>::Reason>;
-
 		type DesiredCollators: Get<u32>;
 
 		type LicenseBond: Get<BalanceOf<Self>>;
 
-		type KickThreshold: Get<Self::BlockNumber>;
+		type KickThreshold: Get<BlockNumberFor<Self>>;
+	}
+
+	#[pallet::composite_enum]
+	pub enum HoldReason {
+		/// The funds are held as the license bond.
+		LicenseBond,
 	}
 
 	#[pallet::pallet]
@@ -199,14 +205,13 @@
 	#[pallet::storage]
 	#[pallet::getter(fn last_authored_block)]
 	pub type LastAuthoredBlock<T: Config> =
-		StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber, ValueQuery>;
+		StorageMap<_, Twox64Concat, T::AccountId, BlockNumberFor<T>, ValueQuery>;
 
 	#[pallet::genesis_config]
 	pub struct GenesisConfig<T: Config> {
 		pub invulnerables: Vec<T::AccountId>,
 	}
 
-	#[cfg(feature = "std")]
 	impl<T: Config> Default for GenesisConfig<T> {
 		fn default() -> Self {
 			Self {
@@ -216,12 +221,11 @@
 	}
 
 	#[pallet::genesis_build]
-	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
 		fn build(&self) {
-			let duplicate_invulnerables = self
-				.invulnerables
-				.iter()
-				.collect::<std::collections::BTreeSet<_>>();
+			use sp_std::collections::btree_set::BTreeSet;
+
+			let duplicate_invulnerables = self.invulnerables.iter().collect::<BTreeSet<_>>();
 			assert!(
 				duplicate_invulnerables.len() == self.invulnerables.len(),
 				"duplicate invulnerables in genesis."
@@ -375,7 +379,7 @@
 
 			let deposit = T::LicenseBond::get();
 
-			T::Currency::hold(&T::LicenceBondIdentifier::get(), &who, deposit)?;
+			T::Currency::hold(&HoldReason::LicenseBond.into(), &who, deposit)?;
 			LicenseDepositOf::<T>::insert(who.clone(), deposit);
 
 			Self::deposit_event(Event::LicenseObtained {
@@ -538,7 +542,7 @@
 						let remaining = deposit - slashed;
 
 						let (imbalance, _) =
-							T::Currency::slash(&T::LicenceBondIdentifier::get(), who, slashed);
+							T::Currency::slash(&HoldReason::LicenseBond.into(), who, slashed);
 						deposit_returned = remaining;
 
 						T::Currency::resolve(&T::TreasuryAccountId::get(), imbalance)
@@ -548,7 +552,7 @@
 					}
 
 					T::Currency::release(
-						&T::LicenceBondIdentifier::get(),
+						&HoldReason::LicenseBond.into(),
 						who,
 						deposit_returned,
 						Precision::Exact,
@@ -608,7 +612,7 @@
 	/// Keep track of number of authored blocks per authority, uncles are counted as well since
 	/// they're a valid proof of being online.
 	impl<T: Config + pallet_authorship::Config>
-		pallet_authorship::EventHandler<T::AccountId, T::BlockNumber> for Pallet<T>
+		pallet_authorship::EventHandler<T::AccountId, BlockNumberFor<T>> for Pallet<T>
 	{
 		fn note_author(author: T::AccountId) {
 			let pot = Self::account_id();
modifiedpallets/collator-selection/src/mock.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/mock.rs
+++ b/pallets/collator-selection/src/mock.rs
@@ -51,18 +51,14 @@
 
 // Configure a mock runtime to test the pallet.
 frame_support::construct_runtime!(
-	pub enum Test where
-		Block = Block,
-		NodeBlock = Block,
-		UncheckedExtrinsic = UncheckedExtrinsic,
-	{
-		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
-		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
-		Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
-		Aura: pallet_aura::{Pallet, Storage, Config<T>},
-		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
-		CollatorSelection: collator_selection::{Pallet, Call, Storage, Event<T>},
-		Authorship: pallet_authorship::{Pallet, Storage},
+	pub enum Test {
+		System: frame_system,
+		Timestamp: pallet_timestamp,
+		Session: pallet_session,
+		Aura: pallet_aura,
+		Balances: pallet_balances,
+		CollatorSelection: collator_selection,
+		Authorship: pallet_authorship,
 	}
 );
 
@@ -78,13 +74,11 @@
 	type DbWeight = ();
 	type RuntimeOrigin = RuntimeOrigin;
 	type RuntimeCall = RuntimeCall;
-	type Index = u64;
-	type BlockNumber = u64;
+	type Nonce = u64;
 	type Hash = H256;
 	type Hashing = BlakeTwo256;
 	type AccountId = u64;
 	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
 	type RuntimeEvent = RuntimeEvent;
 	type BlockHashCount = BlockHashCount;
 	type Version = ();
@@ -115,7 +109,6 @@
 	type MaxLocks = ();
 	type MaxReserves = MaxReserves;
 	type ReserveIdentifier = [u8; 8];
-	type HoldIdentifier = [u8; 16];
 	type FreezeIdentifier = [u8; 16];
 	type MaxHolds = MaxHolds;
 	type MaxFreezes = MaxFreezes;
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -463,7 +463,6 @@
 	#[pallet::genesis_config]
 	pub struct GenesisConfig<T>(PhantomData<T>);
 
-	#[cfg(feature = "std")]
 	impl<T: Config> Default for GenesisConfig<T> {
 		fn default() -> Self {
 			Self(Default::default())
@@ -471,7 +470,7 @@
 	}
 
 	#[pallet::genesis_build]
-	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
 		fn build(&self) {
 			StorageVersion::new(1).put::<Pallet<T>>();
 		}
modifiedpallets/configuration/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/configuration/src/benchmarking.rs
+++ b/pallets/configuration/src/benchmarking.rs
@@ -52,7 +52,7 @@
 	}
 
 	set_app_promotion_configuration_override {
-		let configuration: AppPromotionConfiguration<T::BlockNumber> = Default::default();
+		let configuration: AppPromotionConfiguration<BlockNumberFor<T>> = Default::default();
 	}: {
 		assert_ok!(
 			<Pallet<T>>::set_app_promotion_configuration_override(RawOrigin::Root.into(), configuration)
@@ -82,7 +82,7 @@
 	}
 
 	set_collator_selection_kick_threshold {
-		let threshold: Option<T::BlockNumber> = Some(900u32.into());
+		let threshold: Option<BlockNumberFor<T>> = Some(900u32.into());
 	}: {
 		assert_ok!(
 			<Pallet<T>>::set_collator_selection_kick_threshold(RawOrigin::Root.into(), threshold)
modifiedpallets/configuration/src/lib.rsdiffbeforeafterboth
--- a/pallets/configuration/src/lib.rs
+++ b/pallets/configuration/src/lib.rs
@@ -80,14 +80,14 @@
 		#[pallet::constant]
 		type AppPromotionDailyRate: Get<Perbill>;
 		#[pallet::constant]
-		type DayRelayBlocks: Get<Self::BlockNumber>;
+		type DayRelayBlocks: Get<BlockNumberFor<Self>>;
 
 		#[pallet::constant]
 		type DefaultCollatorSelectionMaxCollators: Get<u32>;
 		#[pallet::constant]
 		type DefaultCollatorSelectionLicenseBond: Get<Self::Balance>;
 		#[pallet::constant]
-		type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;
+		type DefaultCollatorSelectionKickThreshold: Get<BlockNumberFor<Self>>;
 
 		/// The weight information of this pallet.
 		type WeightInfo: WeightInfo;
@@ -103,7 +103,7 @@
 			bond_cost: Option<T::Balance>,
 		},
 		NewCollatorKickThreshold {
-			length_in_blocks: Option<T::BlockNumber>,
+			length_in_blocks: Option<BlockNumberFor<T>>,
 		},
 	}
 
@@ -134,7 +134,6 @@
 	#[pallet::genesis_config]
 	pub struct GenesisConfig<T>(PhantomData<T>);
 
-	#[cfg(feature = "std")]
 	impl<T: Config> Default for GenesisConfig<T> {
 		fn default() -> Self {
 			Self(Default::default())
@@ -142,7 +141,7 @@
 	}
 
 	#[pallet::genesis_build]
-	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
 		fn build(&self) {
 			update_base_fee::<T>();
 		}
@@ -166,7 +165,7 @@
 
 	#[pallet::storage]
 	pub type AppPromomotionConfigurationOverride<T: Config> =
-		StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;
+		StorageValue<Value = AppPromotionConfiguration<BlockNumberFor<T>>, QueryKind = ValueQuery>;
 
 	#[pallet::storage]
 	pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<
@@ -184,7 +183,7 @@
 
 	#[pallet::storage]
 	pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = ValueQuery,
 		OnEmpty = T::DefaultCollatorSelectionKickThreshold,
 	>;
@@ -228,7 +227,7 @@
 		#[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]
 		pub fn set_app_promotion_configuration_override(
 			origin: OriginFor<T>,
-			mut configuration: AppPromotionConfiguration<T::BlockNumber>,
+			mut configuration: AppPromotionConfiguration<BlockNumberFor<T>>,
 		) -> DispatchResult {
 			ensure_root(origin)?;
 			if configuration.interval_income.is_some() {
@@ -287,7 +286,7 @@
 		#[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]
 		pub fn set_collator_selection_kick_threshold(
 			origin: OriginFor<T>,
-			threshold: Option<T::BlockNumber>,
+			threshold: Option<BlockNumberFor<T>>,
 		) -> DispatchResult {
 			ensure_root(origin)?;
 			if let Some(threshold) = threshold {
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -422,7 +422,7 @@
 		{
 			return None;
 		}
-		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+		let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 
 		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {
 			let limit = <SponsoringRateLimit<T>>::get(contract_address);
modifiedpallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -53,7 +53,7 @@
 
 		/// In case of enabled sponsoring, but no sponsoring rate limit set,
 		/// this value will be used implicitly
-		type DefaultSponsoringRateLimit: Get<Self::BlockNumber>;
+		type DefaultSponsoringRateLimit: Get<BlockNumberFor<Self>>;
 	}
 
 	#[pallet::error]
@@ -115,7 +115,7 @@
 	pub(super) type SponsoringRateLimit<T: Config> = StorageMap<
 		Hasher = Twox128,
 		Key = H160,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = ValueQuery,
 		OnEmpty = T::DefaultSponsoringRateLimit,
 	>;
@@ -139,7 +139,7 @@
 		Key1 = H160,
 		Hasher2 = Twox128,
 		Key2 = H160,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 
@@ -393,7 +393,7 @@
 		}
 
 		/// Set duration between two sponsored contract calls
-		pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: T::BlockNumber) {
+		pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: BlockNumberFor<T>) {
 			<SponsoringRateLimit<T>>::insert(contract, rate_limit);
 		}
 
modifiedpallets/evm-migration/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/evm-migration/src/benchmarking.rs
+++ b/pallets/evm-migration/src/benchmarking.rs
@@ -23,7 +23,7 @@
 use sp_std::{vec::Vec, vec};
 
 benchmarks! {
-	where_clause { where <T as Config>::RuntimeEvent: codec::Encode }
+	where_clause { where <T as Config>::RuntimeEvent: parity_scale_codec::Encode }
 
 	begin {
 	}: _(RawOrigin::Root, H160::default())
@@ -59,7 +59,7 @@
 
 	insert_events {
 		let b in 0..200;
-		use codec::Encode;
+		use parity_scale_codec::Encode;
 		let logs = (0..b).map(|_| <T as Config>::RuntimeEvent::from(crate::Event::<T>::TestEvent).encode()).collect::<Vec<_>>();
 	}: _(RawOrigin::Root, logs)
 }
modifiedpallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -30,30 +30,30 @@
 
 impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>
 where
-	T: orml_tokens::Config<CurrencyId = AssetIds>,
+	T: orml_tokens::Config<CurrencyId = AssetId>,
 	BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
 	BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
 	<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
 	<T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
 {
-	type AssetId = AssetIds;
+	type AssetId = AssetId;
 	type Balance = BalanceOf<T>;
 
 	fn total_issuance(asset: Self::AssetId) -> Self::Balance {
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible total_issuance");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()
 					.into()
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 				)
 				.into()
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => return Zero::zero(),
@@ -71,38 +71,36 @@
 	fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()
 					.into()
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 				)
 				.into()
 			}
-			AssetIds::ForeignAssetId(fid) => {
-				AssetMetadatas::<T>::get(AssetIds::ForeignAssetId(fid))
-					.map(|x| x.minimal_balance)
-					.unwrap_or_else(Zero::zero)
-			}
+			AssetId::ForeignAssetId(fid) => AssetMetadatas::<T>::get(AssetId::ForeignAssetId(fid))
+				.map(|x| x.minimal_balance)
+				.unwrap_or_else(Zero::zero),
 		}
 	}
 
 	fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 				)
 				.into()
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => return Zero::zero(),
@@ -133,7 +131,7 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible reducible_balance");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(
 					who,
 					preservation,
@@ -141,9 +139,9 @@
 				)
 				.into()
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					preservation,
 					fortitude,
@@ -163,16 +161,16 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(
 					who,
 					amount.into(),
 					provenance,
 				)
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					amount.into(),
 					provenance,
@@ -219,7 +217,7 @@
 		};
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
 					Ok(val) => val,
 					Err(_) => {
@@ -240,7 +238,7 @@
 					_ => WithdrawConsequence::BalanceLow,
 				}
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
 					Ok(val) => val,
 					Err(_) => {
@@ -248,7 +246,7 @@
 					}
 				};
 				match <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_withdraw(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					parent_amount,
 				) {
@@ -269,17 +267,17 @@
 		}
 	}
 
-	fn asset_exists(asset: AssetIds) -> bool {
+	fn asset_exists(asset: AssetId) -> bool {
 		match asset {
-			AssetIds::NativeAssetId(_) => true,
-			AssetIds::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
+			AssetId::NativeAssetId(_) => true,
+			AssetId::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
 		}
 	}
 }
 
 impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>
 where
-	T: orml_tokens::Config<CurrencyId = AssetIds>,
+	T: orml_tokens::Config<CurrencyId = AssetId>,
 	BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
 	BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
 	<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
@@ -295,22 +293,22 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(
 					who,
 					amount.into(),
 				)
 				.map(Into::into)
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					amount.into(),
 				)
 				.map(Into::into)
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => {
@@ -349,7 +347,7 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				<pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(
 					who,
 					amount.into(),
@@ -358,9 +356,9 @@
 				)
 				.map(Into::into)
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				<orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					who,
 					amount.into(),
 					precision,
@@ -368,7 +366,7 @@
 				)
 				.map(Into::into)
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => {
@@ -401,7 +399,7 @@
 		log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible transfer");
 
 		match asset {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => {
+			AssetId::NativeAssetId(NativeCurrency::Here) => {
 				match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::transfer(
 					source,
 					dest,
@@ -414,9 +412,9 @@
 					)),
 				}
 			}
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => {
 				match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::transfer(
-					AssetIds::NativeAssetId(NativeCurrency::Parent),
+					AssetId::NativeAssetId(NativeCurrency::Parent),
 					source,
 					dest,
 					amount.into(),
@@ -426,7 +424,7 @@
 					Err(e) => Err(e),
 				}
 			}
-			AssetIds::ForeignAssetId(fid) => {
+			AssetId::ForeignAssetId(fid) => {
 				let target_collection_id = match <AssetBinding<T>>::get(fid) {
 					Some(v) => v,
 					None => {
@@ -479,7 +477,7 @@
 
 impl<T: Config> fungibles::Unbalanced<<T as SystemConfig>::AccountId> for Pallet<T>
 where
-	T: orml_tokens::Config<CurrencyId = AssetIds>,
+	T: orml_tokens::Config<CurrencyId = AssetId>,
 	BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
 	BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
 	<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -79,8 +79,9 @@
 	Encode,
 	Decode,
 	TypeInfo,
+	Serialize,
+	Deserialize,
 )]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 pub enum NativeCurrency {
 	Here = 0,
 	Parent = 1,
@@ -98,9 +99,10 @@
 	Encode,
 	Decode,
 	TypeInfo,
+	Serialize,
+	Deserialize,
 )]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub enum AssetIds {
+pub enum AssetId {
 	ForeignAssetId(ForeignAssetId),
 	NativeAssetId(NativeCurrency),
 }
@@ -109,17 +111,17 @@
 	fn try_as_foreign(asset: T) -> Option<F>;
 }
 
-impl TryAsForeign<AssetIds, ForeignAssetId> for AssetIds {
-	fn try_as_foreign(asset: AssetIds) -> Option<ForeignAssetId> {
+impl TryAsForeign<AssetId, ForeignAssetId> for AssetId {
+	fn try_as_foreign(asset: AssetId) -> Option<ForeignAssetId> {
 		match asset {
-			AssetIds::ForeignAssetId(id) => Some(id),
+			Self::ForeignAssetId(id) => Some(id),
 			_ => None,
 		}
 	}
 }
 
 pub type ForeignAssetId = u32;
-pub type CurrencyId = AssetIds;
+pub type CurrencyId = AssetId;
 
 mod impl_fungibles;
 pub mod weights;
@@ -151,7 +153,7 @@
 {
 	fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {
 		log::trace!(target: "fassets::asset_metadatas", "call");
-		Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))
+		Pallet::<T>::asset_metadatas(AssetId::ForeignAssetId(foreign_asset_id))
 	}
 
 	fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {
@@ -161,7 +163,7 @@
 
 	fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
 		log::trace!(target: "fassets::get_currency_id", "call");
-		Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)
+		Pallet::<T>::location_to_currency_ids(multi_location).map(AssetId::ForeignAssetId)
 	}
 }
 
@@ -231,12 +233,12 @@
 		},
 		/// The asset registered.
 		AssetRegistered {
-			asset_id: AssetIds,
+			asset_id: AssetId,
 			metadata: AssetMetadata<BalanceOf<T>>,
 		},
 		/// The asset updated.
 		AssetUpdated {
-			asset_id: AssetIds,
+			asset_id: AssetId,
 			metadata: AssetMetadata<BalanceOf<T>>,
 		},
 	}
@@ -253,7 +255,7 @@
 	#[pallet::storage]
 	#[pallet::getter(fn foreign_asset_locations)]
 	pub type ForeignAssetLocations<T: Config> =
-		StorageMap<_, Twox64Concat, ForeignAssetId, xcm::v3::MultiLocation, OptionQuery>;
+		StorageMap<_, Twox64Concat, ForeignAssetId, staging_xcm::v3::MultiLocation, OptionQuery>;
 
 	/// The storages for CurrencyIds.
 	///
@@ -261,7 +263,7 @@
 	#[pallet::storage]
 	#[pallet::getter(fn location_to_currency_ids)]
 	pub type LocationToCurrencyIds<T: Config> =
-		StorageMap<_, Twox64Concat, xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
+		StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
 
 	/// The storages for AssetMetadatas.
 	///
@@ -269,7 +271,7 @@
 	#[pallet::storage]
 	#[pallet::getter(fn asset_metadatas)]
 	pub type AssetMetadatas<T: Config> =
-		StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;
+		StorageMap<_, Twox64Concat, AssetId, AssetMetadata<BalanceOf<T>>, OptionQuery>;
 
 	/// The storages for assets to fungible collection binding
 	///
@@ -381,7 +383,7 @@
 					*maybe_location = Some(*location);
 
 					AssetMetadatas::<T>::try_mutate(
-						AssetIds::ForeignAssetId(foreign_asset_id),
+						AssetId::ForeignAssetId(foreign_asset_id),
 						|maybe_asset_metadatas| -> DispatchResult {
 							ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);
 							*maybe_asset_metadatas = Some(metadata.clone());
@@ -413,7 +415,7 @@
 					.ok_or(Error::<T>::AssetIdNotExists)?;
 
 				AssetMetadatas::<T>::try_mutate(
-					AssetIds::ForeignAssetId(foreign_asset_id),
+					AssetId::ForeignAssetId(foreign_asset_id),
 					|maybe_asset_metadatas| -> DispatchResult {
 						ensure!(
 							maybe_asset_metadatas.is_some(),
@@ -450,7 +452,7 @@
 	traits::{
 		fungibles::Balanced, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT,
 	},
-	weights::{WeightToFeePolynomial, WeightToFee},
+	weights::{WeightToFee, WeightToFeePolynomial},
 };
 
 pub struct FreeForAll<
@@ -477,7 +479,12 @@
 		Self(Weight::default(), Zero::zero(), PhantomData)
 	}
 
-	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
+	fn buy_weight(
+		&mut self,
+		weight: Weight,
+		payment: Assets,
+		_xcm: &XcmContext,
+	) -> Result<Assets, XcmError> {
 		log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);
 		Ok(payment)
 	}
modifiedpallets/identity/src/tests.rsdiffbeforeafterboth
--- a/pallets/identity/src/tests.rs
+++ b/pallets/identity/src/tests.rs
@@ -54,14 +54,10 @@
 type Block = frame_system::mocking::MockBlock<Test>;
 
 frame_support::construct_runtime!(
-	pub enum Test where
-		Block = Block,
-		NodeBlock = Block,
-		UncheckedExtrinsic = UncheckedExtrinsic,
-	{
-		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
-		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
-		Identity: pallet_identity::{Pallet, Call, Storage, Event<T>},
+	pub enum Test {
+		System: frame_system,
+		Balances: pallet_balances,
+		Identity: pallet_identity,
 	}
 );
 
@@ -71,17 +67,16 @@
 }
 impl frame_system::Config for Test {
 	type BaseCallFilter = frame_support::traits::Everything;
+	type Block = Block;
 	type BlockWeights = ();
 	type BlockLength = ();
 	type RuntimeOrigin = RuntimeOrigin;
-	type Index = u64;
-	type BlockNumber = u64;
+	type Nonce = u64;
 	type Hash = H256;
 	type RuntimeCall = RuntimeCall;
 	type Hashing = BlakeTwo256;
 	type AccountId = u64;
 	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
 	type RuntimeEvent = RuntimeEvent;
 	type BlockHashCount = ConstU64<250>;
 	type DbWeight = ();
@@ -106,7 +101,7 @@
 	type MaxReserves = ();
 	type ReserveIdentifier = [u8; 8];
 	type WeightInfo = ();
-	type HoldIdentifier = ();
+	type RuntimeHoldReason = RuntimeHoldReason;
 	type FreezeIdentifier = ();
 	type MaxHolds = ();
 	type MaxFreezes = ();
@@ -139,8 +134,8 @@
 }
 
 pub fn new_test_ext() -> sp_io::TestExternalities {
-	let mut t = frame_system::GenesisConfig::default()
-		.build_storage::<Test>()
+	let mut t = <frame_system::GenesisConfig<Test>>::default()
+		.build_storage()
 		.unwrap();
 	pallet_balances::GenesisConfig::<Test> {
 		balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)],
modifiedpallets/identity/src/types.rsdiffbeforeafterboth
--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -77,7 +77,9 @@
 }
 
 impl Decode for Data {
-	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+	fn decode<I: parity_scale_codec::Input>(
+		input: &mut I,
+	) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
 		let b = input.read_byte()?;
 		Ok(match b {
 			0 => Data::None,
@@ -92,7 +94,7 @@
 			35 => Data::Sha256(<[u8; 32]>::decode(input)?),
 			36 => Data::Keccak256(<[u8; 32]>::decode(input)?),
 			37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),
-			_ => return Err(codec::Error::from("invalid leading byte")),
+			_ => return Err(parity_scale_codec::Error::from("invalid leading byte")),
 		})
 	}
 }
@@ -114,7 +116,7 @@
 		}
 	}
 }
-impl codec::EncodeLike for Data {}
+impl parity_scale_codec::EncodeLike for Data {}
 
 /// Add a Raw variant with the given index and a fixed sized byte array
 macro_rules! data_raw_variants {
@@ -284,7 +286,9 @@
 	}
 }
 impl Decode for IdentityFields {
-	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+	fn decode<I: parity_scale_codec::Input>(
+		input: &mut I,
+	) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
 		let field = u64::decode(input)?;
 		Ok(Self(
 			<BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,
@@ -445,7 +449,9 @@
 		MaxAdditionalFields: Get<u32>,
 	> Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>
 {
-	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+	fn decode<I: parity_scale_codec::Input>(
+		input: &mut I,
+	) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
 		let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;
 		Ok(Self {
 			judgements,
modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -73,11 +73,11 @@
 		type TreasuryAccountId: Get<Self::AccountId>;
 
 		// The block number provider
-		type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
+		type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
 
 		/// Number of blocks that pass between treasury balance updates due to inflation
 		#[pallet::constant]
-		type InflationBlockInterval: Get<Self::BlockNumber>;
+		type InflationBlockInterval: Get<BlockNumberFor<Self>>;
 	}
 
 	#[pallet::pallet]
@@ -95,22 +95,23 @@
 	/// Next target (relay) block when inflation will be applied
 	#[pallet::storage]
 	pub type NextInflationBlock<T: Config> =
-		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+		StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
 
 	/// Next target (relay) block when inflation is recalculated
 	#[pallet::storage]
 	pub type NextRecalculationBlock<T: Config> =
-		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+		StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
 
 	/// Relay block when inflation has started
 	#[pallet::storage]
-	pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+	pub type StartBlock<T: Config> =
+		StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
 
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
-		fn on_initialize(_: T::BlockNumber) -> Weight
+		fn on_initialize(_: BlockNumberFor<T>) -> Weight
 		where
-			<T as frame_system::Config>::BlockNumber: From<u32>,
+			BlockNumberFor<T>: From<u32>,
 		{
 			let mut consumed_weight = Weight::zero();
 			let mut add_weight = |reads, writes, weight| {
@@ -120,7 +121,7 @@
 
 			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
 			let current_relay_block = T::BlockNumberProvider::current_block_number();
-			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();
+			let next_inflation: BlockNumberFor<T> = <NextInflationBlock<T>>::get();
 			add_weight(1, 0, Weight::from_parts(5_000_000, 0));
 
 			// Apply inflation every InflationBlockInterval blocks
@@ -129,7 +130,7 @@
 				// Recalculate inflation on the first block of the year (or if it is not initialized yet)
 				// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"
 				// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.
-				let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();
+				let next_recalculation: BlockNumberFor<T> = <NextRecalculationBlock<T>>::get();
 				add_weight(1, 0, Weight::zero());
 				if current_relay_block >= next_recalculation {
 					Self::recalculate_inflation(next_recalculation);
@@ -169,10 +170,10 @@
 		#[pallet::weight(Weight::from_parts(0, 0))]
 		pub fn start_inflation(
 			origin: OriginFor<T>,
-			inflation_start_relay_block: T::BlockNumber,
+			inflation_start_relay_block: BlockNumberFor<T>,
 		) -> DispatchResult
 		where
-			<T as frame_system::Config>::BlockNumber: From<u32>,
+			BlockNumberFor<T>: From<u32>,
 		{
 			ensure_root(origin)?;
 
@@ -200,9 +201,9 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {
+	pub fn recalculate_inflation(recalculation_block: BlockNumberFor<T>) {
 		let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())
-			/ T::BlockNumber::from(YEAR))
+			/ BlockNumberFor::<T>::from(YEAR))
 		.try_into()
 		.unwrap_or(0);
 		let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -57,21 +57,16 @@
 	type MaxLocks = MaxLocks;
 	type MaxReserves = ();
 	type ReserveIdentifier = ();
-	type HoldIdentifier = ();
 	type FreezeIdentifier = ();
 	type MaxHolds = ();
 	type MaxFreezes = ();
 }
 
 frame_support::construct_runtime!(
-	pub enum Test where
-		Block = Block,
-		NodeBlock = Block,
-		UncheckedExtrinsic = UncheckedExtrinsic,
-	{
-		Balances: pallet_balances::{Pallet, Call, Storage},
-		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
-		Inflation: pallet_inflation::{Pallet, Call, Storage},
+	pub enum Test {
+		Balances: pallet_balances,
+		System: frame_system,
+		Inflation: pallet_inflation,
 	}
 );
 
@@ -89,13 +84,11 @@
 	type DbWeight = ();
 	type RuntimeOrigin = RuntimeOrigin;
 	type RuntimeCall = RuntimeCall;
-	type Index = u64;
-	type BlockNumber = u64;
+	type Nonce = u64;
 	type Hash = H256;
 	type Hashing = BlakeTwo256;
 	type AccountId = u64;
 	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
 	type RuntimeEvent = ();
 	type BlockHashCount = BlockHashCount;
 	type Version = ();
@@ -112,11 +105,11 @@
 parameter_types! {
 	pub TreasuryAccountId: u64 = 1234;
 	pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
-	pub static MockBlockNumberProvider: u64 = 0;
+	pub static MockBlockNumberProvider: u32 = 0;
 }
 
 impl BlockNumberProvider for MockBlockNumberProvider {
-	type BlockNumber = u64;
+	type BlockNumber = u32;
 
 	fn current_block_number() -> Self::BlockNumber {
 		Self::get()
@@ -131,8 +124,8 @@
 }
 
 pub fn new_test_ext() -> sp_io::TestExternalities {
-	frame_system::GenesisConfig::default()
-		.build_storage::<Test>()
+	<frame_system::GenesisConfig<Test>>::default()
+		.build_storage()
 		.unwrap()
 		.into()
 }
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -90,37 +90,37 @@
 
 #![cfg_attr(not(feature = "std"), no_std)]
 
+use core::ops::Deref;
+
 use erc::ERC721Events;
 use evm_coder::ToLog;
 use frame_support::{
-	BoundedVec, ensure, fail, transactional,
+	dispatch::{Pays, PostDispatchInfo},
+	ensure, fail,
+	pallet_prelude::*,
 	storage::with_transaction,
-	pallet_prelude::DispatchResultWithPostInfo,
-	pallet_prelude::Weight,
-	dispatch::{PostDispatchInfo, Pays},
-};
-use up_data_structs::{
-	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
-	mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
-	PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
-	TokenProperties as TokenPropertiesT,
+	transactional, BoundedVec,
 };
-use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
+pub use pallet::*;
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
 	eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
 	weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
 };
-use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
+use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
+use pallet_structure::{Error as StructureError, Pallet as PalletStructure};
+use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
+use scale_info::TypeInfo;
 use sp_core::{Get, H160};
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
-use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
-use core::ops::Deref;
-use codec::{Encode, Decode, MaxEncodedLen};
-use scale_info::TypeInfo;
-
-pub use pallet::*;
+use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
+use up_data_structs::{
+	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
+	mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
+	PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
+	TokenProperties as TokenPropertiesT,
+};
 use weights::WeightInfo;
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
@@ -147,13 +147,13 @@
 
 #[frame_support::pallet]
 pub mod pallet {
-	use super::*;
 	use frame_support::{
-		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,
+		pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat, Twox64Concat,
 	};
 	use up_data_structs::{CollectionId, TokenId};
-	use super::weights::WeightInfo;
 
+	use super::{weights::WeightInfo, *};
+
 	#[pallet::error]
 	pub enum Error<T> {
 		/// Not Nonfungible item data used to mint in Nonfungible collection.
@@ -285,7 +285,6 @@
 	#[pallet::genesis_config]
 	pub struct GenesisConfig<T>(PhantomData<T>);
 
-	#[cfg(feature = "std")]
 	impl<T: Config> Default for GenesisConfig<T> {
 		fn default() -> Self {
 			Self(Default::default())
@@ -293,7 +292,7 @@
 	}
 
 	#[pallet::genesis_build]
-	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
 		fn build(&self) {
 			StorageVersion::new(1).put::<Pallet<T>>();
 		}
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -174,7 +174,7 @@
 	pub type CreateItemBasket<T: Config> = StorageMap<
 		Hasher = Blake2_128Concat,
 		Key = (CollectionId, T::AccountId),
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Collection id (controlled?2), token id (controlled?2)
@@ -185,7 +185,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Blake2_128Concat,
 		Key2 = TokenId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Collection id (controlled?2), owning user (real)
@@ -196,7 +196,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Twox64Concat,
 		Key2 = T::AccountId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Collection id (controlled?2), token id (controlled?2)
@@ -208,7 +208,7 @@
 			Key<Blake2_128Concat, TokenId>,
 			Key<Twox64Concat, T::AccountId>,
 		),
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	//#endregion
@@ -221,7 +221,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Blake2_128Concat,
 		Key2 = TokenId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 
@@ -233,7 +233,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Blake2_128Concat,
 		Key2 = TokenId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Last sponsoring of fungible tokens approval in a collection
@@ -244,7 +244,7 @@
 		Key1 = CollectionId,
 		Hasher2 = Twox64Concat,
 		Key2 = T::AccountId,
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 	/// Last sponsoring of RFT approval in a collection
@@ -256,7 +256,7 @@
 			Key<Blake2_128Concat, TokenId>,
 			Key<Twox64Concat, T::AccountId>,
 		),
-		Value = T::BlockNumber,
+		Value = BlockNumberFor<T>,
 		QueryKind = OptionQuery,
 	>;
 
modifiedprimitives/common/src/constants.rsdiffbeforeafterboth
--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -28,14 +28,14 @@
 pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
 
 // These time units are defined in number of blocks.
-pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
-pub const HOURS: BlockNumber = MINUTES * 60;
-pub const DAYS: BlockNumber = HOURS * 24;
+pub const MINUTES: u32 = 60_000 / (MILLISECS_PER_BLOCK as u32);
+pub const HOURS: u32 = MINUTES * 60;
+pub const DAYS: u32 = HOURS * 24;
 
 // These time units are defined in number of relay blocks.
-pub const RELAY_MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_RELAY_BLOCK as BlockNumber);
-pub const RELAY_HOURS: BlockNumber = RELAY_MINUTES * 60;
-pub const RELAY_DAYS: BlockNumber = RELAY_HOURS * 24;
+pub const RELAY_MINUTES: u32 = 60_000 / (MILLISECS_PER_RELAY_BLOCK as u32);
+pub const RELAY_HOURS: u32 = RELAY_MINUTES * 60;
+pub const RELAY_DAYS: u32 = RELAY_HOURS * 24;
 
 pub const MICROUNIQUE: Balance = 1_000_000_000_000;
 pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;
modifiedprimitives/common/src/types.rsdiffbeforeafterboth
--- a/primitives/common/src/types.rs
+++ b/primitives/common/src/types.rs
@@ -37,10 +37,8 @@
 		Unknown(sp_std::vec::Vec<u8>),
 	}
 
-	/// Opaque block header type.
 	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
 
-	/// Opaque block type.
 	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
 
 	pub trait RuntimeInstance {
@@ -71,7 +69,7 @@
 pub type Balance = u128;
 
 /// Index of a transaction in the chain.
-pub type Index = u32;
+pub type Nonce = u32;
 
 /// A hash of some data used by the chain.
 pub type Hash = sp_core::H256;
modifiedprimitives/data-structs/src/bondrewd_codec.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/bondrewd_codec.rs
+++ b/primitives/data-structs/src/bondrewd_codec.rs
@@ -5,12 +5,14 @@
 macro_rules! bondrewd_codec {
 	($T:ty) => {
 		impl Encode for $T {
-			fn encode_to<O: codec::Output + ?Sized>(&self, dest: &mut O) {
+			fn encode_to<O: parity_scale_codec::Output + ?Sized>(&self, dest: &mut O) {
 				dest.write(&self.into_bytes())
 			}
 		}
-		impl codec::Decode for $T {
-			fn decode<I: codec::Input + ?Sized>(from: &mut I) -> Result<Self, codec::Error> {
+		impl parity_scale_codec::Decode for $T {
+			fn decode<I: parity_scale_codec::Input + ?Sized>(
+				from: &mut I,
+			) -> Result<Self, parity_scale_codec::Error> {
 				let mut bytes = [0; Self::BYTE_SIZE];
 				from.read(&mut bytes)?;
 				Ok(Self::from_bytes(bytes))
modifiedprimitives/data-structs/src/bounded.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/bounded.rs
+++ b/primitives/data-structs/src/bounded.rs
@@ -26,13 +26,13 @@
 };
 
 /// [`serde`] implementations for [`BoundedVec`].
-#[cfg(feature = "serde1")]
 pub mod vec_serde {
 	use core::convert::TryFrom;
-	use frame_support::{BoundedVec, traits::Get};
+
+	use frame_support::{traits::Get, BoundedVec};
 	use serde::{
-		ser::{self, Serialize},
 		de::{self, Deserialize, Error},
+		ser::{self, Serialize},
 	};
 	use sp_std::vec::Vec;
 
@@ -66,17 +66,17 @@
 	(v as &Vec<V>).fmt(f)
 }
 
-#[cfg(feature = "serde1")]
 #[allow(dead_code)]
 /// [`serde`] implementations for [`BoundedBTreeMap`].
 pub mod map_serde {
 	use core::convert::TryFrom;
-	use sp_std::collections::btree_map::BTreeMap;
-	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};
+
+	use frame_support::{storage::bounded_btree_map::BoundedBTreeMap, traits::Get};
 	use serde::{
+		de::{self, Deserialize, Error},
 		ser::{self, Serialize},
-		de::{self, Deserialize, Error},
 	};
+	use sp_std::collections::btree_map::BTreeMap;
 	pub fn serialize<D, K, V, S>(
 		value: &BoundedBTreeMap<K, V, S>,
 		serializer: D,
@@ -117,17 +117,17 @@
 	(v as &BTreeMap<K, V>).fmt(f)
 }
 
-#[cfg(feature = "serde1")]
 #[allow(dead_code)]
 /// [`serde`] implementations for [`BoundedBTreeSet`].
 pub mod set_serde {
 	use core::convert::TryFrom;
-	use sp_std::collections::btree_set::BTreeSet;
-	use frame_support::{traits::Get, storage::bounded_btree_set::BoundedBTreeSet};
+
+	use frame_support::{storage::bounded_btree_set::BoundedBTreeSet, traits::Get};
 	use serde::{
-		ser::{self, Serialize},
 		de::{self, Deserialize, Error},
+		ser::{self, Serialize},
 	};
+	use sp_std::collections::btree_set::BTreeSet;
 	pub fn serialize<D, K, S>(
 		value: &BoundedBTreeSet<K, S>,
 		serializer: D,
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -153,8 +153,9 @@
 	Default,
 	TypeInfo,
 	MaxEncodedLen,
+	Serialize,
+	Deserialize,
 )]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct CollectionId(pub u32);
 impl EncodeLike<u32> for CollectionId {}
 impl EncodeLike<CollectionId> for u32 {}
@@ -187,8 +188,9 @@
 	Default,
 	TypeInfo,
 	MaxEncodedLen,
+	Serialize,
+	Deserialize,
 )]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct TokenId(pub u32);
 impl EncodeLike<u32> for TokenId {}
 impl EncodeLike<TokenId> for u32 {}
@@ -221,8 +223,7 @@
 
 /// Token data.
 #[struct_versioning::versioned(version = 2, upper)]
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct TokenData<CrossAccountId> {
 	/// Properties of token.
 	pub properties: Vec<Property>,
@@ -251,8 +252,9 @@
 /// Collection can represent various types of tokens.
 /// Each collection can contain only one type of tokens at a time.
 /// This type helps to understand which tokens the collection contains.
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum CollectionMode {
 	/// Non fungible tokens.
 	NFT,
@@ -279,8 +281,19 @@
 }
 
 /// Access mode for some token operations.
-#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	Eq,
+	Debug,
+	Clone,
+	Copy,
+	PartialEq,
+	TypeInfo,
+	MaxEncodedLen,
+	Serialize,
+	Deserialize,
+)]
 pub enum AccessMode {
 	/// Access grant for owner and admins. Used as default.
 	Normal,
@@ -294,8 +307,9 @@
 }
 
 // TODO: remove in future.
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum SchemaVersion {
 	ImageURL,
 	Unique,
@@ -307,16 +321,16 @@
 }
 
 // TODO: unused type
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct Ownership<AccountId> {
 	pub owner: AccountId,
 	pub fraction: u128,
 }
 
 /// The state of collection sponsorship.
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum SponsorshipState<AccountId> {
 	/// The fees are applied to the transaction sender.
 	Disabled,
@@ -444,8 +458,7 @@
 	pub meta_update_permission: MetaUpdatePermission,
 }
 
-#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct RpcCollectionFlags {
 	/// Is collection is foreign.
 	pub foreign: bool,
@@ -455,8 +468,7 @@
 
 /// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).
 #[struct_versioning::versioned(version = 2, upper)]
-#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
 pub struct RpcCollection<AccountId> {
 	/// Collection owner account.
 	pub owner: AccountId,
@@ -538,8 +550,10 @@
 
 pub struct RawEncoded(Vec<u8>);
 
-impl codec::Decode for RawEncoded {
-	fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
+impl parity_scale_codec::Decode for RawEncoded {
+	fn decode<I: parity_scale_codec::Input>(
+		input: &mut I,
+	) -> Result<Self, parity_scale_codec::Error> {
 		let mut out = Vec::new();
 		while let Ok(v) = input.read_byte() {
 			out.push(v);
@@ -612,8 +626,18 @@
 ///
 /// Update with `pallet_common::Pallet::clamp_limits`.
 // IMPORTANT: When adding/removing fields from this struct - don't forget to also
-#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	Debug,
+	Default,
+	Clone,
+	PartialEq,
+	TypeInfo,
+	MaxEncodedLen,
+	Serialize,
+	Deserialize,
+)]
 // When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.
 // TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.
 // TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.
@@ -769,8 +793,18 @@
 /// Some fields are wrapped in [`Option`], where `None` means chain default.
 ///
 /// Update with `pallet_common::Pallet::clamp_permissions`.
-#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	Debug,
+	Default,
+	Clone,
+	PartialEq,
+	TypeInfo,
+	MaxEncodedLen,
+	Serialize,
+	Deserialize,
+)]
 // When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.
 // TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.
 pub struct CollectionPermissions {
@@ -821,11 +855,12 @@
 type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;
 
 /// Wraper for collections set allowing nest.
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative, Serialize, Deserialize,
+)]
 #[derivative(Debug)]
 pub struct OwnerRestrictedSet(
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]
+	#[serde(with = "bounded::set_serde")]
 	#[derivative(Debug(format_with = "bounded::set_debug"))]
 	pub OwnerRestrictedSetInner,
 );
@@ -862,8 +897,9 @@
 }
 
 /// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative, Serialize, Deserialize,
+)]
 #[derivative(Debug)]
 pub struct NestingPermissions {
 	/// Owner of token can nest tokens under it.
@@ -881,8 +917,9 @@
 /// Enum denominating how often can sponsoring occur if it is enabled.
 ///
 /// Used for [`collection limits`](CollectionLimits).
-#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum SponsoringRateLimit {
 	/// Sponsoring is disabled, and the collection sponsor will not pay for transactions
 	SponsoringDisabled,
@@ -891,42 +928,73 @@
 }
 
 /// Data used to describe an NFT at creation.
-#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	MaxEncodedLen,
+	Default,
+	PartialEq,
+	Clone,
+	Derivative,
+	TypeInfo,
+	Serialize,
+	Deserialize,
+)]
 #[derivative(Debug)]
 pub struct CreateNftData {
 	/// Key-value pairs used to describe the token as metadata
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+	#[serde(with = "bounded::vec_serde")]
 	#[derivative(Debug(format_with = "bounded::vec_debug"))]
 	/// Properties that wil be assignet to created item.
 	pub properties: CollectionPropertiesVec,
 }
 
 /// Data used to describe a Fungible token at creation.
-#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	MaxEncodedLen,
+	Default,
+	Debug,
+	Clone,
+	PartialEq,
+	TypeInfo,
+	Serialize,
+	Deserialize,
+)]
 pub struct CreateFungibleData {
 	/// Number of fungible coins minted
 	pub value: u128,
 }
 
 /// Data used to describe a Refungible token at creation.
-#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	MaxEncodedLen,
+	Default,
+	PartialEq,
+	Clone,
+	Derivative,
+	TypeInfo,
+	Serialize,
+	Deserialize,
+)]
 #[derivative(Debug)]
 pub struct CreateReFungibleData {
 	/// Number of pieces the RFT is split into
 	pub pieces: u128,
 
 	/// Key-value pairs used to describe the token as metadata
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+	#[serde(with = "bounded::vec_serde")]
 	#[derivative(Debug(format_with = "bounded::vec_debug"))]
 	pub properties: CollectionPropertiesVec,
 }
 
 // TODO: remove this.
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub enum MetaUpdatePermission {
 	ItemOwner,
 	Admin,
@@ -935,8 +1003,9 @@
 
 /// Enum holding data used for creation of all three item types.
 /// Unified data for create item.
-#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
+)]
 pub enum CreateItemData {
 	/// Data for create NFT.
 	NFT(CreateNftData),
@@ -1025,8 +1094,9 @@
 }
 
 /// Token's address, dictated by its collection and token IDs.
-#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
+)]
 // todo possibly rename to be used generally as an address pair
 pub struct TokenChild {
 	/// Token id.
@@ -1037,8 +1107,9 @@
 }
 
 /// Collection statistics.
-#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
+)]
 pub struct CollectionStats {
 	/// Number of created items.
 	pub created: u32,
@@ -1060,10 +1131,9 @@
 
 	fn type_info() -> scale_info::Type {
 		use scale_info::{
-			Type, Path,
 			build::{FieldsBuilder, UnnamedFields},
 			form::MetaForm,
-			type_params,
+			type_params, Path, Type,
 		};
 		Type::builder()
 			.path(Path::new("up_data_structs", "PhantomType"))
@@ -1092,8 +1162,18 @@
 pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
 
 /// Property permission.
-#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Default)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode,
+	Decode,
+	TypeInfo,
+	Debug,
+	MaxEncodedLen,
+	PartialEq,
+	Clone,
+	Default,
+	Serialize,
+	Deserialize,
+)]
 pub struct PropertyPermission {
 	/// Permission to change the property and property permission.
 	///
@@ -1119,15 +1199,16 @@
 }
 
 /// Property is simpl key-value record.
-#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen, Serialize, Deserialize,
+)]
 pub struct Property {
 	/// Property key.
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+	#[serde(with = "bounded::vec_serde")]
 	pub key: PropertyKey,
 
 	/// Property value.
-	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+	#[serde(with = "bounded::vec_serde")]
 	pub value: PropertyValue,
 }
 
@@ -1138,8 +1219,9 @@
 }
 
 /// Record for proprty key permission.
-#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derive(
+	Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Serialize, Deserialize,
+)]
 pub struct PropertyKeyPermission {
 	/// Key.
 	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
@@ -1362,7 +1444,7 @@
 	scoped_slice_size(PropertyScope::None, data)
 }
 fn scoped_slice_size(scope: PropertyScope, data: &[u8]) -> u32 {
-	use codec::Compact;
+	use parity_scale_codec::Compact;
 	let prefix = scope.prefix();
 	<Compact<u32>>::encoded_size(&Compact(data.len() as u32 + prefix.len() as u32)) as u32
 		+ data.len() as u32
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -82,7 +82,7 @@
 			collection: CollectionId,
 			token_id: TokenId,
 			keys: Option<Vec<Vec<u8>>>
-		) -> Result<TokenDataVersion1<CrossAccountId>>;
+		) -> Result<up_data_structs::TokenDataVersion1<CrossAccountId>>;
 
 		/// Total number of tokens in collection.
 		fn total_supply(collection: CollectionId) -> Result<u32>;
@@ -117,7 +117,7 @@
 		fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;
 
 		#[changed_in(3)]
-		fn collection_by_id(collection: CollectionId) -> Result<Option<RawEncoded>>;
+		fn collection_by_id(collection: CollectionId) -> Result<Option<up_data_structs::RawEncoded>>;
 
 		/// Get collection stats.
 		fn collection_stats() -> Result<CollectionStats>;
modifiedruntime/common/config/pallets/collator_selection.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/collator_selection.rs
+++ b/runtime/common/config/pallets/collator_selection.rs
@@ -107,6 +107,7 @@
 
 impl pallet_collator_selection::Config for Runtime {
 	type RuntimeEvent = RuntimeEvent;
+	type RuntimeHoldReason = RuntimeHoldReason;
 	type Currency = Balances;
 	// We allow root only to execute privileged collator selection operations.
 
@@ -128,7 +129,6 @@
 	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
 	type ValidatorRegistration = Session;
 	type WeightInfo = pallet_collator_selection::weights::SubstrateWeight<Runtime>;
-	type LicenceBondIdentifier = LicenceBondIdentifier;
 	type DesiredCollators = DesiredCollators;
 	type LicenseBond = LicenseBond;
 	type KickThreshold = KickThreshold;
modifiedruntime/common/config/substrate.rsdiffbeforeafterboth
--- a/runtime/common/config/substrate.rs
+++ b/runtime/common/config/substrate.rs
@@ -76,10 +76,10 @@
 	type BaseCallFilter = Everything;
 	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
 	type BlockHashCount = BlockHashCount;
+	/// The block type.
+	type Block = Block;
 	/// The maximum length of a block (in bytes).
 	type BlockLength = RuntimeBlockLength;
-	/// The index type for blocks.
-	type BlockNumber = BlockNumber;
 	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.
 	type BlockWeights = RuntimeBlockWeights;
 	/// The aggregated dispatch type that is available for extrinsics.
@@ -92,10 +92,8 @@
 	type Hash = Hash;
 	/// The hashing algorithm used.
 	type Hashing = BlakeTwo256;
-	/// The header type.
-	type Header = generic::Header<BlockNumber, BlakeTwo256>;
 	/// The index type for storing how many extrinsics an account has signed.
-	type Index = Index;
+	type Nonce = Nonce;
 	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
 	type Lookup = AccountIdLookup<AccountId, ()>;
 	/// What to do if an account is fully reaped from the system.
@@ -171,7 +169,7 @@
 	type ExistentialDeposit = ExistentialDeposit;
 	type AccountStore = System;
 	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;
-	type HoldIdentifier = [u8; 16];
+	type RuntimeHoldReason = RuntimeHoldReason;
 	type FreezeIdentifier = [u8; 16];
 	type MaxHolds = MaxHolds;
 	type MaxFreezes = MaxFreezes;
@@ -247,6 +245,7 @@
 	type AuthorityId = AuraId;
 	type DisabledValidators = ();
 	type MaxAuthorities = MaxAuthorities;
+	type AllowMultipleBlocksPerSlot = ConstBool<true>;
 }
 
 impl pallet_utility::Config for Runtime {
modifiedruntime/common/config/xcm/foreignassets.rsdiffbeforeafterboth
--- a/runtime/common/config/xcm/foreignassets.rs
+++ b/runtime/common/config/xcm/foreignassets.rs
@@ -36,17 +36,11 @@
 	pub CheckingAccount: AccountId = PolkadotXcm::check_account();
 }
 
-pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
-impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>
-	ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>
-where
-	AssetId: Borrow<AssetId>,
-	AssetId: TryAsForeign<AssetId, ForeignAssetId>,
-	AssetIds: Borrow<AssetId>,
+pub struct AsInnerId<ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
+impl<ConvertAssetId: MaybeEquivalence<AssetId, AssetId>> MaybeEquivalence<MultiLocation, AssetId>
+	for AsInnerId<ConvertAssetId>
 {
-	fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {
-		let id = id.borrow();
-
+	fn convert(id: &MultiLocation) -> Option<AssetId> {
 		log::trace!(
 			target: "xcm::AsInnerId::Convert",
 			"AsInnerId {:?}",
@@ -58,52 +52,46 @@
 		let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
 
 		if *id == parent {
-			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));
+			return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent));
 		}
 
 		if *id == here || *id == self_location {
-			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
+			return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here));
 		}
 
 		match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
-			Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
-				ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
+			Some(AssetId::ForeignAssetId(foreign_asset_id)) => {
+				ConvertAssetId::convert(&AssetId::ForeignAssetId(foreign_asset_id))
 			}
-			_ => Err(()),
+			_ => None,
 		}
 	}
 
-	fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {
+	fn convert_back(asset_id: &AssetId) -> Option<MultiLocation> {
 		log::trace!(
 			target: "xcm::AsInnerId::Reverse",
 			"AsInnerId",
 		);
-
-		let asset_id = what.borrow();
 
 		let parent_id =
-			ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();
+			ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent)).unwrap();
 		let here_id =
-			ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();
+			ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here)).unwrap();
 
 		if asset_id.clone() == parent_id {
-			return Ok(MultiLocation::parent());
+			return Some(MultiLocation::parent());
 		}
 
 		if asset_id.clone() == here_id {
-			return Ok(MultiLocation::new(
+			return Some(MultiLocation::new(
 				1,
 				X1(Parachain(ParachainInfo::get().into())),
 			));
 		}
 
-		match <AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(asset_id.clone()) {
-			Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {
-				Some(location) => Ok(location),
-				None => Err(()),
-			},
-			None => Err(()),
-		}
+		let fid =
+			<AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(asset_id.clone())?;
+		XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid)
 	}
 }
 
@@ -112,7 +100,7 @@
 	// Use this fungibles implementation:
 	ForeignAssets,
 	// Use this currency when it is a fungible asset matching the given location or name:
-	ConvertedConcreteId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,
+	ConvertedConcreteId<AssetId, Balance, AsInnerId<JustTry>, JustTry>,
 	// Convert an XCM MultiLocation into a local account id:
 	LocationToAccountId,
 	// Our chain's account ID type (we can't get away without mentioning it explicitly):
@@ -154,7 +142,7 @@
 		what: &MultiAsset,
 		who: &MultiLocation,
 		maybe_context: Option<&XcmContext>,
-	) -> Result<xcm_executor::Assets, XcmError> {
+	) -> Result<staging_xcm_executor::Assets, XcmError> {
 		FungiblesTransactor::withdraw_asset(what, who, maybe_context)
 	}
 
@@ -163,7 +151,7 @@
 		from: &MultiLocation,
 		to: &MultiLocation,
 		context: &XcmContext,
-	) -> Result<xcm_executor::Assets, XcmError> {
+	) -> Result<staging_xcm_executor::Assets, XcmError> {
 		FungiblesTransactor::internal_transfer_asset(what, from, to, context)
 	}
 }
@@ -179,15 +167,15 @@
 >;
 
 pub struct CurrencyIdConvert;
-impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
-	fn convert(id: AssetIds) -> Option<MultiLocation> {
+impl Convert<AssetId, Option<MultiLocation>> for CurrencyIdConvert {
+	fn convert(id: AssetId) -> Option<MultiLocation> {
 		match id {
-			AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
+			AssetId::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
 				1,
 				X1(Parachain(ParachainInfo::get().into())),
 			)),
-			AssetIds::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
-			AssetIds::ForeignAssetId(foreign_asset_id) => {
+			AssetId::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
+			AssetId::ForeignAssetId(foreign_asset_id) => {
 				XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
 			}
 		}
@@ -199,11 +187,11 @@
 		if location == MultiLocation::here()
 			|| location == MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())))
 		{
-			return Some(AssetIds::NativeAssetId(NativeCurrency::Here));
+			return Some(AssetId::NativeAssetId(NativeCurrency::Here));
 		}
 
 		if location == MultiLocation::parent() {
-			return Some(AssetIds::NativeAssetId(NativeCurrency::Parent));
+			return Some(AssetId::NativeAssetId(NativeCurrency::Parent));
 		}
 
 		if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
modifiedruntime/common/config/xcm/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/xcm/mod.rs
+++ b/runtime/common/config/xcm/mod.rs
@@ -153,10 +153,10 @@
 		origin: &MultiLocation,
 		message: &mut [Instruction<Call>],
 		max_weight: Weight,
-		weight_credit: &mut Weight,
+		properties: &mut Properties,
 	) -> Result<(), ProcessMessageError> {
 		Deny::try_pass(origin, message)?;
-		Allow::should_execute(origin, message, max_weight, weight_credit)
+		Allow::should_execute(origin, message, max_weight, properties)
 	}
 }
 
@@ -211,7 +211,7 @@
 }
 
 pub struct XcmExecutorConfig<T>(PhantomData<T>);
-impl<T> xcm_executor::Config for XcmExecutorConfig<T>
+impl<T> staging_xcm_executor::Config for XcmExecutorConfig<T>
 where
 	T: pallet_configuration::Config,
 {
@@ -240,6 +240,7 @@
 	type UniversalAliases = Nothing;
 	type CallDispatcher = RuntimeCall;
 	type SafeCallFilter = XcmCallFilter;
+	type Aliasers = Nothing;
 }
 
 #[cfg(feature = "runtime-benchmarks")]
modifiedruntime/common/config/xcm/nativeassets.rsdiffbeforeafterboth
--- a/runtime/common/config/xcm/nativeassets.rs
+++ b/runtime/common/config/xcm/nativeassets.rs
@@ -106,7 +106,12 @@
 		Self(Weight::from_parts(0, 0), Zero::zero(), PhantomData)
 	}
 
-	fn buy_weight(&mut self, _weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
+	fn buy_weight(
+		&mut self,
+		_weight: Weight,
+		payment: Assets,
+		_xcm: &XcmContext,
+	) -> Result<Assets, XcmError> {
 		Ok(payment)
 	}
 }
modifiedruntime/common/construct_runtime.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime.rs
+++ b/runtime/common/construct_runtime.rs
@@ -19,11 +19,7 @@
 	() => {
 		frame_support::construct_runtime! {
 
-			pub enum Runtime where
-				Block = Block,
-				NodeBlock = opaque::Block,
-				UncheckedExtrinsic = UncheckedExtrinsic
-			{
+			pub enum Runtime {
 				System: frame_system = 0,
 				StateTrieMigration: pallet_state_trie_migration = 1,
 
modifiedruntime/common/mod.rsdiffbeforeafterboth
--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -63,12 +63,15 @@
 
 /// The address format for describing accounts.
 pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
-/// Block header type as expected by this runtime.
-pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
-/// Block type as expected by this runtime.
-pub type Block = generic::Block<Header, UncheckedExtrinsic>;
 /// A Block signed with a Justification
 pub type SignedBlock = generic::SignedBlock<Block>;
+/// Frontier wrapped extrinsic
+pub type UncheckedExtrinsic =
+	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
+/// Header type.
+pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
+/// Block type.
+pub type Block = generic::Block<Header, UncheckedExtrinsic>;
 /// BlockId type as expected by this runtime.
 pub type BlockId = generic::BlockId<Block>;
 
@@ -102,14 +105,6 @@
 	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
 	pallet_ethereum::FakeTransactionFinalizer<Runtime>,
 );
-
-/// Unchecked extrinsic type as expected by this runtime.
-pub type UncheckedExtrinsic =
-	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
-
-/// Extrinsic type that has already been checked.
-pub type CheckedExtrinsic =
-	fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
 
 /// Executive: handles dispatch to the various modules.
 pub type Executive = frame_executive::Executive<
modifiedruntime/common/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -79,7 +79,7 @@
 		return None;
 	}
 
-	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 	let limit = collection.limits.sponsored_data_rate_limit()?;
 
 	if let Some(last_tx_block) = TokenPropertyBasket::<T>::get(collection.id, item_id) {
@@ -123,7 +123,7 @@
 	}
 
 	// sponsor timeout
-	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 	let limit = collection
 		.limits
 		.sponsor_transfer_timeout(match collection.mode {
@@ -169,7 +169,7 @@
 	properties: &CreateItemData,
 ) -> Option<()> {
 	// sponsor timeout
-	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 	let limit = collection
 		.limits
 		.sponsor_transfer_timeout(match properties {
@@ -195,7 +195,7 @@
 	item_id: &TokenId,
 ) -> Option<()> {
 	// sponsor timeout
-	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 	let limit = collection.limits.sponsor_approve_timeout();
 
 	let last_tx_block = match collection.mode {
@@ -307,7 +307,7 @@
 pub trait SponsorshipPredict<T: Config> {
 	fn predict(collection: CollectionId, account: T::CrossAccountId, token: TokenId) -> Option<u64>
 	where
-		u64: From<<T as frame_system::Config>::BlockNumber>;
+		u64: From<BlockNumberFor<T>>;
 }
 
 pub struct UniqueSponsorshipPredict<T>(PhantomData<T>);
@@ -315,13 +315,13 @@
 impl<T: Config> SponsorshipPredict<T> for UniqueSponsorshipPredict<T> {
 	fn predict(collection_id: CollectionId, who: T::CrossAccountId, token: TokenId) -> Option<u64>
 	where
-		u64: From<<T as frame_system::Config>::BlockNumber>,
+		u64: From<BlockNumberFor<T>>,
 	{
 		let collection = <CollectionHandle<T>>::try_get(collection_id).ok()?;
 		let _ = collection.sponsorship.sponsor()?;
 
 		// sponsor timeout
-		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+		let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
 		let limit = collection
 			.limits
 			.sponsor_transfer_timeout(match collection.mode {
modifiedruntime/common/tests/mod.rsdiffbeforeafterboth
--- a/runtime/common/tests/mod.rs
+++ b/runtime/common/tests/mod.rs
@@ -51,8 +51,8 @@
 fn new_test_ext(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities {
 	let mut storage = make_basic_storage();
 
-	pallet_balances::GenesisConfig::<Runtime> { balances }
-		.assimilate_storage(&mut storage)
+	pallet_balances::BuildGenesisConfig::<Runtime> { balances }
+		.build_storage(&mut storage)
 		.unwrap();
 
 	let mut ext = sp_io::TestExternalities::new(storage);
@@ -94,13 +94,14 @@
 		.map(|acc| get_account_id_from_seed::<sr25519::Public>(acc))
 		.collect::<Vec<_>>();
 
-	let cfg = GenesisConfig {
+	let cfg = BuildGenesisConfig {
 		collator_selection: CollatorSelectionConfig { invulnerables },
 		session: SessionConfig { keys },
 		parachain_info: ParachainInfoConfig {
 			parachain_id: PARA_ID.into(),
+			..Default::default()
 		},
-		..GenesisConfig::default()
+		..Default::default()
 	};
 
 	cfg.build_storage().unwrap()
@@ -110,7 +111,7 @@
 fn make_basic_storage() -> Storage {
 	use crate::AuraConfig;
 
-	let cfg = GenesisConfig {
+	let cfg = BuildGenesisConfig {
 		aura: AuraConfig {
 			authorities: vec![
 				get_from_seed::<AuraId>("Alice"),
@@ -119,8 +120,9 @@
 		},
 		parachain_info: ParachainInfoConfig {
 			parachain_id: PARA_ID.into(),
+			..Default::default()
 		},
-		..GenesisConfig::default()
+		..Default::default()
 	};
 
 	cfg.build_storage().unwrap().into()
modifiedruntime/tests/src/lib.rsdiffbeforeafterboth
--- a/runtime/tests/src/lib.rs
+++ b/runtime/tests/src/lib.rs
@@ -57,23 +57,19 @@
 
 // Configure a mock runtime to test the pallet.
 frame_support::construct_runtime!(
-	pub enum Test where
-		Block = Block,
-		NodeBlock = Block,
-		UncheckedExtrinsic = UncheckedExtrinsic,
-	{
+	pub enum Test {
 		System: frame_system,
 		Timestamp: pallet_timestamp,
-		Unique: pallet_unique::{Pallet, Call, Storage},
-		Balances: pallet_balances::{Pallet, Call, Storage, Event<T>},
-		Common: pallet_common::{Pallet, Storage, Event<T>},
-		Fungible: pallet_fungible::{Pallet, Storage},
-		Refungible: pallet_refungible::{Pallet, Storage},
-		Nonfungible: pallet_nonfungible::{Pallet, Storage},
-		Structure: pallet_structure::{Pallet, Storage, Event<T>},
-		TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event<T>},
-		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin},
-		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>},
+		Unique: pallet_unique,
+		Balances: pallet_balances,
+		Common: pallet_common,
+		Fungible: pallet_fungible,
+		Refungible: pallet_refungible,
+		Nonfungible: pallet_nonfungible,
+		Structure: pallet_structure,
+		TransactionPayment: pallet_transaction_payment,
+		Ethereum: pallet_ethereum,
+		EVM: pallet_evm,
 	}
 );
 
@@ -90,13 +86,11 @@
 	type DbWeight = ();
 	type RuntimeOrigin = RuntimeOrigin;
 	type RuntimeCall = RuntimeCall;
-	type Index = u64;
-	type BlockNumber = u64;
+	type Nonce = u64;
 	type Hash = H256;
 	type Hashing = BlakeTwo256;
 	type AccountId = u64;
 	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
 	type BlockHashCount = BlockHashCount;
 	type Version = ();
 	type PalletInfo = PalletInfo;
@@ -127,7 +121,6 @@
 	type MaxFreezes = MaxLocks;
 	type FreezeIdentifier = [u8; 8];
 	type MaxHolds = MaxLocks;
-	type HoldIdentifier = [u8; 8];
 }
 
 parameter_types! {
@@ -242,7 +235,6 @@
 	type OnChargeTransaction = ();
 	type FindAuthor = ();
 	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
-	type TransactionValidityHack = ();
 	type Timestamp = Timestamp;
 	type GasLimitPovSizeRatio = ConstU64<0>;
 }