git.delta.rocks / unique-network / refs/commits / 081dbb6ae4fb

difftreelog

feat Separate rpc calls to own group

Trubnikov Sergey2022-09-01parent: #33ed679.patch.diff
in: master

31 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -113,6 +113,20 @@
 checksum = "508b352bb5c066aac251f6daf6b36eccd03e8a88e8081cd44959ea277a3af9a8"
 
 [[package]]
+name = "app-promotion-rpc"
+version = "0.1.0"
+dependencies = [
+ "pallet-common",
+ "pallet-evm",
+ "parity-scale-codec 3.1.5",
+ "sp-api",
+ "sp-core",
+ "sp-runtime",
+ "sp-std",
+ "up-data-structs",
+]
+
+[[package]]
 name = "approx"
 version = "0.5.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5127,6 +5141,7 @@
 name = "opal-runtime"
 version = "0.9.27"
 dependencies = [
+ "app-promotion-rpc",
  "cumulus-pallet-aura-ext",
  "cumulus-pallet-dmp-queue",
  "cumulus-pallet-parachain-system",
@@ -8358,6 +8373,7 @@
 name = "quartz-runtime"
 version = "0.9.27"
 dependencies = [
+ "app-promotion-rpc",
  "cumulus-pallet-aura-ext",
  "cumulus-pallet-dmp-queue",
  "cumulus-pallet-parachain-system",
@@ -8381,6 +8397,7 @@
  "hex-literal",
  "log",
  "orml-vesting",
+ "pallet-app-promotion",
  "pallet-aura",
  "pallet-balances",
  "pallet-base-fee",
@@ -12132,6 +12149,7 @@
 version = "0.1.3"
 dependencies = [
  "anyhow",
+ "app-promotion-rpc",
  "jsonrpsee",
  "pallet-common",
  "pallet-evm",
@@ -12210,6 +12228,7 @@
 name = "unique-node"
 version = "0.9.27"
 dependencies = [
+ "app-promotion-rpc",
  "clap",
  "cumulus-client-cli",
  "cumulus-client-collator",
@@ -12298,6 +12317,7 @@
 name = "unique-rpc"
 version = "0.1.1"
 dependencies = [
+ "app-promotion-rpc",
  "fc-db",
  "fc-mapping-sync",
  "fc-rpc",
@@ -12347,6 +12367,7 @@
 name = "unique-runtime"
 version = "0.9.27"
 dependencies = [
+ "app-promotion-rpc",
  "cumulus-pallet-aura-ext",
  "cumulus-pallet-dmp-queue",
  "cumulus-pallet-parachain-system",
@@ -12370,6 +12391,7 @@
  "hex-literal",
  "log",
  "orml-vesting",
+ "pallet-app-promotion",
  "pallet-aura",
  "pallet-balances",
  "pallet-base-fee",
modifiedclient/rpc/Cargo.tomldiffbeforeafterboth
--- a/client/rpc/Cargo.toml
+++ b/client/rpc/Cargo.toml
@@ -8,6 +8,7 @@
 pallet-common = { default-features = false, path = '../../pallets/common' }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
 up-rpc = { path = "../../primitives/rpc" }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc"}
 rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
 codec = { package = "parity-scale-codec", version = "3.1.2" }
 jsonrpsee = { version = "0.14.0", features = ["server", "macros"] }
modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -31,6 +31,7 @@
 use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};
 use sp_blockchain::HeaderBackend;
 use up_rpc::UniqueApi as UniqueRuntimeApi;
+use app_promotion_rpc::AppPromotionApi as AppPromotionRuntimeApi;
 
 // RMRK
 use rmrk_rpc::RmrkApi as RmrkRuntimeApi;
@@ -38,6 +39,7 @@
 	RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName, RmrkResourceId,
 };
 
+pub use app_promotion_unique_rpc::AppPromotionApiServer;
 pub use rmrk_unique_rpc::RmrkApiServer;
 
 #[rpc(server)]
@@ -244,39 +246,48 @@
 		token_id: TokenId,
 		at: Option<BlockHash>,
 	) -> Result<Option<String>>;
+}
+
+mod app_promotion_unique_rpc {
+	use super::*;
+	
+	#[rpc(server)]
+	#[async_trait]
+	pub trait AppPromotionApi<BlockHash, BlockNumber, CrossAccountId, AccountId> {
+		/// Returns the total amount of staked tokens.
+		#[method(name = "appPromotion_totalStaked")]
+		fn total_staked(&self, staker: Option<CrossAccountId>, at: Option<BlockHash>)
+			-> Result<String>;
 
-	/// Returns the total amount of staked tokens.
-	#[method(name = "unique_totalStaked")]
-	fn total_staked(&self, staker: Option<CrossAccountId>, at: Option<BlockHash>)
-		-> Result<String>;
+		///Returns the total amount of staked tokens per block when staked.
+		#[method(name = "appPromotion_totalStakedPerBlock")]
+		fn total_staked_per_block(
+			&self,
+			staker: CrossAccountId,
+			at: Option<BlockHash>,
+		) -> Result<Vec<(BlockNumber, String)>>;
 
-	///Returns the total amount of staked tokens per block when staked.
-	#[method(name = "unique_totalStakedPerBlock")]
-	fn total_staked_per_block(
-		&self,
-		staker: CrossAccountId,
-		at: Option<BlockHash>,
-	) -> Result<Vec<(BlockNumber, String)>>;
+		/// Returns the total amount locked by staking tokens.
+		#[method(name = "appPromotion_totalStakingLocked")]
+		fn total_staking_locked(&self, staker: CrossAccountId, at: Option<BlockHash>)
+			-> Result<String>;
 
-	/// Returns the total amount locked by staking tokens.
-	#[method(name = "unique_totalStakingLocked")]
-	fn total_staking_locked(&self, staker: CrossAccountId, at: Option<BlockHash>)
-		-> Result<String>;
+		/// Returns the total amount of tokens pending withdrawal from staking.
+		#[method(name = "appPromotion_pendingUnstake")]
+		fn pending_unstake(
+			&self,
+			staker: Option<CrossAccountId>,
+			at: Option<BlockHash>,
+		) -> Result<String>;
 
-	/// Returns the total amount of tokens pending withdrawal from staking.
-	#[method(name = "unique_pendingUnstake")]
-	fn pending_unstake(
-		&self,
-		staker: Option<CrossAccountId>,
-		at: Option<BlockHash>,
-	) -> Result<String>;
-	/// Returns the total amount of tokens pending withdrawal from staking per block.
-	#[method(name = "unique_pendingUnstakePerBlock")]
-	fn pending_unstake_per_block(
-		&self,
-		staker: CrossAccountId,
-		at: Option<BlockHash>,
-	) -> Result<Vec<(BlockNumber, String)>>;
+		/// Returns the total amount of tokens pending withdrawal from staking per block.
+		#[method(name = "appPromotion_pendingUnstakePerBlock")]
+		fn pending_unstake_per_block(
+			&self,
+			staker: CrossAccountId,
+			at: Option<BlockHash>,
+		) -> Result<Vec<(BlockNumber, String)>>;
+	}
 }
 
 mod rmrk_unique_rpc {
@@ -415,6 +426,20 @@
 	}
 }
 
+pub struct AppPromotion<C, P> {
+	client: Arc<C>,
+	_marker: std::marker::PhantomData<P>,
+}
+
+impl<C, P> AppPromotion<C, P> {
+	pub fn new(client: Arc<C>) -> Self {
+		Self {
+			client,
+			_marker: Default::default(),
+		}
+	}
+}
+
 pub struct Rmrk<C, P> {
 	client: Arc<C>,
 	_marker: std::marker::PhantomData<P>,
@@ -474,6 +499,12 @@
 	};
 }
 
+macro_rules! app_promotion_api {
+	() => {
+		dyn AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>
+	};
+}
+
 macro_rules! rmrk_api {
 	() => {
 		dyn RmrkRuntimeApi<Block, AccountId, CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme>
@@ -556,7 +587,20 @@
 	pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);
 	pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<String> => |o| o.map(|number| number.to_string()) , unique_api);
 	pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);
-	pass_method!(total_staked(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), unique_api);
+}
+
+impl<C, Block, BlockNumber, CrossAccountId, AccountId>
+ 	app_promotion_unique_rpc::AppPromotionApiServer<<Block as BlockT>::Hash, BlockNumber, CrossAccountId, AccountId>
+	for AppPromotion<C, Block>
+where
+	Block: BlockT,
+	BlockNumber: Decode + Member + AtLeast32BitUnsigned,
+	AccountId: Decode,
+	C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
+	C::Api: AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,
+	CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,
+{
+	pass_method!(total_staked(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);
 	pass_method!(total_staked_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>
 		|v| v
 		.into_iter()
modifiednode/cli/Cargo.tomldiffbeforeafterboth
--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -318,6 +318,7 @@
 pallet-ethereum = { git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
 
 unique-rpc = { default-features = false, path = "../rpc" }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false}
 rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
 
 [features]
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_rpc_core::types::FeeHistoryCache;24use futures::{25	Stream, StreamExt,26	stream::select,27	task::{Context, Poll},28};29use tokio::time::Interval;3031use unique_rpc::overrides_handle;3233use serde::{Serialize, Deserialize};3435// Cumulus Imports36use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};37use cumulus_client_consensus_common::ParachainConsensus;38use cumulus_client_service::{39	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,40};41use cumulus_client_cli::CollatorOptions;42use cumulus_client_network::BlockAnnounceValidator;43use cumulus_primitives_core::ParaId;44use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;45use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};46use cumulus_relay_chain_rpc_interface::RelayChainRPCInterface;4748// Substrate Imports49use sc_client_api::ExecutorProvider;50use sc_executor::NativeElseWasmExecutor;51use sc_executor::NativeExecutionDispatch;52use sc_network::NetworkService;53use sc_service::{BasePath, Configuration, PartialComponents, TaskManager};54use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};55use sp_keystore::SyncCryptoStorePtr;56use sp_runtime::traits::BlakeTwo256;57use substrate_prometheus_endpoint::Registry;58use sc_client_api::BlockchainEvents;5960use polkadot_service::CollatorPair;6162// Frontier Imports63use fc_rpc_core::types::FilterPool;64use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6566use up_common::types::opaque::{67	AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,68};6970// RMRK71use up_data_structs::{72	RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,73	RmrkPartType, RmrkTheme,74};7576/// Unique native executor instance.77#[cfg(feature = "unique-runtime")]78pub struct UniqueRuntimeExecutor;7980#[cfg(feature = "quartz-runtime")]81/// Quartz native executor instance.82pub struct QuartzRuntimeExecutor;8384/// Opal native executor instance.85pub struct OpalRuntimeExecutor;8687#[cfg(feature = "unique-runtime")]88pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;8990#[cfg(all(not(feature = "unique-runtime"), feature = "quartz-runtime"))]91pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9293#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]94pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;9596#[cfg(feature = "unique-runtime")]97impl NativeExecutionDispatch for UniqueRuntimeExecutor {98	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;99100	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {101		unique_runtime::api::dispatch(method, data)102	}103104	fn native_version() -> sc_executor::NativeVersion {105		unique_runtime::native_version()106	}107}108109#[cfg(feature = "quartz-runtime")]110impl NativeExecutionDispatch for QuartzRuntimeExecutor {111	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;112113	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {114		quartz_runtime::api::dispatch(method, data)115	}116117	fn native_version() -> sc_executor::NativeVersion {118		quartz_runtime::native_version()119	}120}121122impl NativeExecutionDispatch for OpalRuntimeExecutor {123	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;124125	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {126		opal_runtime::api::dispatch(method, data)127	}128129	fn native_version() -> sc_executor::NativeVersion {130		opal_runtime::native_version()131	}132}133134pub struct AutosealInterval {135	interval: Interval,136}137138impl AutosealInterval {139	pub fn new(config: &Configuration, interval: Duration) -> Self {140		let _tokio_runtime = config.tokio_handle.enter();141		let interval = tokio::time::interval(interval);142143		Self { interval }144	}145}146147impl Stream for AutosealInterval {148	type Item = tokio::time::Instant;149150	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {151		self.interval.poll_tick(cx).map(Some)152	}153}154155pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {156	let config_dir = config157		.base_path158		.as_ref()159		.map(|base_path| base_path.config_dir(config.chain_spec.id()))160		.unwrap_or_else(|| {161			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())162		});163	let database_dir = config_dir.join("frontier").join("db");164165	Ok(Arc::new(fc_db::Backend::<Block>::new(166		&fc_db::DatabaseSettings {167			source: fc_db::DatabaseSource::RocksDb {168				path: database_dir,169				cache_size: 0,170			},171		},172	)?))173}174175type FullClient<RuntimeApi, ExecutorDispatch> =176	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;177type FullBackend = sc_service::TFullBackend<Block>;178type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;179180/// Starts a `ServiceBuilder` for a full service.181///182/// Use this macro if you don't actually need the full service, but just the builder in order to183/// be able to perform chain operations.184#[allow(clippy::type_complexity)]185pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(186	config: &Configuration,187	build_import_queue: BIQ,188) -> Result<189	PartialComponents<190		FullClient<RuntimeApi, ExecutorDispatch>,191		FullBackend,192		FullSelectChain,193		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,194		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,195		(196			Option<Telemetry>,197			Option<FilterPool>,198			Arc<fc_db::Backend<Block>>,199			Option<TelemetryWorkerHandle>,200			FeeHistoryCache,201		),202	>,203	sc_service::Error,204>205where206	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,207	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>208		+ Send209		+ Sync210		+ 'static,211	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,212	ExecutorDispatch: NativeExecutionDispatch + 'static,213	BIQ: FnOnce(214		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,215		&Configuration,216		Option<TelemetryHandle>,217		&TaskManager,218	) -> Result<219		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,220		sc_service::Error,221	>,222{223	let _telemetry = config224		.telemetry_endpoints225		.clone()226		.filter(|x| !x.is_empty())227		.map(|endpoints| -> Result<_, sc_telemetry::Error> {228			let worker = TelemetryWorker::new(16)?;229			let telemetry = worker.handle().new_telemetry(endpoints);230			Ok((worker, telemetry))231		})232		.transpose()?;233234	let telemetry = config235		.telemetry_endpoints236		.clone()237		.filter(|x| !x.is_empty())238		.map(|endpoints| -> Result<_, sc_telemetry::Error> {239			let worker = TelemetryWorker::new(16)?;240			let telemetry = worker.handle().new_telemetry(endpoints);241			Ok((worker, telemetry))242		})243		.transpose()?;244245	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(246		config.wasm_method,247		config.default_heap_pages,248		config.max_runtime_instances,249		config.runtime_cache_size,250	);251252	let (client, backend, keystore_container, task_manager) =253		sc_service::new_full_parts::<Block, RuntimeApi, _>(254			config,255			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),256			executor,257		)?;258	let client = Arc::new(client);259260	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());261262	let telemetry = telemetry.map(|(worker, telemetry)| {263		task_manager264			.spawn_handle()265			.spawn("telemetry", None, worker.run());266		telemetry267	});268269	let select_chain = sc_consensus::LongestChain::new(backend.clone());270271	let transaction_pool = sc_transaction_pool::BasicPool::new_full(272		config.transaction_pool.clone(),273		config.role.is_authority().into(),274		config.prometheus_registry(),275		task_manager.spawn_essential_handle(),276		client.clone(),277	);278279	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));280281	let frontier_backend = open_frontier_backend(config)?;282283	let import_queue = build_import_queue(284		client.clone(),285		config,286		telemetry.as_ref().map(|telemetry| telemetry.handle()),287		&task_manager,288	)?;289	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));290291	let params = PartialComponents {292		backend,293		client,294		import_queue,295		keystore_container,296		task_manager,297		transaction_pool,298		select_chain,299		other: (300			telemetry,301			filter_pool,302			frontier_backend,303			telemetry_worker_handle,304			fee_history_cache,305		),306	};307308	Ok(params)309}310311async fn build_relay_chain_interface(312	polkadot_config: Configuration,313	parachain_config: &Configuration,314	telemetry_worker_handle: Option<TelemetryWorkerHandle>,315	task_manager: &mut TaskManager,316	collator_options: CollatorOptions,317	hwbench: Option<sc_sysinfo::HwBench>,318) -> RelayChainResult<(319	Arc<(dyn RelayChainInterface + 'static)>,320	Option<CollatorPair>,321)> {322	match collator_options.relay_chain_rpc_url {323		Some(relay_chain_url) => Ok((324			Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,325			None,326		)),327		None => build_inprocess_relay_chain(328			polkadot_config,329			parachain_config,330			telemetry_worker_handle,331			task_manager,332			hwbench,333		),334	}335}336337/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.338///339/// This is the actual implementation that is abstract over the executor and the runtime api.340#[sc_tracing::logging::prefix_logs_with("Parachain")]341async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(342	parachain_config: Configuration,343	polkadot_config: Configuration,344	collator_options: CollatorOptions,345	id: ParaId,346	build_import_queue: BIQ,347	build_consensus: BIC,348	hwbench: Option<sc_sysinfo::HwBench>,349) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>350where351	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,352	Runtime: RuntimeInstance + Send + Sync + 'static,353	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,354	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,355	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>356		+ Send357		+ Sync358		+ 'static,359	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>360		+ fp_rpc::EthereumRuntimeRPCApi<Block>361		+ fp_rpc::ConvertTransactionRuntimeApi<Block>362		+ sp_session::SessionKeys<Block>363		+ sp_block_builder::BlockBuilder<Block>364		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>365		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>366		+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>367		+ rmrk_rpc::RmrkApi<368			Block,369			AccountId,370			RmrkCollectionInfo<AccountId>,371			RmrkInstanceInfo<AccountId>,372			RmrkResourceInfo,373			RmrkPropertyInfo,374			RmrkBaseInfo<AccountId>,375			RmrkPartType,376			RmrkTheme,377		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>378		+ sp_api::Metadata<Block>379		+ sp_offchain::OffchainWorkerApi<Block>380		+ cumulus_primitives_core::CollectCollationInfo<Block>,381	ExecutorDispatch: NativeExecutionDispatch + 'static,382	BIQ: FnOnce(383		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,384		&Configuration,385		Option<TelemetryHandle>,386		&TaskManager,387	) -> Result<388		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,389		sc_service::Error,390	>,391	BIC: FnOnce(392		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,393		Option<&Registry>,394		Option<TelemetryHandle>,395		&TaskManager,396		Arc<dyn RelayChainInterface>,397		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,398		Arc<NetworkService<Block, Hash>>,399		SyncCryptoStorePtr,400		bool,401	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,402{403	let parachain_config = prepare_node_config(parachain_config);404405	let params =406		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;407	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =408		params.other;409410	let client = params.client.clone();411	let backend = params.backend.clone();412	let mut task_manager = params.task_manager;413414	let (relay_chain_interface, collator_key) = build_relay_chain_interface(415		polkadot_config,416		&parachain_config,417		telemetry_worker_handle,418		&mut task_manager,419		collator_options.clone(),420		hwbench.clone(),421	)422	.await423	.map_err(|e| match e {424		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,425		s => s.to_string().into(),426	})?;427428	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);429430	let force_authoring = parachain_config.force_authoring;431	let validator = parachain_config.role.is_authority();432	let prometheus_registry = parachain_config.prometheus_registry().cloned();433	let transaction_pool = params.transaction_pool.clone();434	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);435436	let (network, system_rpc_tx, start_network) =437		sc_service::build_network(sc_service::BuildNetworkParams {438			config: &parachain_config,439			client: client.clone(),440			transaction_pool: transaction_pool.clone(),441			spawn_handle: task_manager.spawn_handle(),442			import_queue: import_queue.clone(),443			block_announce_validator_builder: Some(Box::new(|_| {444				Box::new(block_announce_validator)445			})),446			warp_sync: None,447		})?;448449	let rpc_client = client.clone();450	let rpc_pool = transaction_pool.clone();451	let select_chain = params.select_chain.clone();452	let rpc_network = network.clone();453454	let rpc_frontier_backend = frontier_backend.clone();455456	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(457		task_manager.spawn_handle(),458		overrides_handle::<_, _, Runtime>(client.clone()),459		50,460		50,461		prometheus_registry.clone(),462	));463464	task_manager.spawn_essential_handle().spawn(465		"frontier-mapping-sync-worker",466		None,467		MappingSyncWorker::new(468			client.import_notification_stream(),469			Duration::new(6, 0),470			client.clone(),471			backend.clone(),472			frontier_backend.clone(),473			3,474			0,475			SyncStrategy::Normal,476		)477		.for_each(|()| futures::future::ready(())),478	);479480	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {481		let full_deps = unique_rpc::FullDeps {482			backend: rpc_frontier_backend.clone(),483			deny_unsafe,484			client: rpc_client.clone(),485			pool: rpc_pool.clone(),486			graph: rpc_pool.pool().clone(),487			// TODO: Unhardcode488			enable_dev_signer: false,489			filter_pool: filter_pool.clone(),490			network: rpc_network.clone(),491			select_chain: select_chain.clone(),492			is_authority: validator,493			// TODO: Unhardcode494			max_past_logs: 10000,495			block_data_cache: block_data_cache.clone(),496			fee_history_cache: fee_history_cache.clone(),497			// TODO: Unhardcode498			fee_history_limit: 2048,499		};500501		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(502			full_deps,503			subscription_task_executor,504		)505		.map_err(Into::into)506	});507508	sc_service::spawn_tasks(sc_service::SpawnTasksParams {509		rpc_builder,510		client: client.clone(),511		transaction_pool: transaction_pool.clone(),512		task_manager: &mut task_manager,513		config: parachain_config,514		keystore: params.keystore_container.sync_keystore(),515		backend: backend.clone(),516		network: network.clone(),517		system_rpc_tx,518		telemetry: telemetry.as_mut(),519	})?;520521	if let Some(hwbench) = hwbench {522		sc_sysinfo::print_hwbench(&hwbench);523524		if let Some(ref mut telemetry) = telemetry {525			let telemetry_handle = telemetry.handle();526			task_manager.spawn_handle().spawn(527				"telemetry_hwbench",528				None,529				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),530			);531		}532	}533534	let announce_block = {535		let network = network.clone();536		Arc::new(move |hash, data| network.announce_block(hash, data))537	};538539	let relay_chain_slot_duration = Duration::from_secs(6);540541	if validator {542		let parachain_consensus = build_consensus(543			client.clone(),544			prometheus_registry.as_ref(),545			telemetry.as_ref().map(|t| t.handle()),546			&task_manager,547			relay_chain_interface.clone(),548			transaction_pool,549			network,550			params.keystore_container.sync_keystore(),551			force_authoring,552		)?;553554		let spawner = task_manager.spawn_handle();555556		let params = StartCollatorParams {557			para_id: id,558			block_status: client.clone(),559			announce_block,560			client: client.clone(),561			task_manager: &mut task_manager,562			spawner,563			parachain_consensus,564			import_queue,565			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),566			relay_chain_interface,567			relay_chain_slot_duration,568		};569570		start_collator(params).await?;571	} else {572		let params = StartFullNodeParams {573			client: client.clone(),574			announce_block,575			task_manager: &mut task_manager,576			para_id: id,577			import_queue,578			relay_chain_interface,579			relay_chain_slot_duration,580			collator_options,581		};582583		start_full_node(params)?;584	}585586	start_network.start_network();587588	Ok((task_manager, client))589}590591/// Build the import queue for the the parachain runtime.592pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(593	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,594	config: &Configuration,595	telemetry: Option<TelemetryHandle>,596	task_manager: &TaskManager,597) -> Result<598	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,599	sc_service::Error,600>601where602	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>603		+ Send604		+ Sync605		+ 'static,606	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>607		+ sp_block_builder::BlockBuilder<Block>608		+ sp_consensus_aura::AuraApi<Block, AuraId>609		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,610	ExecutorDispatch: NativeExecutionDispatch + 'static,611{612	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;613614	cumulus_client_consensus_aura::import_queue::<615		sp_consensus_aura::sr25519::AuthorityPair,616		_,617		_,618		_,619		_,620		_,621		_,622	>(cumulus_client_consensus_aura::ImportQueueParams {623		block_import: client.clone(),624		client: client.clone(),625		create_inherent_data_providers: move |_, _| async move {626			let time = sp_timestamp::InherentDataProvider::from_system_time();627628			let slot =629				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(630					*time,631					slot_duration,632				);633634			Ok((time, slot))635		},636		registry: config.prometheus_registry(),637		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),638		spawner: &task_manager.spawn_essential_handle(),639		telemetry,640	})641	.map_err(Into::into)642}643644/// Start a normal parachain node.645pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(646	parachain_config: Configuration,647	polkadot_config: Configuration,648	collator_options: CollatorOptions,649	id: ParaId,650	hwbench: Option<sc_sysinfo::HwBench>,651) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>652where653	Runtime: RuntimeInstance + Send + Sync + 'static,654	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,655	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,656	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>657		+ Send658		+ Sync659		+ 'static,660	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>661		+ fp_rpc::EthereumRuntimeRPCApi<Block>662		+ fp_rpc::ConvertTransactionRuntimeApi<Block>663		+ sp_session::SessionKeys<Block>664		+ sp_block_builder::BlockBuilder<Block>665		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>666		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>667		+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>668		+ rmrk_rpc::RmrkApi<669			Block,670			AccountId,671			RmrkCollectionInfo<AccountId>,672			RmrkInstanceInfo<AccountId>,673			RmrkResourceInfo,674			RmrkPropertyInfo,675			RmrkBaseInfo<AccountId>,676			RmrkPartType,677			RmrkTheme,678		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>679		+ sp_api::Metadata<Block>680		+ sp_offchain::OffchainWorkerApi<Block>681		+ cumulus_primitives_core::CollectCollationInfo<Block>682		+ sp_consensus_aura::AuraApi<Block, AuraId>,683	ExecutorDispatch: NativeExecutionDispatch + 'static,684{685	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(686		parachain_config,687		polkadot_config,688		collator_options,689		id,690		parachain_build_import_queue,691		|client,692		 prometheus_registry,693		 telemetry,694		 task_manager,695		 relay_chain_interface,696		 transaction_pool,697		 sync_oracle,698		 keystore,699		 force_authoring| {700			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;701702			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(703				task_manager.spawn_handle(),704				client.clone(),705				transaction_pool,706				prometheus_registry,707				telemetry.clone(),708			);709710			Ok(AuraConsensus::build::<711				sp_consensus_aura::sr25519::AuthorityPair,712				_,713				_,714				_,715				_,716				_,717				_,718			>(BuildAuraConsensusParams {719				proposer_factory,720				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {721					let relay_chain_interface = relay_chain_interface.clone();722					async move {723						let parachain_inherent =724						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(725							relay_parent,726							&relay_chain_interface,727							&validation_data,728							id,729						).await;730731						let time = sp_timestamp::InherentDataProvider::from_system_time();732733						let slot =734						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(735							*time,736							slot_duration,737						);738739						let parachain_inherent = parachain_inherent.ok_or_else(|| {740							Box::<dyn std::error::Error + Send + Sync>::from(741								"Failed to create parachain inherent",742							)743						})?;744						Ok((time, slot, parachain_inherent))745					}746				},747				block_import: client.clone(),748				para_client: client,749				backoff_authoring_blocks: Option::<()>::None,750				sync_oracle,751				keystore,752				force_authoring,753				slot_duration,754				// We got around 500ms for proposing755				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),756				telemetry,757				max_block_proposal_slot_portion: None,758			}))759		},760		hwbench,761	)762	.await763}764765fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(766	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,767	config: &Configuration,768	_: Option<TelemetryHandle>,769	task_manager: &TaskManager,770) -> Result<771	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,772	sc_service::Error,773>774where775	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>776		+ Send777		+ Sync778		+ 'static,779	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>780		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,781	ExecutorDispatch: NativeExecutionDispatch + 'static,782{783	Ok(sc_consensus_manual_seal::import_queue(784		Box::new(client.clone()),785		&task_manager.spawn_essential_handle(),786		config.prometheus_registry(),787	))788}789790/// Builds a new development service. This service uses instant seal, and mocks791/// the parachain inherent792pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(793	config: Configuration,794	autoseal_interval: Duration,795) -> sc_service::error::Result<TaskManager>796where797	Runtime: RuntimeInstance + Send + Sync + 'static,798	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,799	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,800	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>801		+ Send802		+ Sync803		+ 'static,804	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>805		+ fp_rpc::EthereumRuntimeRPCApi<Block>806		+ fp_rpc::ConvertTransactionRuntimeApi<Block>807		+ sp_session::SessionKeys<Block>808		+ sp_block_builder::BlockBuilder<Block>809		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>810		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>811		+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>812		+ rmrk_rpc::RmrkApi<813			Block,814			AccountId,815			RmrkCollectionInfo<AccountId>,816			RmrkInstanceInfo<AccountId>,817			RmrkResourceInfo,818			RmrkPropertyInfo,819			RmrkBaseInfo<AccountId>,820			RmrkPartType,821			RmrkTheme,822		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>823		+ sp_api::Metadata<Block>824		+ sp_offchain::OffchainWorkerApi<Block>825		+ cumulus_primitives_core::CollectCollationInfo<Block>826		+ sp_consensus_aura::AuraApi<Block, AuraId>,827	ExecutorDispatch: NativeExecutionDispatch + 'static,828{829	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};830	use fc_consensus::FrontierBlockImport;831	use sc_client_api::HeaderBackend;832833	let sc_service::PartialComponents {834		client,835		backend,836		mut task_manager,837		import_queue,838		keystore_container,839		select_chain: maybe_select_chain,840		transaction_pool,841		other:842			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),843	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(844		&config,845		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,846	)?;847	let prometheus_registry = config.prometheus_registry().cloned();848849	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(850		task_manager.spawn_handle(),851		overrides_handle::<_, _, Runtime>(client.clone()),852		50,853		50,854		prometheus_registry.clone(),855	));856857	let (network, system_rpc_tx, network_starter) =858		sc_service::build_network(sc_service::BuildNetworkParams {859			config: &config,860			client: client.clone(),861			transaction_pool: transaction_pool.clone(),862			spawn_handle: task_manager.spawn_handle(),863			import_queue,864			block_announce_validator_builder: None,865			warp_sync: None,866		})?;867868	if config.offchain_worker.enabled {869		sc_service::build_offchain_workers(870			&config,871			task_manager.spawn_handle(),872			client.clone(),873			network.clone(),874		);875	}876877	let collator = config.role.is_authority();878879	let select_chain = maybe_select_chain.clone();880881	if collator {882		let block_import =883			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());884885		let env = sc_basic_authorship::ProposerFactory::new(886			task_manager.spawn_handle(),887			client.clone(),888			transaction_pool.clone(),889			prometheus_registry.as_ref(),890			telemetry.as_ref().map(|x| x.handle()),891		);892893		let transactions_commands_stream: Box<894			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,895		> = Box::new(896			transaction_pool897				.pool()898				.validated_pool()899				.import_notification_stream()900				.map(|_| EngineCommand::SealNewBlock {901					create_empty: true,902					finalize: false,903					parent_hash: None,904					sender: None,905				}),906		);907908		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));909		let idle_commands_stream: Box<910			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,911		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {912			create_empty: true,913			finalize: false,914			parent_hash: None,915			sender: None,916		}));917918		let commands_stream = select(transactions_commands_stream, idle_commands_stream);919920		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;921		let client_set_aside_for_cidp = client.clone();922923		task_manager.spawn_essential_handle().spawn_blocking(924			"authorship_task",925			Some("block-authoring"),926			run_manual_seal(ManualSealParams {927				block_import,928				env,929				client: client.clone(),930				pool: transaction_pool.clone(),931				commands_stream,932				select_chain: select_chain.clone(),933				consensus_data_provider: None,934				create_inherent_data_providers: move |block: Hash, ()| {935					let current_para_block = client_set_aside_for_cidp936						.number(block)937						.expect("Header lookup should succeed")938						.expect("Header passed in as parent should be present in backend.");939940					let client_for_xcm = client_set_aside_for_cidp.clone();941					async move {942						let time = sp_timestamp::InherentDataProvider::from_system_time();943944						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {945							current_para_block,946							relay_offset: 1000,947							relay_blocks_per_para_block: 2,948							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(949								&*client_for_xcm,950								block,951								Default::default(),952								Default::default(),953							),954							raw_downward_messages: vec![],955							raw_horizontal_messages: vec![],956						};957958						let slot =959						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(960							*time,961							slot_duration,962						);963964						Ok((time, slot, mocked_parachain))965					}966				},967			}),968		);969	}970971	task_manager.spawn_essential_handle().spawn(972		"frontier-mapping-sync-worker",973		Some("block-authoring"),974		MappingSyncWorker::new(975			client.import_notification_stream(),976			Duration::new(6, 0),977			client.clone(),978			backend.clone(),979			frontier_backend.clone(),980			3,981			0,982			SyncStrategy::Normal,983		)984		.for_each(|()| futures::future::ready(())),985	);986987	let rpc_client = client.clone();988	let rpc_pool = transaction_pool.clone();989	let rpc_network = network.clone();990	let rpc_frontier_backend = frontier_backend.clone();991	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {992		let full_deps = unique_rpc::FullDeps {993			backend: rpc_frontier_backend.clone(),994			deny_unsafe,995			client: rpc_client.clone(),996			pool: rpc_pool.clone(),997			graph: rpc_pool.pool().clone(),998			// TODO: Unhardcode999			enable_dev_signer: false,1000			filter_pool: filter_pool.clone(),1001			network: rpc_network.clone(),1002			select_chain: select_chain.clone(),1003			is_authority: collator,1004			// TODO: Unhardcode1005			max_past_logs: 10000,1006			block_data_cache: block_data_cache.clone(),1007			fee_history_cache: fee_history_cache.clone(),1008			// TODO: Unhardcode1009			fee_history_limit: 2048,1010		};10111012		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1013			full_deps,1014			subscription_executor,1015		)1016		.map_err(Into::into)1017	});10181019	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1020		network,1021		client,1022		keystore: keystore_container.sync_keystore(),1023		task_manager: &mut task_manager,1024		transaction_pool,1025		rpc_builder,1026		backend,1027		system_rpc_tx,1028		config,1029		telemetry: None,1030	})?;10311032	network_starter.start_network();1033	Ok(task_manager)1034}
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_rpc_core::types::FeeHistoryCache;24use futures::{25	Stream, StreamExt,26	stream::select,27	task::{Context, Poll},28};29use tokio::time::Interval;3031use unique_rpc::overrides_handle;3233use serde::{Serialize, Deserialize};3435// Cumulus Imports36use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};37use cumulus_client_consensus_common::ParachainConsensus;38use cumulus_client_service::{39	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,40};41use cumulus_client_cli::CollatorOptions;42use cumulus_client_network::BlockAnnounceValidator;43use cumulus_primitives_core::ParaId;44use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;45use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};46use cumulus_relay_chain_rpc_interface::RelayChainRPCInterface;4748// Substrate Imports49use sc_client_api::ExecutorProvider;50use sc_executor::NativeElseWasmExecutor;51use sc_executor::NativeExecutionDispatch;52use sc_network::NetworkService;53use sc_service::{BasePath, Configuration, PartialComponents, TaskManager};54use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};55use sp_keystore::SyncCryptoStorePtr;56use sp_runtime::traits::BlakeTwo256;57use substrate_prometheus_endpoint::Registry;58use sc_client_api::BlockchainEvents;5960use polkadot_service::CollatorPair;6162// Frontier Imports63use fc_rpc_core::types::FilterPool;64use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6566use up_common::types::opaque::{67	AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,68};6970// RMRK71use up_data_structs::{72	RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,73	RmrkPartType, RmrkTheme,74};7576/// Unique native executor instance.77#[cfg(feature = "unique-runtime")]78pub struct UniqueRuntimeExecutor;7980#[cfg(feature = "quartz-runtime")]81/// Quartz native executor instance.82pub struct QuartzRuntimeExecutor;8384/// Opal native executor instance.85pub struct OpalRuntimeExecutor;8687#[cfg(feature = "unique-runtime")]88pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;8990#[cfg(all(not(feature = "unique-runtime"), feature = "quartz-runtime"))]91pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9293#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]94pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;9596#[cfg(feature = "unique-runtime")]97impl NativeExecutionDispatch for UniqueRuntimeExecutor {98	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;99100	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {101		unique_runtime::api::dispatch(method, data)102	}103104	fn native_version() -> sc_executor::NativeVersion {105		unique_runtime::native_version()106	}107}108109#[cfg(feature = "quartz-runtime")]110impl NativeExecutionDispatch for QuartzRuntimeExecutor {111	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;112113	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {114		quartz_runtime::api::dispatch(method, data)115	}116117	fn native_version() -> sc_executor::NativeVersion {118		quartz_runtime::native_version()119	}120}121122impl NativeExecutionDispatch for OpalRuntimeExecutor {123	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;124125	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {126		opal_runtime::api::dispatch(method, data)127	}128129	fn native_version() -> sc_executor::NativeVersion {130		opal_runtime::native_version()131	}132}133134pub struct AutosealInterval {135	interval: Interval,136}137138impl AutosealInterval {139	pub fn new(config: &Configuration, interval: Duration) -> Self {140		let _tokio_runtime = config.tokio_handle.enter();141		let interval = tokio::time::interval(interval);142143		Self { interval }144	}145}146147impl Stream for AutosealInterval {148	type Item = tokio::time::Instant;149150	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {151		self.interval.poll_tick(cx).map(Some)152	}153}154155pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {156	let config_dir = config157		.base_path158		.as_ref()159		.map(|base_path| base_path.config_dir(config.chain_spec.id()))160		.unwrap_or_else(|| {161			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())162		});163	let database_dir = config_dir.join("frontier").join("db");164165	Ok(Arc::new(fc_db::Backend::<Block>::new(166		&fc_db::DatabaseSettings {167			source: fc_db::DatabaseSource::RocksDb {168				path: database_dir,169				cache_size: 0,170			},171		},172	)?))173}174175type FullClient<RuntimeApi, ExecutorDispatch> =176	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;177type FullBackend = sc_service::TFullBackend<Block>;178type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;179180/// Starts a `ServiceBuilder` for a full service.181///182/// Use this macro if you don't actually need the full service, but just the builder in order to183/// be able to perform chain operations.184#[allow(clippy::type_complexity)]185pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(186	config: &Configuration,187	build_import_queue: BIQ,188) -> Result<189	PartialComponents<190		FullClient<RuntimeApi, ExecutorDispatch>,191		FullBackend,192		FullSelectChain,193		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,194		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,195		(196			Option<Telemetry>,197			Option<FilterPool>,198			Arc<fc_db::Backend<Block>>,199			Option<TelemetryWorkerHandle>,200			FeeHistoryCache,201		),202	>,203	sc_service::Error,204>205where206	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,207	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>208		+ Send209		+ Sync210		+ 'static,211	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,212	ExecutorDispatch: NativeExecutionDispatch + 'static,213	BIQ: FnOnce(214		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,215		&Configuration,216		Option<TelemetryHandle>,217		&TaskManager,218	) -> Result<219		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,220		sc_service::Error,221	>,222{223	let _telemetry = config224		.telemetry_endpoints225		.clone()226		.filter(|x| !x.is_empty())227		.map(|endpoints| -> Result<_, sc_telemetry::Error> {228			let worker = TelemetryWorker::new(16)?;229			let telemetry = worker.handle().new_telemetry(endpoints);230			Ok((worker, telemetry))231		})232		.transpose()?;233234	let telemetry = config235		.telemetry_endpoints236		.clone()237		.filter(|x| !x.is_empty())238		.map(|endpoints| -> Result<_, sc_telemetry::Error> {239			let worker = TelemetryWorker::new(16)?;240			let telemetry = worker.handle().new_telemetry(endpoints);241			Ok((worker, telemetry))242		})243		.transpose()?;244245	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(246		config.wasm_method,247		config.default_heap_pages,248		config.max_runtime_instances,249		config.runtime_cache_size,250	);251252	let (client, backend, keystore_container, task_manager) =253		sc_service::new_full_parts::<Block, RuntimeApi, _>(254			config,255			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),256			executor,257		)?;258	let client = Arc::new(client);259260	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());261262	let telemetry = telemetry.map(|(worker, telemetry)| {263		task_manager264			.spawn_handle()265			.spawn("telemetry", None, worker.run());266		telemetry267	});268269	let select_chain = sc_consensus::LongestChain::new(backend.clone());270271	let transaction_pool = sc_transaction_pool::BasicPool::new_full(272		config.transaction_pool.clone(),273		config.role.is_authority().into(),274		config.prometheus_registry(),275		task_manager.spawn_essential_handle(),276		client.clone(),277	);278279	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));280281	let frontier_backend = open_frontier_backend(config)?;282283	let import_queue = build_import_queue(284		client.clone(),285		config,286		telemetry.as_ref().map(|telemetry| telemetry.handle()),287		&task_manager,288	)?;289	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));290291	let params = PartialComponents {292		backend,293		client,294		import_queue,295		keystore_container,296		task_manager,297		transaction_pool,298		select_chain,299		other: (300			telemetry,301			filter_pool,302			frontier_backend,303			telemetry_worker_handle,304			fee_history_cache,305		),306	};307308	Ok(params)309}310311async fn build_relay_chain_interface(312	polkadot_config: Configuration,313	parachain_config: &Configuration,314	telemetry_worker_handle: Option<TelemetryWorkerHandle>,315	task_manager: &mut TaskManager,316	collator_options: CollatorOptions,317	hwbench: Option<sc_sysinfo::HwBench>,318) -> RelayChainResult<(319	Arc<(dyn RelayChainInterface + 'static)>,320	Option<CollatorPair>,321)> {322	match collator_options.relay_chain_rpc_url {323		Some(relay_chain_url) => Ok((324			Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,325			None,326		)),327		None => build_inprocess_relay_chain(328			polkadot_config,329			parachain_config,330			telemetry_worker_handle,331			task_manager,332			hwbench,333		),334	}335}336337/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.338///339/// This is the actual implementation that is abstract over the executor and the runtime api.340#[sc_tracing::logging::prefix_logs_with("Parachain")]341async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(342	parachain_config: Configuration,343	polkadot_config: Configuration,344	collator_options: CollatorOptions,345	id: ParaId,346	build_import_queue: BIQ,347	build_consensus: BIC,348	hwbench: Option<sc_sysinfo::HwBench>,349) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>350where351	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,352	Runtime: RuntimeInstance + Send + Sync + 'static,353	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,354	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,355	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>356		+ Send357		+ Sync358		+ 'static,359	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>360		+ fp_rpc::EthereumRuntimeRPCApi<Block>361		+ fp_rpc::ConvertTransactionRuntimeApi<Block>362		+ sp_session::SessionKeys<Block>363		+ sp_block_builder::BlockBuilder<Block>364		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>365		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>366		+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>367		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>368		+ rmrk_rpc::RmrkApi<369			Block,370			AccountId,371			RmrkCollectionInfo<AccountId>,372			RmrkInstanceInfo<AccountId>,373			RmrkResourceInfo,374			RmrkPropertyInfo,375			RmrkBaseInfo<AccountId>,376			RmrkPartType,377			RmrkTheme,378		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>379		+ sp_api::Metadata<Block>380		+ sp_offchain::OffchainWorkerApi<Block>381		+ cumulus_primitives_core::CollectCollationInfo<Block>,382	ExecutorDispatch: NativeExecutionDispatch + 'static,383	BIQ: FnOnce(384		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,385		&Configuration,386		Option<TelemetryHandle>,387		&TaskManager,388	) -> Result<389		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,390		sc_service::Error,391	>,392	BIC: FnOnce(393		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,394		Option<&Registry>,395		Option<TelemetryHandle>,396		&TaskManager,397		Arc<dyn RelayChainInterface>,398		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,399		Arc<NetworkService<Block, Hash>>,400		SyncCryptoStorePtr,401		bool,402	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,403{404	let parachain_config = prepare_node_config(parachain_config);405406	let params =407		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;408	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =409		params.other;410411	let client = params.client.clone();412	let backend = params.backend.clone();413	let mut task_manager = params.task_manager;414415	let (relay_chain_interface, collator_key) = build_relay_chain_interface(416		polkadot_config,417		&parachain_config,418		telemetry_worker_handle,419		&mut task_manager,420		collator_options.clone(),421		hwbench.clone(),422	)423	.await424	.map_err(|e| match e {425		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,426		s => s.to_string().into(),427	})?;428429	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);430431	let force_authoring = parachain_config.force_authoring;432	let validator = parachain_config.role.is_authority();433	let prometheus_registry = parachain_config.prometheus_registry().cloned();434	let transaction_pool = params.transaction_pool.clone();435	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);436437	let (network, system_rpc_tx, start_network) =438		sc_service::build_network(sc_service::BuildNetworkParams {439			config: &parachain_config,440			client: client.clone(),441			transaction_pool: transaction_pool.clone(),442			spawn_handle: task_manager.spawn_handle(),443			import_queue: import_queue.clone(),444			block_announce_validator_builder: Some(Box::new(|_| {445				Box::new(block_announce_validator)446			})),447			warp_sync: None,448		})?;449450	let rpc_client = client.clone();451	let rpc_pool = transaction_pool.clone();452	let select_chain = params.select_chain.clone();453	let rpc_network = network.clone();454455	let rpc_frontier_backend = frontier_backend.clone();456457	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(458		task_manager.spawn_handle(),459		overrides_handle::<_, _, Runtime>(client.clone()),460		50,461		50,462		prometheus_registry.clone(),463	));464465	task_manager.spawn_essential_handle().spawn(466		"frontier-mapping-sync-worker",467		None,468		MappingSyncWorker::new(469			client.import_notification_stream(),470			Duration::new(6, 0),471			client.clone(),472			backend.clone(),473			frontier_backend.clone(),474			3,475			0,476			SyncStrategy::Normal,477		)478		.for_each(|()| futures::future::ready(())),479	);480481	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {482		let full_deps = unique_rpc::FullDeps {483			backend: rpc_frontier_backend.clone(),484			deny_unsafe,485			client: rpc_client.clone(),486			pool: rpc_pool.clone(),487			graph: rpc_pool.pool().clone(),488			// TODO: Unhardcode489			enable_dev_signer: false,490			filter_pool: filter_pool.clone(),491			network: rpc_network.clone(),492			select_chain: select_chain.clone(),493			is_authority: validator,494			// TODO: Unhardcode495			max_past_logs: 10000,496			block_data_cache: block_data_cache.clone(),497			fee_history_cache: fee_history_cache.clone(),498			// TODO: Unhardcode499			fee_history_limit: 2048,500		};501502		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(503			full_deps,504			subscription_task_executor,505		)506		.map_err(Into::into)507	});508509	sc_service::spawn_tasks(sc_service::SpawnTasksParams {510		rpc_builder,511		client: client.clone(),512		transaction_pool: transaction_pool.clone(),513		task_manager: &mut task_manager,514		config: parachain_config,515		keystore: params.keystore_container.sync_keystore(),516		backend: backend.clone(),517		network: network.clone(),518		system_rpc_tx,519		telemetry: telemetry.as_mut(),520	})?;521522	if let Some(hwbench) = hwbench {523		sc_sysinfo::print_hwbench(&hwbench);524525		if let Some(ref mut telemetry) = telemetry {526			let telemetry_handle = telemetry.handle();527			task_manager.spawn_handle().spawn(528				"telemetry_hwbench",529				None,530				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),531			);532		}533	}534535	let announce_block = {536		let network = network.clone();537		Arc::new(move |hash, data| network.announce_block(hash, data))538	};539540	let relay_chain_slot_duration = Duration::from_secs(6);541542	if validator {543		let parachain_consensus = build_consensus(544			client.clone(),545			prometheus_registry.as_ref(),546			telemetry.as_ref().map(|t| t.handle()),547			&task_manager,548			relay_chain_interface.clone(),549			transaction_pool,550			network,551			params.keystore_container.sync_keystore(),552			force_authoring,553		)?;554555		let spawner = task_manager.spawn_handle();556557		let params = StartCollatorParams {558			para_id: id,559			block_status: client.clone(),560			announce_block,561			client: client.clone(),562			task_manager: &mut task_manager,563			spawner,564			parachain_consensus,565			import_queue,566			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),567			relay_chain_interface,568			relay_chain_slot_duration,569		};570571		start_collator(params).await?;572	} else {573		let params = StartFullNodeParams {574			client: client.clone(),575			announce_block,576			task_manager: &mut task_manager,577			para_id: id,578			import_queue,579			relay_chain_interface,580			relay_chain_slot_duration,581			collator_options,582		};583584		start_full_node(params)?;585	}586587	start_network.start_network();588589	Ok((task_manager, client))590}591592/// Build the import queue for the the parachain runtime.593pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(594	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,595	config: &Configuration,596	telemetry: Option<TelemetryHandle>,597	task_manager: &TaskManager,598) -> Result<599	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,600	sc_service::Error,601>602where603	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>604		+ Send605		+ Sync606		+ 'static,607	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>608		+ sp_block_builder::BlockBuilder<Block>609		+ sp_consensus_aura::AuraApi<Block, AuraId>610		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,611	ExecutorDispatch: NativeExecutionDispatch + 'static,612{613	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;614615	cumulus_client_consensus_aura::import_queue::<616		sp_consensus_aura::sr25519::AuthorityPair,617		_,618		_,619		_,620		_,621		_,622		_,623	>(cumulus_client_consensus_aura::ImportQueueParams {624		block_import: client.clone(),625		client: client.clone(),626		create_inherent_data_providers: move |_, _| async move {627			let time = sp_timestamp::InherentDataProvider::from_system_time();628629			let slot =630				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(631					*time,632					slot_duration,633				);634635			Ok((time, slot))636		},637		registry: config.prometheus_registry(),638		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),639		spawner: &task_manager.spawn_essential_handle(),640		telemetry,641	})642	.map_err(Into::into)643}644645/// Start a normal parachain node.646pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(647	parachain_config: Configuration,648	polkadot_config: Configuration,649	collator_options: CollatorOptions,650	id: ParaId,651	hwbench: Option<sc_sysinfo::HwBench>,652) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>653where654	Runtime: RuntimeInstance + Send + Sync + 'static,655	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,656	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,657	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>658		+ Send659		+ Sync660		+ 'static,661	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>662		+ fp_rpc::EthereumRuntimeRPCApi<Block>663		+ fp_rpc::ConvertTransactionRuntimeApi<Block>664		+ sp_session::SessionKeys<Block>665		+ sp_block_builder::BlockBuilder<Block>666		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>667		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>668		+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>669		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>670		+ rmrk_rpc::RmrkApi<671			Block,672			AccountId,673			RmrkCollectionInfo<AccountId>,674			RmrkInstanceInfo<AccountId>,675			RmrkResourceInfo,676			RmrkPropertyInfo,677			RmrkBaseInfo<AccountId>,678			RmrkPartType,679			RmrkTheme,680		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>681		+ sp_api::Metadata<Block>682		+ sp_offchain::OffchainWorkerApi<Block>683		+ cumulus_primitives_core::CollectCollationInfo<Block>684		+ sp_consensus_aura::AuraApi<Block, AuraId>,685	ExecutorDispatch: NativeExecutionDispatch + 'static,686{687	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(688		parachain_config,689		polkadot_config,690		collator_options,691		id,692		parachain_build_import_queue,693		|client,694		 prometheus_registry,695		 telemetry,696		 task_manager,697		 relay_chain_interface,698		 transaction_pool,699		 sync_oracle,700		 keystore,701		 force_authoring| {702			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;703704			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(705				task_manager.spawn_handle(),706				client.clone(),707				transaction_pool,708				prometheus_registry,709				telemetry.clone(),710			);711712			Ok(AuraConsensus::build::<713				sp_consensus_aura::sr25519::AuthorityPair,714				_,715				_,716				_,717				_,718				_,719				_,720			>(BuildAuraConsensusParams {721				proposer_factory,722				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {723					let relay_chain_interface = relay_chain_interface.clone();724					async move {725						let parachain_inherent =726						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(727							relay_parent,728							&relay_chain_interface,729							&validation_data,730							id,731						).await;732733						let time = sp_timestamp::InherentDataProvider::from_system_time();734735						let slot =736						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(737							*time,738							slot_duration,739						);740741						let parachain_inherent = parachain_inherent.ok_or_else(|| {742							Box::<dyn std::error::Error + Send + Sync>::from(743								"Failed to create parachain inherent",744							)745						})?;746						Ok((time, slot, parachain_inherent))747					}748				},749				block_import: client.clone(),750				para_client: client,751				backoff_authoring_blocks: Option::<()>::None,752				sync_oracle,753				keystore,754				force_authoring,755				slot_duration,756				// We got around 500ms for proposing757				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),758				telemetry,759				max_block_proposal_slot_portion: None,760			}))761		},762		hwbench,763	)764	.await765}766767fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(768	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,769	config: &Configuration,770	_: Option<TelemetryHandle>,771	task_manager: &TaskManager,772) -> Result<773	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,774	sc_service::Error,775>776where777	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>778		+ Send779		+ Sync780		+ 'static,781	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>782		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,783	ExecutorDispatch: NativeExecutionDispatch + 'static,784{785	Ok(sc_consensus_manual_seal::import_queue(786		Box::new(client.clone()),787		&task_manager.spawn_essential_handle(),788		config.prometheus_registry(),789	))790}791792/// Builds a new development service. This service uses instant seal, and mocks793/// the parachain inherent794pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(795	config: Configuration,796	autoseal_interval: Duration,797) -> sc_service::error::Result<TaskManager>798where799	Runtime: RuntimeInstance + Send + Sync + 'static,800	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,801	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,802	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>803		+ Send804		+ Sync805		+ 'static,806	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>807		+ fp_rpc::EthereumRuntimeRPCApi<Block>808		+ fp_rpc::ConvertTransactionRuntimeApi<Block>809		+ sp_session::SessionKeys<Block>810		+ sp_block_builder::BlockBuilder<Block>811		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>812		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>813		+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>814		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>815		+ rmrk_rpc::RmrkApi<816			Block,817			AccountId,818			RmrkCollectionInfo<AccountId>,819			RmrkInstanceInfo<AccountId>,820			RmrkResourceInfo,821			RmrkPropertyInfo,822			RmrkBaseInfo<AccountId>,823			RmrkPartType,824			RmrkTheme,825		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>826		+ sp_api::Metadata<Block>827		+ sp_offchain::OffchainWorkerApi<Block>828		+ cumulus_primitives_core::CollectCollationInfo<Block>829		+ sp_consensus_aura::AuraApi<Block, AuraId>,830	ExecutorDispatch: NativeExecutionDispatch + 'static,831{832	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};833	use fc_consensus::FrontierBlockImport;834	use sc_client_api::HeaderBackend;835836	let sc_service::PartialComponents {837		client,838		backend,839		mut task_manager,840		import_queue,841		keystore_container,842		select_chain: maybe_select_chain,843		transaction_pool,844		other:845			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),846	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(847		&config,848		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,849	)?;850	let prometheus_registry = config.prometheus_registry().cloned();851852	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(853		task_manager.spawn_handle(),854		overrides_handle::<_, _, Runtime>(client.clone()),855		50,856		50,857		prometheus_registry.clone(),858	));859860	let (network, system_rpc_tx, network_starter) =861		sc_service::build_network(sc_service::BuildNetworkParams {862			config: &config,863			client: client.clone(),864			transaction_pool: transaction_pool.clone(),865			spawn_handle: task_manager.spawn_handle(),866			import_queue,867			block_announce_validator_builder: None,868			warp_sync: None,869		})?;870871	if config.offchain_worker.enabled {872		sc_service::build_offchain_workers(873			&config,874			task_manager.spawn_handle(),875			client.clone(),876			network.clone(),877		);878	}879880	let collator = config.role.is_authority();881882	let select_chain = maybe_select_chain.clone();883884	if collator {885		let block_import =886			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());887888		let env = sc_basic_authorship::ProposerFactory::new(889			task_manager.spawn_handle(),890			client.clone(),891			transaction_pool.clone(),892			prometheus_registry.as_ref(),893			telemetry.as_ref().map(|x| x.handle()),894		);895896		let transactions_commands_stream: Box<897			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,898		> = Box::new(899			transaction_pool900				.pool()901				.validated_pool()902				.import_notification_stream()903				.map(|_| EngineCommand::SealNewBlock {904					create_empty: true,905					finalize: false,906					parent_hash: None,907					sender: None,908				}),909		);910911		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));912		let idle_commands_stream: Box<913			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,914		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {915			create_empty: true,916			finalize: false,917			parent_hash: None,918			sender: None,919		}));920921		let commands_stream = select(transactions_commands_stream, idle_commands_stream);922923		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;924		let client_set_aside_for_cidp = client.clone();925926		task_manager.spawn_essential_handle().spawn_blocking(927			"authorship_task",928			Some("block-authoring"),929			run_manual_seal(ManualSealParams {930				block_import,931				env,932				client: client.clone(),933				pool: transaction_pool.clone(),934				commands_stream,935				select_chain: select_chain.clone(),936				consensus_data_provider: None,937				create_inherent_data_providers: move |block: Hash, ()| {938					let current_para_block = client_set_aside_for_cidp939						.number(block)940						.expect("Header lookup should succeed")941						.expect("Header passed in as parent should be present in backend.");942943					let client_for_xcm = client_set_aside_for_cidp.clone();944					async move {945						let time = sp_timestamp::InherentDataProvider::from_system_time();946947						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {948							current_para_block,949							relay_offset: 1000,950							relay_blocks_per_para_block: 2,951							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(952								&*client_for_xcm,953								block,954								Default::default(),955								Default::default(),956							),957							raw_downward_messages: vec![],958							raw_horizontal_messages: vec![],959						};960961						let slot =962						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(963							*time,964							slot_duration,965						);966967						Ok((time, slot, mocked_parachain))968					}969				},970			}),971		);972	}973974	task_manager.spawn_essential_handle().spawn(975		"frontier-mapping-sync-worker",976		Some("block-authoring"),977		MappingSyncWorker::new(978			client.import_notification_stream(),979			Duration::new(6, 0),980			client.clone(),981			backend.clone(),982			frontier_backend.clone(),983			3,984			0,985			SyncStrategy::Normal,986		)987		.for_each(|()| futures::future::ready(())),988	);989990	let rpc_client = client.clone();991	let rpc_pool = transaction_pool.clone();992	let rpc_network = network.clone();993	let rpc_frontier_backend = frontier_backend.clone();994	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {995		let full_deps = unique_rpc::FullDeps {996			backend: rpc_frontier_backend.clone(),997			deny_unsafe,998			client: rpc_client.clone(),999			pool: rpc_pool.clone(),1000			graph: rpc_pool.pool().clone(),1001			// TODO: Unhardcode1002			enable_dev_signer: false,1003			filter_pool: filter_pool.clone(),1004			network: rpc_network.clone(),1005			select_chain: select_chain.clone(),1006			is_authority: collator,1007			// TODO: Unhardcode1008			max_past_logs: 10000,1009			block_data_cache: block_data_cache.clone(),1010			fee_history_cache: fee_history_cache.clone(),1011			// TODO: Unhardcode1012			fee_history_limit: 2048,1013		};10141015		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1016			full_deps,1017			subscription_executor,1018		)1019		.map_err(Into::into)1020	});10211022	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1023		network,1024		client,1025		keystore: keystore_container.sync_keystore(),1026		task_manager: &mut task_manager,1027		transaction_pool,1028		rpc_builder,1029		backend,1030		system_rpc_tx,1031		config,1032		telemetry: None,1033	})?;10341035	network_starter.start_network();1036	Ok(task_manager)1037}
modifiednode/rpc/Cargo.tomldiffbeforeafterboth
--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -53,6 +53,7 @@
 pallet-unique = { path = "../../pallets/unique" }
 uc-rpc = { path = "../../client/rpc" }
 up-rpc = { path = "../../primitives/rpc" }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc"}
 rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
 up-data-structs = { default-features = false, path = "../../primitives/data-structs" }
 
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -38,6 +38,7 @@
 use sp_block_builder::BlockBuilder;
 use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
 use sc_service::TransactionPool;
+use uc_rpc::AppPromotion;
 use std::{collections::BTreeMap, sync::Arc};
 
 use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance};
@@ -147,6 +148,7 @@
 	C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,
 	C::Api:
 		up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,
+	C::Api: app_promotion_rpc::AppPromotionApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,
 	C::Api: rmrk_rpc::RmrkApi<
 		Block,
 		AccountId,
@@ -171,6 +173,7 @@
 		EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer,
 	};
 	use uc_rpc::{UniqueApiServer, Unique};
+	use uc_rpc::{AppPromotionApiServer, AppPromotion};
 
 	#[cfg(not(feature = "unique-runtime"))]
 	use uc_rpc::{RmrkApiServer, Rmrk};
@@ -229,6 +232,9 @@
 
 	io.merge(Unique::new(client.clone()).into_rpc())?;
 
+	// #[cfg(not(feature = "unique-runtime"))]
+	io.merge(AppPromotion::new(client.clone()).into_rpc())?;
+
 	#[cfg(not(feature = "unique-runtime"))]
 	io.merge(Rmrk::new(client.clone()).into_rpc())?;
 
addedprimitives/app_promotion_rpc/CHANGELOG.mddiffbeforeafterboth
--- /dev/null
+++ b/primitives/app_promotion_rpc/CHANGELOG.md
@@ -0,0 +1,5 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+<!-- bureaucrate goes here -->
addedprimitives/app_promotion_rpc/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/primitives/app_promotion_rpc/Cargo.toml
@@ -0,0 +1,29 @@
+[package]
+name = "app-promotion-rpc"
+version = "0.1.0"
+license = "GPLv3"
+edition = "2021"
+
+[dependencies]
+pallet-common = { default-features = false, path = '../../pallets/common' }
+up-data-structs = { default-features = false, path = '../data-structs' }
+codec = { package = "parity-scale-codec", version = "3.1.2", default-features = false, features = [
+	"derive",
+] }
+sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
+
+[features]
+default = ["std"]
+std = [
+	"codec/std",
+	"sp-core/std",
+	"sp-std/std",
+	"sp-api/std",
+	"sp-runtime/std",
+	"pallet-common/std",
+	"up-data-structs/std",
+]
addedprimitives/app_promotion_rpc/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/app_promotion_rpc/src/lib.rs
@@ -0,0 +1,47 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use up_data_structs::{
+	CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
+	PropertyKeyPermission, TokenData, TokenChild,
+};
+
+use sp_std::vec::Vec;
+use codec::Decode;
+use sp_runtime::{
+	DispatchError,
+	traits::{AtLeast32BitUnsigned, Member},
+};
+
+type Result<T> = core::result::Result<T, DispatchError>;
+
+sp_api::decl_runtime_apis! {
+	#[api_version(2)]
+	/// Trait for generate rpc.
+	pub trait AppPromotionApi<BlockNumber ,CrossAccountId, AccountId> where
+		BlockNumber: Decode + Member + AtLeast32BitUnsigned,
+		AccountId: Decode,
+		CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,
+	{
+		fn total_staked(staker: Option<CrossAccountId>) -> Result<u128>;
+		fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>>;
+		fn total_staking_locked(staker: CrossAccountId) -> Result<u128>;
+		fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128>;
+		fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>>;
+	}
+}
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -127,11 +127,5 @@
 		fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;
 
 		fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;
-		fn total_staked(staker: Option<CrossAccountId>) -> Result<u128>;
-		fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>>;
-		fn total_staking_locked(staker: CrossAccountId) -> Result<u128>;
-		fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128>;
-		fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>>;
-
 	}
 }
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -187,25 +187,47 @@
                 fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {
                     dispatch_unique_runtime!(collection.total_pieces(token_id))
                 }
+            }
 
+            impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {
                 fn total_staked(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {
-                    Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default())
-                }
+                    #[cfg(not(feature = "app-promotion"))]
+                    return unsupported!();
 
+                    #[cfg(feature = "app-promotion")]
+                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());
+                }
+                
                 fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {
-                    Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker))
+                    #[cfg(not(feature = "app-promotion"))]
+                    return unsupported!();
+                    
+                    #[cfg(feature = "app-promotion")]
+                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));
                 }
 
                 fn total_staking_locked(staker: CrossAccountId) -> Result<u128, DispatchError> {
-                    Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_locked_balance(staker))
+                    #[cfg(not(feature = "app-promotion"))]
+                    return unsupported!();
+                    
+                    #[cfg(feature = "app-promotion")]
+                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_locked_balance(staker));
                 }
 
                 fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {
-                    Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker))
+                    #[cfg(not(feature = "app-promotion"))]
+                    return unsupported!();
+                    
+                    #[cfg(feature = "app-promotion")]
+                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));
                 }
 
                 fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {
-                    Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))
+                    #[cfg(not(feature = "app-promotion"))]
+                    return unsupported!();
+                    
+                    #[cfg(feature = "app-promotion")]
+                    return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))
                 }
             }
 
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -83,6 +83,7 @@
     'pallet-base-fee/std',
     'fp-rpc/std',
     'up-rpc/std',
+    'app-promotion-rpc/std',
     'fp-evm-mapping/std',
     'fp-self-contained/std',
     'parachain-info/std',
@@ -414,6 +415,7 @@
 derivative = "2.2.0"
 pallet-unique = { path = '../../pallets/unique', default-features = false }
 up-rpc = { path = "../../primitives/rpc", default-features = false }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false}
 rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
 fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
 pallet-inflation = { path = '../../pallets/inflation', default-features = false }
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -82,6 +82,7 @@
     'pallet-base-fee/std',
     'fp-rpc/std',
     'up-rpc/std',
+    'app-promotion-rpc/std',
     'fp-evm-mapping/std',
     'fp-self-contained/std',
     'parachain-info/std',
@@ -416,8 +417,10 @@
 derivative = "2.2.0"
 pallet-unique = { path = '../../pallets/unique', default-features = false }
 up-rpc = { path = "../../primitives/rpc", default-features = false }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false}
 fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
 pallet-inflation = { path = '../../pallets/inflation', default-features = false }
+pallet-app-promotion = { path = '../../pallets/app-promotion', default-features = false }
 up-data-structs = { path = '../../primitives/data-structs', default-features = false }
 pallet-configuration = { default-features = false, path = "../../pallets/configuration" }
 pallet-common = { default-features = false, path = "../../pallets/common" }
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -83,6 +83,7 @@
     'pallet-base-fee/std',
     'fp-rpc/std',
     'up-rpc/std',
+    'app-promotion-rpc/std',
     'fp-evm-mapping/std',
     'fp-self-contained/std',
     'parachain-info/std',
@@ -409,8 +410,10 @@
 derivative = "2.2.0"
 pallet-unique = { path = '../../pallets/unique', default-features = false }
 up-rpc = { path = "../../primitives/rpc", default-features = false }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false}
 rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
 pallet-inflation = { path = '../../pallets/inflation', default-features = false }
+pallet-app-promotion = { path = '../../pallets/app-promotion', default-features = false }
 up-data-structs = { path = '../../primitives/data-structs', default-features = false }
 pallet-configuration = { default-features = false, path = "../../pallets/configuration" }
 pallet-common = { default-features = false, path = "../../pallets/common" }
addedtests/src/interfaces/appPromotion/definitions.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/interfaces/appPromotion/definitions.ts
@@ -0,0 +1,66 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+type RpcParam = {
+  name: string;
+  type: string;
+  isOptional?: true;
+};
+
+const CROSS_ACCOUNT_ID_TYPE = 'PalletEvmAccountBasicCrossAccountIdRepr';
+
+const collectionParam = {name: 'collection', type: 'u32'};
+const tokenParam = {name: 'tokenId', type: 'u32'};
+const propertyKeysParam = {name: 'propertyKeys', type: 'Vec<String>', isOptional: true};
+const crossAccountParam = (name = 'account') => ({name, type: CROSS_ACCOUNT_ID_TYPE});
+const atParam = {name: 'at', type: 'Hash', isOptional: true};
+
+const fun = (description: string, params: RpcParam[], type: string) => ({
+  description,
+  params: [...params, atParam],
+  type,
+});
+
+export default {
+  types: {},
+  rpc: {
+    totalStaked: fun(
+      'Returns the total amount of staked tokens',
+      [{name: 'staker', type: CROSS_ACCOUNT_ID_TYPE, isOptional: true}],
+      'u128',
+    ),
+    totalStakedPerBlock: fun(
+      'Returns the total amount of staked tokens per block when staked',
+      [crossAccountParam('staker')],
+      'Vec<(u32, u128)>',
+    ),
+    totalStakingLocked: fun(
+      'Return the total amount locked by staking tokens',
+      [crossAccountParam('staker')],
+      'u128',
+    ),
+    pendingUnstake: fun(
+      'Returns the total amount of unstaked tokens',
+      [{name: 'staker', type: CROSS_ACCOUNT_ID_TYPE, isOptional: true}],
+      'u128',
+    ),
+    pendingUnstakePerBlock: fun(
+      'Returns the total amount of unstaked tokens per block',
+      [crossAccountParam('staker')],
+      'Vec<(u32, u128)>',
+    ),
+  },
+};
addedtests/src/interfaces/appPromotion/index.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/interfaces/appPromotion/index.ts
@@ -0,0 +1,4 @@
+// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
+/* eslint-disable */
+
+export * from './types';
addedtests/src/interfaces/appPromotion/types.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/interfaces/appPromotion/types.ts
@@ -0,0 +1,4 @@
+// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
+/* eslint-disable */
+
+export type PHANTOM_APPPROMOTION = 'appPromotion';
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -269,7 +269,7 @@
        **/
       NoPendingSponsor: AugmentedError<ApiType>;
       /**
-       * This method is only executable by owner.
+       * This method is only executable by contract owner
        **/
       NoPermission: AugmentedError<ApiType>;
       /**
@@ -278,7 +278,13 @@
       [key: string]: AugmentedError<ApiType>;
     };
     evmMigration: {
+      /**
+       * Migration of this account is not yet started, or already finished.
+       **/
       AccountIsNotMigrating: AugmentedError<ApiType>;
+      /**
+       * Can only migrate to empty address.
+       **/
       AccountNotEmpty: AugmentedError<ApiType>;
       /**
        * Generic error
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -335,7 +335,7 @@
        * 
        * Currently used to store RMRK data.
        **/
-      tokenAuxProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array, arg3: UpDataStructsPropertyScope | 'None' | 'Rmrk' | 'Eth' | number | Uint8Array, arg4: Bytes | string | Uint8Array) => Observable<Option<Bytes>>, [u32, u32, UpDataStructsPropertyScope, Bytes]> & QueryableStorageEntry<ApiType, [u32, u32, UpDataStructsPropertyScope, Bytes]>;
+      tokenAuxProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array, arg3: UpDataStructsPropertyScope | 'None' | 'Rmrk' | number | Uint8Array, arg4: Bytes | string | Uint8Array) => Observable<Option<Bytes>>, [u32, u32, UpDataStructsPropertyScope, Bytes]> & QueryableStorageEntry<ApiType, [u32, u32, UpDataStructsPropertyScope, Bytes]>;
       /**
        * Used to enumerate token's children.
        **/
modifiedtests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -35,6 +35,28 @@
 
 declare module '@polkadot/rpc-core/types/jsonrpc' {
   interface RpcInterface {
+    appPromotion: {
+      /**
+       * Returns the total amount of unstaked tokens
+       **/
+      pendingUnstake: AugmentedRpc<(staker?: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
+      /**
+       * Returns the total amount of unstaked tokens per block
+       **/
+      pendingUnstakePerBlock: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<ITuple<[u32, u128]>>>>;
+      /**
+       * Returns the total amount of staked tokens
+       **/
+      totalStaked: AugmentedRpc<(staker?: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
+      /**
+       * Returns the total amount of staked tokens per block when staked
+       **/
+      totalStakedPerBlock: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<ITuple<[u32, u128]>>>>;
+      /**
+       * Return the total amount locked by staking tokens
+       **/
+      totalStakingLocked: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
+    };
     author: {
       /**
        * Returns true if the keystore has private keys for the given public key and key type.
@@ -702,15 +724,7 @@
        * Get the number of blocks until sponsoring a transaction is available
        **/
       nextSponsored: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, account: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<u64>>>;
-      /**
-       * Returns the total amount of unstaked tokens
-       **/
-      pendingUnstake: AugmentedRpc<(staker?: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
       /**
-       * Returns the total amount of unstaked tokens per block
-       **/
-      pendingUnstakePerBlock: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<ITuple<[u32, u128]>>>>;
-      /**
        * Get property permissions, optionally limited to the provided keys
        **/
       propertyPermissions: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, propertyKeys?: Vec<Text> | (Text | string)[], at?: Hash | string | Uint8Array) => Observable<Vec<UpDataStructsPropertyKeyPermission>>>;
@@ -746,18 +760,6 @@
        * Get the total amount of pieces of an RFT
        **/
       totalPieces: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<u128>>>;
-      /**
-       * Returns the total amount of staked tokens
-       **/
-      totalStaked: AugmentedRpc<(staker?: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
-      /**
-       * Returns the total amount of staked tokens per block when staked
-       **/
-      totalStakedPerBlock: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<ITuple<[u32, u128]>>>>;
-      /**
-       * Return the total amount locked by staking tokens
-       **/
-      totalStakingLocked: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
       /**
        * Get the amount of distinctive tokens present in a collection
        **/
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -181,8 +181,21 @@
       [key: string]: SubmittableExtrinsicFunction<ApiType>;
     };
     evmMigration: {
+      /**
+       * Start contract migration, inserts contract stub at target address,
+       * and marks account as pending, allowing to insert storage
+       **/
       begin: AugmentedSubmittable<(address: H160 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160]>;
+      /**
+       * Finish contract migration, allows it to be called.
+       * It is not possible to alter contract storage via [`Self::set_data`]
+       * after this call.
+       **/
       finish: AugmentedSubmittable<(address: H160 | string | Uint8Array, code: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160, Bytes]>;
+      /**
+       * Insert items into contract storage, this method can be called
+       * multiple times
+       **/
       setData: AugmentedSubmittable<(address: H160 | string | Uint8Array, data: Vec<ITuple<[H256, H256]>> | ([H256 | string | Uint8Array, H256 | string | Uint8Array])[]) => SubmittableExtrinsic<ApiType>, [H160, Vec<ITuple<[H256, H256]>>]>;
       /**
        * Generic tx
@@ -372,7 +385,7 @@
       stopAppPromotion: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
       stopSponsoringCollection: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
       stopSponsoringContract: AugmentedSubmittable<(contractId: H160 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160]>;
-      unstake: AugmentedSubmittable<(amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u128]>;
+      unstake: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
       /**
        * Generic tx
        **/
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -822,9 +822,6 @@
     readonly amount: u128;
   } & Struct;
   readonly isUnstake: boolean;
-  readonly asUnstake: {
-    readonly amount: u128;
-  } & Struct;
   readonly isSponsorCollection: boolean;
   readonly asSponsorCollection: {
     readonly collectionId: u32;
@@ -2639,8 +2636,7 @@
 export interface UpDataStructsPropertyScope extends Enum {
   readonly isNone: boolean;
   readonly isRmrk: boolean;
-  readonly isEth: boolean;
-  readonly type: 'None' | 'Rmrk' | 'Eth';
+  readonly type: 'None' | 'Rmrk';
 }
 
 /** @name UpDataStructsRpcCollection */
modifiedtests/src/interfaces/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/definitions.ts
+++ b/tests/src/interfaces/definitions.ts
@@ -15,5 +15,6 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 export {default as unique} from './unique/definitions';
+export {default as appPromotion} from './appPromotion/definitions';
 export {default as rmrk} from './rmrk/definitions';
 export {default as default} from './default/definitions';
\ No newline at end of file
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2467,9 +2467,7 @@
       stake: {
         amount: 'u128',
       },
-      unstake: {
-        amount: 'u128',
-      },
+      unstake: 'Null',
       sponsor_collection: {
         collectionId: 'u32',
       },
@@ -3078,7 +3076,7 @@
    * Lookup403: up_data_structs::PropertyScope
    **/
   UpDataStructsPropertyScope: {
-    _enum: ['None', 'Rmrk', 'Eth']
+    _enum: ['None', 'Rmrk']
   },
   /**
    * Lookup405: pallet_nonfungible::pallet::Error<T>
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -2675,9 +2675,6 @@
       readonly amount: u128;
     } & Struct;
     readonly isUnstake: boolean;
-    readonly asUnstake: {
-      readonly amount: u128;
-    } & Struct;
     readonly isSponsorCollection: boolean;
     readonly asSponsorCollection: {
       readonly collectionId: u32;
@@ -3238,8 +3235,7 @@
   interface UpDataStructsPropertyScope extends Enum {
     readonly isNone: boolean;
     readonly isRmrk: boolean;
-    readonly isEth: boolean;
-    readonly type: 'None' | 'Rmrk' | 'Eth';
+    readonly type: 'None' | 'Rmrk';
   }
 
   /** @name PalletNonfungibleError (405) */
modifiedtests/src/interfaces/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types.ts
+++ b/tests/src/interfaces/types.ts
@@ -2,5 +2,6 @@
 /* eslint-disable */
 
 export * from './unique/types';
+export * from './appPromotion/types';
 export * from './rmrk/types';
 export * from './default/types';
modifiedtests/src/interfaces/unique/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -175,30 +175,5 @@
       [collectionParam, tokenParam], 
       'Option<u128>',
     ),
-    totalStaked: fun(
-      'Returns the total amount of staked tokens',
-      [{name: 'staker', type: CROSS_ACCOUNT_ID_TYPE, isOptional: true}],
-      'u128',
-    ),
-    totalStakedPerBlock: fun(
-      'Returns the total amount of staked tokens per block when staked',
-      [crossAccountParam('staker')],
-      'Vec<(u32, u128)>',
-    ),
-    totalStakingLocked: fun(
-      'Return the total amount locked by staking tokens',
-      [crossAccountParam('staker')],
-      'u128',
-    ),
-    pendingUnstake: fun(
-      'Returns the total amount of unstaked tokens',
-      [{name: 'staker', type: CROSS_ACCOUNT_ID_TYPE, isOptional: true}],
-      'u128',
-    ),
-    pendingUnstakePerBlock: fun(
-      'Returns the total amount of unstaked tokens per block',
-      [crossAccountParam('staker')],
-      'Vec<(u32, u128)>',
-    ),
   },
 };
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -42,6 +42,7 @@
     },
     rpc: {
       unique: defs.unique.rpc,
+      appPromotion: defs.appPromotion.rpc,
       rmrk: defs.rmrk.rpc,
       eth: {
         feeHistory: {
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -35,6 +35,7 @@
       },
       rpc: {
         unique: defs.unique.rpc,
+        appPromotion: defs.appPromotion.rpc,
         rmrk: defs.rmrk.rpc,
         eth: {
           feeHistory: {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2027,24 +2027,24 @@
   }
 
   async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {
-    if (address) return (await this.helper.callRpc('api.rpc.unique.totalStaked', [address])).toBigInt();
-    return (await this.helper.callRpc('api.rpc.unique.totalStaked')).toBigInt();
+    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();
+    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();
   }
 
   async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {
-    return (await this.helper.callRpc('api.rpc.unique.totalStakingLocked', [address])).toBigInt();
+    return (await this.helper.callRpc('api.rpc.appPromotion.totalStakingLocked', [address])).toBigInt();
   }
 
   async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {
-    return (await this.helper.callRpc('api.rpc.unique.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
+    return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
   }
 
   async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {
-    return (await this.helper.callRpc('api.rpc.unique.pendingUnstake', [address])).toBigInt();
+    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();
   }
   
   async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {
-    return (await this.helper.callRpc('api.rpc.unique.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
+    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
   }
 }