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

difftreelog

refactor ethereum RPC/tasks initialization

Yaroslav Bolyukin2023-06-16parent: #f28d992.patch.diff
in: master

7 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6507,11 +6507,13 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
+ "hex-literal",
  "parity-scale-codec",
  "scale-info",
  "smallvec",
  "sp-arithmetic",
  "sp-core",
+ "sp-io",
  "sp-std",
  "xcm",
 ]
@@ -13841,9 +13843,11 @@
  "fc-rpc",
  "fc-rpc-core",
  "fp-rpc",
+ "fp-storage",
  "frame-benchmarking",
  "frame-benchmarking-cli",
  "futures",
+ "jsonrpsee",
  "log",
  "opal-runtime",
  "pallet-transaction-payment-rpc-runtime-api",
@@ -13861,6 +13865,7 @@
  "sc-executor",
  "sc-network",
  "sc-network-sync",
+ "sc-rpc",
  "sc-service",
  "sc-sysinfo",
  "sc-telemetry",
@@ -13906,9 +13911,9 @@
  "fp-rpc",
  "fp-storage",
  "jsonrpsee",
+ "pallet-ethereum",
  "pallet-transaction-payment-rpc",
  "sc-client-api",
- "sc-consensus-grandpa",
  "sc-network",
  "sc-network-sync",
  "sc-rpc",
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -125,7 +125,6 @@
 sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" }
 sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" }
 sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" }
-sc-consensus-grandpa = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" }
 sc-consensus-manual-seal = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" }
 sc-executor = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" }
 sc-network = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" }
modifiednode/cli/Cargo.tomldiffbeforeafterboth
--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -21,7 +21,7 @@
 
 [dependencies]
 clap = "4.1"
-futures = '0.3.17'
+futures = '0.3.28'
 tokio = { version = "1.24", features = ["time"] }
 serde_json = "1.0"
 
@@ -94,6 +94,9 @@
 unique-rpc = { workspace = true }
 up-pov-estimate-rpc = { workspace = true }
 up-rpc = { workspace = true }
+jsonrpsee.workspace = true
+fp-storage.workspace = true
+sc-rpc.workspace = true
 
 [build-dependencies]
 substrate-build-script-utils = { workspace = true }
modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -168,6 +168,7 @@
 					.collect(),
 			},
 			common: Default::default(),
+			configuration: Default::default(),
 			nonfungible: Default::default(),
 			treasury: Default::default(),
 			tokens: TokensConfig { balances: vec![] },
@@ -228,6 +229,7 @@
 					.to_vec(),
 			},
 			common: Default::default(),
+			configuration: Default::default(),
 			nonfungible: Default::default(),
 			balances: BalancesConfig {
 				balances: $endowed_accounts
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 sp_keystore::KeystorePtr;30use tokio::time::Interval;3132use unique_rpc::overrides_handle;3334use serde::{Serialize, Deserialize};3536// Cumulus Imports37use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};38use cumulus_client_consensus_common::{39	ParachainConsensus, ParachainBlockImport as TParachainBlockImport,40};41use cumulus_client_service::{42	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,43};44use cumulus_client_cli::CollatorOptions;45use cumulus_client_network::BlockAnnounceValidator;46use cumulus_primitives_core::ParaId;47use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;48use cumulus_relay_chain_interface::{RelayChainInterface, RelayChainResult};49use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;5051// Substrate Imports52use sp_api::BlockT;53use sc_executor::NativeElseWasmExecutor;54use sc_executor::NativeExecutionDispatch;55use sc_network::NetworkBlock;56use sc_network_sync::SyncingService;57use sc_service::{Configuration, PartialComponents, TaskManager};58use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};59use sp_runtime::traits::BlakeTwo256;60use substrate_prometheus_endpoint::Registry;61use sc_client_api::BlockchainEvents;62use sc_consensus::ImportQueue;6364use polkadot_service::CollatorPair;6566// Frontier Imports67use fc_rpc_core::types::FilterPool;68use fc_mapping_sync::{kv::MappingSyncWorker, SyncStrategy};6970use up_common::types::opaque::*;7172use crate::chain_spec::RuntimeIdentification;7374/// Unique native executor instance.75#[cfg(feature = "unique-runtime")]76pub struct UniqueRuntimeExecutor;7778#[cfg(feature = "quartz-runtime")]79/// Quartz native executor instance.80pub struct QuartzRuntimeExecutor;8182/// Opal native executor instance.83pub struct OpalRuntimeExecutor;8485#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]86pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;8788#[cfg(all(89	not(feature = "unique-runtime"),90	feature = "quartz-runtime",91	feature = "runtime-benchmarks"92))]93pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9495#[cfg(all(96	not(feature = "unique-runtime"),97	not(feature = "quartz-runtime"),98	feature = "runtime-benchmarks"99))]100pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;101102#[cfg(feature = "unique-runtime")]103impl NativeExecutionDispatch for UniqueRuntimeExecutor {104	/// Only enable the benchmarking host functions when we actually want to benchmark.105	#[cfg(feature = "runtime-benchmarks")]106	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;107	/// Otherwise we only use the default Substrate host functions.108	#[cfg(not(feature = "runtime-benchmarks"))]109	type ExtendHostFunctions = ();110111	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {112		unique_runtime::api::dispatch(method, data)113	}114115	fn native_version() -> sc_executor::NativeVersion {116		unique_runtime::native_version()117	}118}119120#[cfg(feature = "quartz-runtime")]121impl NativeExecutionDispatch for QuartzRuntimeExecutor {122	/// Only enable the benchmarking host functions when we actually want to benchmark.123	#[cfg(feature = "runtime-benchmarks")]124	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;125	/// Otherwise we only use the default Substrate host functions.126	#[cfg(not(feature = "runtime-benchmarks"))]127	type ExtendHostFunctions = ();128129	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {130		quartz_runtime::api::dispatch(method, data)131	}132133	fn native_version() -> sc_executor::NativeVersion {134		quartz_runtime::native_version()135	}136}137138impl NativeExecutionDispatch for OpalRuntimeExecutor {139	/// Only enable the benchmarking host functions when we actually want to benchmark.140	#[cfg(feature = "runtime-benchmarks")]141	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;142	/// Otherwise we only use the default Substrate host functions.143	#[cfg(not(feature = "runtime-benchmarks"))]144	type ExtendHostFunctions = ();145146	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {147		opal_runtime::api::dispatch(method, data)148	}149150	fn native_version() -> sc_executor::NativeVersion {151		opal_runtime::native_version()152	}153}154155pub struct AutosealInterval {156	interval: Interval,157}158159impl AutosealInterval {160	pub fn new(config: &Configuration, interval: Duration) -> Self {161		let _tokio_runtime = config.tokio_handle.enter();162		let interval = tokio::time::interval(interval);163164		Self { interval }165	}166}167168impl Stream for AutosealInterval {169	type Item = tokio::time::Instant;170171	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {172		self.interval.poll_tick(cx).map(Some)173	}174}175176pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(177	client: Arc<C>,178	config: &Configuration,179) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {180	let config_dir = config.base_path.config_dir(config.chain_spec.id());181	let database_dir = config_dir.join("frontier").join("db");182183	Ok(Arc::new(fc_db::kv::Backend::<Block>::new(184		client,185		&fc_db::kv::DatabaseSettings {186			source: fc_db::DatabaseSource::RocksDb {187				path: database_dir,188				cache_size: 0,189			},190		},191	)?))192}193194type FullClient<RuntimeApi, ExecutorDispatch> =195	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;196type FullBackend = sc_service::TFullBackend<Block>;197type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;198type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =199	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;200201/// Starts a `ServiceBuilder` for a full service.202///203/// Use this macro if you don't actually need the full service, but just the builder in order to204/// be able to perform chain operations.205#[allow(clippy::type_complexity)]206pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(207	config: &Configuration,208	build_import_queue: BIQ,209) -> Result<210	PartialComponents<211		FullClient<RuntimeApi, ExecutorDispatch>,212		FullBackend,213		FullSelectChain,214		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,215		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,216		(217			Option<Telemetry>,218			Option<FilterPool>,219			Arc<fc_db::kv::Backend<Block>>,220			Option<TelemetryWorkerHandle>,221			FeeHistoryCache,222		),223	>,224	sc_service::Error,225>226where227	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,228	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>229		+ Send230		+ Sync231		+ 'static,232	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,233	ExecutorDispatch: NativeExecutionDispatch + 'static,234	BIQ: FnOnce(235		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,236		Arc<FullBackend>,237		&Configuration,238		Option<TelemetryHandle>,239		&TaskManager,240	) -> Result<241		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,242		sc_service::Error,243	>,244{245	let _telemetry = config246		.telemetry_endpoints247		.clone()248		.filter(|x| !x.is_empty())249		.map(|endpoints| -> Result<_, sc_telemetry::Error> {250			let worker = TelemetryWorker::new(16)?;251			let telemetry = worker.handle().new_telemetry(endpoints);252			Ok((worker, telemetry))253		})254		.transpose()?;255256	let telemetry = config257		.telemetry_endpoints258		.clone()259		.filter(|x| !x.is_empty())260		.map(|endpoints| -> Result<_, sc_telemetry::Error> {261			let worker = TelemetryWorker::new(16)?;262			let telemetry = worker.handle().new_telemetry(endpoints);263			Ok((worker, telemetry))264		})265		.transpose()?;266267	let executor = sc_service::new_native_or_wasm_executor(config);268269	let (client, backend, keystore_container, task_manager) =270		sc_service::new_full_parts::<Block, RuntimeApi, _>(271			config,272			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),273			executor,274		)?;275	let client = Arc::new(client);276277	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());278279	let telemetry = telemetry.map(|(worker, telemetry)| {280		task_manager281			.spawn_handle()282			.spawn("telemetry", None, worker.run());283		telemetry284	});285286	let select_chain = sc_consensus::LongestChain::new(backend.clone());287288	let transaction_pool = sc_transaction_pool::BasicPool::new_full(289		config.transaction_pool.clone(),290		config.role.is_authority().into(),291		config.prometheus_registry(),292		task_manager.spawn_essential_handle(),293		client.clone(),294	);295296	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));297298	let frontier_backend = open_frontier_backend(client.clone(), config)?;299300	let import_queue = build_import_queue(301		client.clone(),302		backend.clone(),303		config,304		telemetry.as_ref().map(|telemetry| telemetry.handle()),305		&task_manager,306	)?;307	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));308309	let params = PartialComponents {310		backend,311		client,312		import_queue,313		keystore_container,314		task_manager,315		transaction_pool,316		select_chain,317		other: (318			telemetry,319			filter_pool,320			frontier_backend,321			telemetry_worker_handle,322			fee_history_cache,323		),324	};325326	Ok(params)327}328329async fn build_relay_chain_interface(330	polkadot_config: Configuration,331	parachain_config: &Configuration,332	telemetry_worker_handle: Option<TelemetryWorkerHandle>,333	task_manager: &mut TaskManager,334	collator_options: CollatorOptions,335	hwbench: Option<sc_sysinfo::HwBench>,336) -> RelayChainResult<(337	Arc<(dyn RelayChainInterface + 'static)>,338	Option<CollatorPair>,339)> {340	if collator_options.relay_chain_rpc_urls.is_empty() {341		build_inprocess_relay_chain(342			polkadot_config,343			parachain_config,344			telemetry_worker_handle,345			task_manager,346			hwbench,347		)348	} else {349		build_minimal_relay_chain_node(350			polkadot_config,351			task_manager,352			collator_options.relay_chain_rpc_urls,353		)354		.await355	}356}357358macro_rules! clone {359    ($($i:ident),* $(,)?) => {360		$(361			let $i = $i.clone();362		)*363    };364}365366/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.367///368/// This is the actual implementation that is abstract over the executor and the runtime api.369#[sc_tracing::logging::prefix_logs_with("Parachain")]370async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(371	parachain_config: Configuration,372	polkadot_config: Configuration,373	collator_options: CollatorOptions,374	id: ParaId,375	build_import_queue: BIQ,376	build_consensus: BIC,377	hwbench: Option<sc_sysinfo::HwBench>,378) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>379where380	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,381	Runtime: RuntimeInstance + Send + Sync + 'static,382	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,383	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,384	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>385		+ Send386		+ Sync387		+ 'static,388	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>389		+ fp_rpc::EthereumRuntimeRPCApi<Block>390		+ fp_rpc::ConvertTransactionRuntimeApi<Block>391		+ sp_session::SessionKeys<Block>392		+ sp_block_builder::BlockBuilder<Block>393		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>394		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>395		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>396		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>397		+ up_pov_estimate_rpc::PovEstimateApi<Block>398		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>399		+ sp_api::Metadata<Block>400		+ sp_offchain::OffchainWorkerApi<Block>401		+ cumulus_primitives_core::CollectCollationInfo<Block>,402	ExecutorDispatch: NativeExecutionDispatch + 'static,403	BIQ: FnOnce(404		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,405		Arc<FullBackend>,406		&Configuration,407		Option<TelemetryHandle>,408		&TaskManager,409	) -> Result<410		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,411		sc_service::Error,412	>,413	BIC: FnOnce(414		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,415		Arc<FullBackend>,416		Option<&Registry>,417		Option<TelemetryHandle>,418		&TaskManager,419		Arc<dyn RelayChainInterface>,420		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,421		Arc<SyncingService<Block>>,422		KeystorePtr,423		bool,424	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,425{426	let parachain_config = prepare_node_config(parachain_config);427428	let params =429		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;430	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =431		params.other;432	let net_config = sc_network::config::FullNetworkConfiguration::new(&parachain_config.network);433434	let client = params.client.clone();435	let backend = params.backend.clone();436	let mut task_manager = params.task_manager;437438	let (relay_chain_interface, collator_key) = build_relay_chain_interface(439		polkadot_config,440		&parachain_config,441		telemetry_worker_handle,442		&mut task_manager,443		collator_options.clone(),444		hwbench.clone(),445	)446	.await447	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;448449	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);450451	let force_authoring = parachain_config.force_authoring;452	let validator = parachain_config.role.is_authority();453	let prometheus_registry = parachain_config.prometheus_registry().cloned();454	let transaction_pool = params.transaction_pool.clone();455	let import_queue_service = params.import_queue.service();456457	let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =458		sc_service::build_network(sc_service::BuildNetworkParams {459			config: &parachain_config,460			net_config,461			client: client.clone(),462			transaction_pool: transaction_pool.clone(),463			spawn_handle: task_manager.spawn_handle(),464			import_queue: params.import_queue,465			block_announce_validator_builder: Some(Box::new(|_| {466				Box::new(block_announce_validator)467			})),468			warp_sync_params: None,469		})?;470471	let select_chain = params.select_chain.clone();472473	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(474		task_manager.spawn_handle(),475		overrides_handle::<_, _, Runtime>(client.clone()),476		50,477		50,478		prometheus_registry.clone(),479	));480481	let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<482		fc_mapping_sync::EthereumBlockNotification<Block>,483	> = Default::default();484	let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);485486	task_manager.spawn_essential_handle().spawn(487		"frontier-mapping-sync-worker",488		Some("frontier"),489		MappingSyncWorker::new(490			client.import_notification_stream(),491			Duration::new(6, 0),492			client.clone(),493			backend.clone(),494			overrides_handle::<_, _, Runtime>(client.clone()),495			frontier_backend.clone(),496			3,497			0,498			SyncStrategy::Parachain,499			sync_service.clone(),500			pubsub_notification_sinks.clone(),501		)502		.for_each(|()| futures::future::ready(())),503	);504505	let runtime_id = parachain_config.chain_spec.runtime_id();506507	let rpc_builder = Box::new({508		clone!(509			client,510			backend,511			pubsub_notification_sinks,512			transaction_pool,513			network,514			sync_service,515			frontier_backend,516		);517		move |deny_unsafe, subscription_task_executor| {518			clone!(519				backend,520				runtime_id,521				client,522				transaction_pool,523				filter_pool,524				network,525				select_chain,526				block_data_cache,527				fee_history_cache,528				pubsub_notification_sinks,529				frontier_backend,530			);531532			#[cfg(not(feature = "pov-estimate"))]533			let _ = backend;534535			let full_deps = unique_rpc::FullDeps {536				runtime_id,537538				#[cfg(feature = "pov-estimate")]539				exec_params: uc_rpc::pov_estimate::ExecutorParams {540					wasm_method: parachain_config.wasm_method,541					default_heap_pages: parachain_config.default_heap_pages,542					max_runtime_instances: parachain_config.max_runtime_instances,543					runtime_cache_size: parachain_config.runtime_cache_size,544				},545546				#[cfg(feature = "pov-estimate")]547				backend,548549				eth_backend: frontier_backend,550				deny_unsafe,551				client,552				graph: transaction_pool.pool().clone(),553				pool: transaction_pool,554				// TODO: Unhardcode555				enable_dev_signer: false,556				filter_pool,557				network,558				sync: sync_service.clone(),559				select_chain,560				is_authority: validator,561				// TODO: Unhardcode562				max_past_logs: 10000,563				block_data_cache,564				fee_history_cache,565				// TODO: Unhardcode566				fee_history_limit: 2048,567				pubsub_notification_sinks,568			};569570			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(571				full_deps,572				subscription_task_executor,573			)574			.map_err(Into::into)575		}576	});577578	sc_service::spawn_tasks(sc_service::SpawnTasksParams {579		rpc_builder,580		client: client.clone(),581		transaction_pool: transaction_pool.clone(),582		task_manager: &mut task_manager,583		config: parachain_config,584		keystore: params.keystore_container.keystore(),585		backend: backend.clone(),586		network: network.clone(),587		sync_service: sync_service.clone(),588		system_rpc_tx,589		telemetry: telemetry.as_mut(),590		tx_handler_controller,591	})?;592593	if let Some(hwbench) = hwbench {594		sc_sysinfo::print_hwbench(&hwbench);595596		if let Some(ref mut telemetry) = telemetry {597			let telemetry_handle = telemetry.handle();598			task_manager.spawn_handle().spawn(599				"telemetry_hwbench",600				None,601				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),602			);603		}604	}605606	let announce_block = {607		let sync_service = sync_service.clone();608		Arc::new(Box::new(move |hash, data| {609			sync_service.announce_block(hash, data)610		}))611	};612613	let relay_chain_slot_duration = Duration::from_secs(6);614615	let overseer_handle = relay_chain_interface616		.overseer_handle()617		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;618619	if validator {620		let parachain_consensus = build_consensus(621			client.clone(),622			backend.clone(),623			prometheus_registry.as_ref(),624			telemetry.as_ref().map(|t| t.handle()),625			&task_manager,626			relay_chain_interface.clone(),627			transaction_pool,628			sync_service.clone(),629			params.keystore_container.keystore(),630			force_authoring,631		)?;632633		let spawner = task_manager.spawn_handle();634635		let params = StartCollatorParams {636			para_id: id,637			block_status: client.clone(),638			announce_block,639			client: client.clone(),640			task_manager: &mut task_manager,641			spawner,642			parachain_consensus,643			import_queue: import_queue_service,644			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),645			relay_chain_interface,646			relay_chain_slot_duration,647			recovery_handle: Box::new(overseer_handle),648			sync_service,649		};650651		start_collator(params).await?;652	} else {653		let params = StartFullNodeParams {654			client: client.clone(),655			announce_block,656			task_manager: &mut task_manager,657			para_id: id,658			import_queue: import_queue_service,659			relay_chain_interface,660			relay_chain_slot_duration,661			recovery_handle: Box::new(overseer_handle),662			sync_service,663		};664665		start_full_node(params)?;666	}667668	start_network.start_network();669670	Ok((task_manager, client))671}672673/// Build the import queue for the the parachain runtime.674pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(675	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,676	backend: Arc<FullBackend>,677	config: &Configuration,678	telemetry: Option<TelemetryHandle>,679	task_manager: &TaskManager,680) -> Result<681	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,682	sc_service::Error,683>684where685	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>686		+ Send687		+ Sync688		+ 'static,689	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>690		+ sp_block_builder::BlockBuilder<Block>691		+ sp_consensus_aura::AuraApi<Block, AuraId>692		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,693	ExecutorDispatch: NativeExecutionDispatch + 'static,694{695	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;696697	let block_import = ParachainBlockImport::new(client.clone(), backend);698699	cumulus_client_consensus_aura::import_queue::<700		sp_consensus_aura::sr25519::AuthorityPair,701		_,702		_,703		_,704		_,705		_,706	>(cumulus_client_consensus_aura::ImportQueueParams {707		block_import,708		client,709		create_inherent_data_providers: move |_, _| async move {710			let time = sp_timestamp::InherentDataProvider::from_system_time();711712			let slot =713				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(714					*time,715					slot_duration,716				);717718			Ok((slot, time))719		},720		registry: config.prometheus_registry(),721		spawner: &task_manager.spawn_essential_handle(),722		telemetry,723	})724	.map_err(Into::into)725}726727/// Start a normal parachain node.728pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(729	parachain_config: Configuration,730	polkadot_config: Configuration,731	collator_options: CollatorOptions,732	id: ParaId,733	hwbench: Option<sc_sysinfo::HwBench>,734) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>735where736	Runtime: RuntimeInstance + Send + Sync + 'static,737	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,738	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,739	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>740		+ Send741		+ Sync742		+ 'static,743	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>744		+ fp_rpc::EthereumRuntimeRPCApi<Block>745		+ fp_rpc::ConvertTransactionRuntimeApi<Block>746		+ sp_session::SessionKeys<Block>747		+ sp_block_builder::BlockBuilder<Block>748		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>749		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>750		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>751		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>752		+ up_pov_estimate_rpc::PovEstimateApi<Block>753		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>754		+ sp_api::Metadata<Block>755		+ sp_offchain::OffchainWorkerApi<Block>756		+ cumulus_primitives_core::CollectCollationInfo<Block>757		+ sp_consensus_aura::AuraApi<Block, AuraId>,758	ExecutorDispatch: NativeExecutionDispatch + 'static,759{760	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(761		parachain_config,762		polkadot_config,763		collator_options,764		id,765		parachain_build_import_queue,766		|client,767		 backend,768		 prometheus_registry,769		 telemetry,770		 task_manager,771		 relay_chain_interface,772		 transaction_pool,773		 sync_oracle,774		 keystore,775		 force_authoring| {776			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;777778			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(779				task_manager.spawn_handle(),780				client.clone(),781				transaction_pool,782				prometheus_registry,783				telemetry.clone(),784			);785786			let block_import = ParachainBlockImport::new(client.clone(), backend);787788			Ok(AuraConsensus::build::<789				sp_consensus_aura::sr25519::AuthorityPair,790				_,791				_,792				_,793				_,794				_,795				_,796			>(BuildAuraConsensusParams {797				proposer_factory,798				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {799					let relay_chain_interface = relay_chain_interface.clone();800					async move {801						let parachain_inherent =802						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(803							relay_parent,804							&relay_chain_interface,805							&validation_data,806							id,807						).await;808809						let time = sp_timestamp::InherentDataProvider::from_system_time();810811						let slot =812						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(813							*time,814							slot_duration,815						);816817						let parachain_inherent = parachain_inherent.ok_or_else(|| {818							Box::<dyn std::error::Error + Send + Sync>::from(819								"Failed to create parachain inherent",820							)821						})?;822						Ok((slot, time, parachain_inherent))823					}824				},825				block_import,826				para_client: client,827				backoff_authoring_blocks: Option::<()>::None,828				sync_oracle,829				keystore,830				force_authoring,831				slot_duration,832				// We got around 500ms for proposing833				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),834				telemetry,835				max_block_proposal_slot_portion: None,836			}))837		},838		hwbench,839	)840	.await841}842843fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(844	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,845	_: Arc<FullBackend>,846	config: &Configuration,847	_: Option<TelemetryHandle>,848	task_manager: &TaskManager,849) -> Result<850	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,851	sc_service::Error,852>853where854	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>855		+ Send856		+ Sync857		+ 'static,858	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>859		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,860	ExecutorDispatch: NativeExecutionDispatch + 'static,861{862	Ok(sc_consensus_manual_seal::import_queue(863		Box::new(client),864		&task_manager.spawn_essential_handle(),865		config.prometheus_registry(),866	))867}868869/// Builds a new development service. This service uses instant seal, and mocks870/// the parachain inherent871pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(872	config: Configuration,873	autoseal_interval: Duration,874) -> sc_service::error::Result<TaskManager>875where876	Runtime: RuntimeInstance + Send + Sync + 'static,877	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,878	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,879	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>880		+ Send881		+ Sync882		+ 'static,883	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>884		+ fp_rpc::EthereumRuntimeRPCApi<Block>885		+ fp_rpc::ConvertTransactionRuntimeApi<Block>886		+ sp_session::SessionKeys<Block>887		+ sp_block_builder::BlockBuilder<Block>888		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>889		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>890		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>891		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>892		+ up_pov_estimate_rpc::PovEstimateApi<Block>893		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>894		+ sp_api::Metadata<Block>895		+ sp_offchain::OffchainWorkerApi<Block>896		+ cumulus_primitives_core::CollectCollationInfo<Block>897		+ sp_consensus_aura::AuraApi<Block, AuraId>,898	ExecutorDispatch: NativeExecutionDispatch + 'static,899{900	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};901	use fc_consensus::FrontierBlockImport;902	use sc_client_api::HeaderBackend;903904	let sc_service::PartialComponents {905		client,906		backend,907		mut task_manager,908		import_queue,909		keystore_container,910		select_chain: maybe_select_chain,911		transaction_pool,912		other:913			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),914	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(915		&config,916		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,917	)?;918	let net_config = sc_network::config::FullNetworkConfiguration::new(&config.network);919	let prometheus_registry = config.prometheus_registry().cloned();920921	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(922		task_manager.spawn_handle(),923		overrides_handle::<_, _, Runtime>(client.clone()),924		50,925		50,926		prometheus_registry.clone(),927	));928929	let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<930		fc_mapping_sync::EthereumBlockNotification<Block>,931	> = Default::default();932	let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);933934	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =935		sc_service::build_network(sc_service::BuildNetworkParams {936			config: &config,937			net_config,938			client: client.clone(),939			transaction_pool: transaction_pool.clone(),940			spawn_handle: task_manager.spawn_handle(),941			import_queue,942			block_announce_validator_builder: None,943			warp_sync_params: None,944		})?;945946	if config.offchain_worker.enabled {947		sc_service::build_offchain_workers(948			&config,949			task_manager.spawn_handle(),950			client.clone(),951			network.clone(),952		);953	}954955	let collator = config.role.is_authority();956957	let select_chain = maybe_select_chain;958959	if collator {960		let block_import = FrontierBlockImport::new(client.clone(), client.clone());961962		let env = sc_basic_authorship::ProposerFactory::new(963			task_manager.spawn_handle(),964			client.clone(),965			transaction_pool.clone(),966			prometheus_registry.as_ref(),967			telemetry.as_ref().map(|x| x.handle()),968		);969970		let transactions_commands_stream: Box<971			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,972		> = Box::new(973			transaction_pool974				.pool()975				.validated_pool()976				.import_notification_stream()977				.map(|_| EngineCommand::SealNewBlock {978					create_empty: true,979					finalize: false, // todo:collator finalize true980					parent_hash: None,981					sender: None,982				}),983		);984985		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));986		let idle_commands_stream: Box<987			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,988		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {989			create_empty: true,990			finalize: false, // todo:collator finalize true991			parent_hash: None,992			sender: None,993		}));994995		let commands_stream = select(transactions_commands_stream, idle_commands_stream);996997		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;998		let client_set_aside_for_cidp = client.clone();9991000		task_manager.spawn_essential_handle().spawn_blocking(1001			"authorship_task",1002			Some("block-authoring"),1003			run_manual_seal(ManualSealParams {1004				block_import,1005				env,1006				client: client.clone(),1007				pool: transaction_pool.clone(),1008				commands_stream,1009				select_chain: select_chain.clone(),1010				consensus_data_provider: None,1011				create_inherent_data_providers: move |block: Hash, ()| {1012					let current_para_block = client_set_aside_for_cidp1013						.number(block)1014						.expect("Header lookup should succeed")1015						.expect("Header passed in as parent should be present in backend.");10161017					let client_for_xcm = client_set_aside_for_cidp.clone();1018					async move {1019						let time = sp_timestamp::InherentDataProvider::from_system_time();10201021						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {1022							current_para_block,1023							relay_offset: 1000,1024							relay_blocks_per_para_block: 2,1025							para_blocks_per_relay_epoch: 0,1026							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(1027								&*client_for_xcm,1028								block,1029								Default::default(),1030								Default::default(),1031							),1032							relay_randomness_config: (),1033							raw_downward_messages: vec![],1034							raw_horizontal_messages: vec![],1035						};10361037						let slot =1038						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(1039							*time,1040							slot_duration,1041						);10421043						Ok((time, slot, mocked_parachain))1044					}1045				},1046			}),1047		);1048	}10491050	task_manager.spawn_essential_handle().spawn(1051		"frontier-mapping-sync-worker",1052		Some("block-authoring"),1053		MappingSyncWorker::new(1054			client.import_notification_stream(),1055			Duration::new(6, 0),1056			client.clone(),1057			backend.clone(),1058			overrides_handle::<_, _, Runtime>(client.clone()),1059			frontier_backend.clone(),1060			3,1061			0,1062			SyncStrategy::Normal,1063			sync_service.clone(),1064			pubsub_notification_sinks.clone(),1065		)1066		.for_each(|()| futures::future::ready(())),1067	);10681069	#[cfg(feature = "pov-estimate")]1070	let rpc_backend = backend.clone();10711072	let runtime_id = config.chain_spec.runtime_id();10731074	let rpc_builder = Box::new({1075		clone!(1076			backend,1077			client,1078			sync_service,1079			frontier_backend,1080			network,1081			transaction_pool,1082			pubsub_notification_sinks1083		);1084		move |deny_unsafe, subscription_executor| {1085			clone!(1086				backend,1087				block_data_cache,1088				client,1089				fee_history_cache,1090				filter_pool,1091				network,1092				pubsub_notification_sinks,1093			);10941095			#[cfg(not(feature = "pov-estimate"))]1096			let _ = backend;10971098			let full_deps = unique_rpc::FullDeps {1099				runtime_id: runtime_id.clone(),11001101				#[cfg(feature = "pov-estimate")]1102				exec_params: uc_rpc::pov_estimate::ExecutorParams {1103					wasm_method: config.wasm_method,1104					default_heap_pages: config.default_heap_pages,1105					max_runtime_instances: config.max_runtime_instances,1106					runtime_cache_size: config.runtime_cache_size,1107				},11081109				#[cfg(feature = "pov-estimate")]1110				backend,1111				eth_backend: frontier_backend.clone(),1112				deny_unsafe,1113				client,1114				pool: transaction_pool.clone(),1115				graph: transaction_pool.pool().clone(),1116				// TODO: Unhardcode1117				enable_dev_signer: false,1118				filter_pool,1119				network,1120				sync: sync_service.clone(),1121				select_chain: select_chain.clone(),1122				is_authority: collator,1123				// TODO: Unhardcode1124				max_past_logs: 10000,1125				block_data_cache,1126				fee_history_cache,1127				// TODO: Unhardcode1128				fee_history_limit: 2048,1129				pubsub_notification_sinks,1130			};11311132			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1133				full_deps,1134				subscription_executor,1135			)1136			.map_err(Into::into)1137		}1138	});11391140	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1141		network,1142		sync_service,1143		client,1144		keystore: keystore_container.keystore(),1145		task_manager: &mut task_manager,1146		transaction_pool,1147		rpc_builder,1148		backend,1149		system_rpc_tx,1150		config,1151		telemetry: None,1152		tx_handler_controller,1153	})?;11541155	network_starter.start_network();1156	Ok(task_manager)1157}
after · node/cli/src/service.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// std18use std::sync::Arc;19use std::sync::Mutex;20use std::collections::BTreeMap;21use std::time::Duration;22use std::pin::Pin;23use fc_mapping_sync::EthereumBlockNotificationSinks;24use fc_rpc::EthBlockDataCacheTask;25use fc_rpc::EthTask;26use fc_rpc_core::types::FeeHistoryCache;27use futures::{28	Stream, StreamExt,29	stream::select,30	task::{Context, Poll},31};32use sc_rpc::SubscriptionTaskExecutor;33use sp_keystore::KeystorePtr;34use tokio::time::Interval;35use jsonrpsee::RpcModule;3637use serde::{Serialize, Deserialize};3839// Cumulus Imports40use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};41use cumulus_client_consensus_common::{42	ParachainConsensus, ParachainBlockImport as TParachainBlockImport,43};44use cumulus_client_service::{45	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,46};47use cumulus_client_cli::CollatorOptions;48use cumulus_client_network::BlockAnnounceValidator;49use cumulus_primitives_core::ParaId;50use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;51use cumulus_relay_chain_interface::{RelayChainInterface, RelayChainResult};52use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;5354// Substrate Imports55use sp_api::{BlockT, HeaderT, ProvideRuntimeApi, StateBackend};56use sc_executor::NativeElseWasmExecutor;57use sc_executor::NativeExecutionDispatch;58use sc_network::NetworkBlock;59use sc_network_sync::SyncingService;60use sc_service::{Configuration, PartialComponents, TaskManager};61use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};62use sp_runtime::traits::BlakeTwo256;63use substrate_prometheus_endpoint::Registry;64use sc_client_api::{BlockchainEvents, BlockOf, Backend, AuxStore, StorageProvider};65use sp_blockchain::{HeaderBackend, HeaderMetadata, Error as BlockChainError};66use sc_consensus::ImportQueue;67use sp_core::H256;68use sp_block_builder::BlockBuilder;6970use polkadot_service::CollatorPair;7172// Frontier Imports73use fc_rpc_core::types::FilterPool;74use fc_mapping_sync::{kv::MappingSyncWorker, SyncStrategy};75use fc_rpc::{76	StorageOverride, OverrideHandle, SchemaV1Override, SchemaV2Override, SchemaV3Override,77	RuntimeApiStorageOverride,78};79use fp_rpc::EthereumRuntimeRPCApi;80use fp_storage::EthereumStorageSchema;8182use up_common::types::opaque::*;8384use crate::chain_spec::RuntimeIdentification;8586/// Unique native executor instance.87#[cfg(feature = "unique-runtime")]88pub struct UniqueRuntimeExecutor;8990#[cfg(feature = "quartz-runtime")]91/// Quartz native executor instance.92pub struct QuartzRuntimeExecutor;9394/// Opal native executor instance.95pub struct OpalRuntimeExecutor;9697#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]98pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;99100#[cfg(all(101	not(feature = "unique-runtime"),102	feature = "quartz-runtime",103	feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;106107#[cfg(all(108	not(feature = "unique-runtime"),109	not(feature = "quartz-runtime"),110	feature = "runtime-benchmarks"111))]112pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;113114#[cfg(feature = "unique-runtime")]115impl NativeExecutionDispatch for UniqueRuntimeExecutor {116	/// Only enable the benchmarking host functions when we actually want to benchmark.117	#[cfg(feature = "runtime-benchmarks")]118	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;119	/// Otherwise we only use the default Substrate host functions.120	#[cfg(not(feature = "runtime-benchmarks"))]121	type ExtendHostFunctions = ();122123	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {124		unique_runtime::api::dispatch(method, data)125	}126127	fn native_version() -> sc_executor::NativeVersion {128		unique_runtime::native_version()129	}130}131132#[cfg(feature = "quartz-runtime")]133impl NativeExecutionDispatch for QuartzRuntimeExecutor {134	/// Only enable the benchmarking host functions when we actually want to benchmark.135	#[cfg(feature = "runtime-benchmarks")]136	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;137	/// Otherwise we only use the default Substrate host functions.138	#[cfg(not(feature = "runtime-benchmarks"))]139	type ExtendHostFunctions = ();140141	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {142		quartz_runtime::api::dispatch(method, data)143	}144145	fn native_version() -> sc_executor::NativeVersion {146		quartz_runtime::native_version()147	}148}149150impl NativeExecutionDispatch for OpalRuntimeExecutor {151	/// Only enable the benchmarking host functions when we actually want to benchmark.152	#[cfg(feature = "runtime-benchmarks")]153	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;154	/// Otherwise we only use the default Substrate host functions.155	#[cfg(not(feature = "runtime-benchmarks"))]156	type ExtendHostFunctions = ();157158	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {159		opal_runtime::api::dispatch(method, data)160	}161162	fn native_version() -> sc_executor::NativeVersion {163		opal_runtime::native_version()164	}165}166167pub struct AutosealInterval {168	interval: Interval,169}170171impl AutosealInterval {172	pub fn new(config: &Configuration, interval: Duration) -> Self {173		let _tokio_runtime = config.tokio_handle.enter();174		let interval = tokio::time::interval(interval);175176		Self { interval }177	}178}179180impl Stream for AutosealInterval {181	type Item = tokio::time::Instant;182183	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {184		self.interval.poll_tick(cx).map(Some)185	}186}187188pub fn open_frontier_backend<Block: BlockT, C: HeaderBackend<Block>>(189	client: Arc<C>,190	config: &Configuration,191) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {192	let config_dir = config.base_path.config_dir(config.chain_spec.id());193	let database_dir = config_dir.join("frontier").join("db");194195	Ok(Arc::new(fc_db::kv::Backend::<Block>::new(196		client,197		&fc_db::kv::DatabaseSettings {198			source: fc_db::DatabaseSource::RocksDb {199				path: database_dir,200				cache_size: 0,201			},202		},203	)?))204}205206type FullClient<RuntimeApi, ExecutorDispatch> =207	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;208type FullBackend = sc_service::TFullBackend<Block>;209type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;210type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =211	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;212213/// Starts a `ServiceBuilder` for a full service.214///215/// Use this macro if you don't actually need the full service, but just the builder in order to216/// be able to perform chain operations.217#[allow(clippy::type_complexity)]218pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(219	config: &Configuration,220	build_import_queue: BIQ,221) -> Result<222	PartialComponents<223		FullClient<RuntimeApi, ExecutorDispatch>,224		FullBackend,225		FullSelectChain,226		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,227		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,228		OtherPartial,229	>,230	sc_service::Error,231>232where233	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,234	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>235		+ Send236		+ Sync237		+ 'static,238	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,239	ExecutorDispatch: NativeExecutionDispatch + 'static,240	BIQ: FnOnce(241		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,242		Arc<FullBackend>,243		&Configuration,244		Option<TelemetryHandle>,245		&TaskManager,246	) -> Result<247		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,248		sc_service::Error,249	>,250{251	let telemetry = config252		.telemetry_endpoints253		.clone()254		.filter(|x| !x.is_empty())255		.map(|endpoints| -> Result<_, sc_telemetry::Error> {256			let worker = TelemetryWorker::new(16)?;257			let telemetry = worker.handle().new_telemetry(endpoints);258			Ok((worker, telemetry))259		})260		.transpose()?;261262	let executor = sc_service::new_native_or_wasm_executor(config);263264	let (client, backend, keystore_container, task_manager) =265		sc_service::new_full_parts::<Block, RuntimeApi, _>(266			config,267			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),268			executor,269		)?;270	let client = Arc::new(client);271272	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());273274	let telemetry = telemetry.map(|(worker, telemetry)| {275		task_manager276			.spawn_handle()277			.spawn("telemetry", None, worker.run());278		telemetry279	});280281	let select_chain = sc_consensus::LongestChain::new(backend.clone());282283	let transaction_pool = sc_transaction_pool::BasicPool::new_full(284		config.transaction_pool.clone(),285		config.role.is_authority().into(),286		config.prometheus_registry(),287		task_manager.spawn_essential_handle(),288		client.clone(),289	);290291	let eth_filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));292293	let eth_backend = open_frontier_backend(client.clone(), config)?;294295	let import_queue = build_import_queue(296		client.clone(),297		backend.clone(),298		config,299		telemetry.as_ref().map(|telemetry| telemetry.handle()),300		&task_manager,301	)?;302303	let params = PartialComponents {304		backend,305		client,306		import_queue,307		keystore_container,308		task_manager,309		transaction_pool,310		select_chain,311		other: OtherPartial {312			telemetry,313			eth_filter_pool,314			eth_backend,315			telemetry_worker_handle,316		},317	};318319	Ok(params)320}321322async fn build_relay_chain_interface(323	polkadot_config: Configuration,324	parachain_config: &Configuration,325	telemetry_worker_handle: Option<TelemetryWorkerHandle>,326	task_manager: &mut TaskManager,327	collator_options: CollatorOptions,328	hwbench: Option<sc_sysinfo::HwBench>,329) -> RelayChainResult<(330	Arc<(dyn RelayChainInterface + 'static)>,331	Option<CollatorPair>,332)> {333	if collator_options.relay_chain_rpc_urls.is_empty() {334		build_inprocess_relay_chain(335			polkadot_config,336			parachain_config,337			telemetry_worker_handle,338			task_manager,339			hwbench,340		)341	} else {342		build_minimal_relay_chain_node(343			polkadot_config,344			task_manager,345			collator_options.relay_chain_rpc_urls,346		)347		.await348	}349}350351macro_rules! clone {352    ($($i:ident),* $(,)?) => {353		$(354			let $i = $i.clone();355		)*356    };357}358359/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.360///361/// This is the actual implementation that is abstract over the executor and the runtime api.362#[sc_tracing::logging::prefix_logs_with("Parachain")]363async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(364	parachain_config: Configuration,365	polkadot_config: Configuration,366	collator_options: CollatorOptions,367	id: ParaId,368	build_import_queue: BIQ,369	build_consensus: BIC,370	hwbench: Option<sc_sysinfo::HwBench>,371) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>372where373	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,374	Runtime: RuntimeInstance + Send + Sync + 'static,375	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,376	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,377	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>378		+ Send379		+ Sync380		+ 'static,381	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>382		+ fp_rpc::EthereumRuntimeRPCApi<Block>383		+ fp_rpc::ConvertTransactionRuntimeApi<Block>384		+ sp_session::SessionKeys<Block>385		+ sp_block_builder::BlockBuilder<Block>386		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>387		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>388		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>389		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>390		+ up_pov_estimate_rpc::PovEstimateApi<Block>391		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>392		+ sp_api::Metadata<Block>393		+ sp_offchain::OffchainWorkerApi<Block>394		+ cumulus_primitives_core::CollectCollationInfo<Block>,395	ExecutorDispatch: NativeExecutionDispatch + 'static,396	BIQ: FnOnce(397		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,398		Arc<FullBackend>,399		&Configuration,400		Option<TelemetryHandle>,401		&TaskManager,402	) -> Result<403		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,404		sc_service::Error,405	>,406	BIC: FnOnce(407		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,408		Arc<FullBackend>,409		Option<&Registry>,410		Option<TelemetryHandle>,411		&TaskManager,412		Arc<dyn RelayChainInterface>,413		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,414		Arc<SyncingService<Block>>,415		KeystorePtr,416		bool,417	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,418{419	let parachain_config = prepare_node_config(parachain_config);420421	let params =422		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;423	let OtherPartial {424		mut telemetry,425		telemetry_worker_handle,426		eth_filter_pool,427		eth_backend,428	} = params.other;429	let net_config = sc_network::config::FullNetworkConfiguration::new(&parachain_config.network);430431	let client = params.client.clone();432	let backend = params.backend.clone();433	let mut task_manager = params.task_manager;434435	let (relay_chain_interface, collator_key) = build_relay_chain_interface(436		polkadot_config,437		&parachain_config,438		telemetry_worker_handle,439		&mut task_manager,440		collator_options.clone(),441		hwbench.clone(),442	)443	.await444	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;445446	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);447448	let force_authoring = parachain_config.force_authoring;449	let validator = parachain_config.role.is_authority();450	let prometheus_registry = parachain_config.prometheus_registry().cloned();451	let transaction_pool = params.transaction_pool.clone();452	let import_queue_service = params.import_queue.service();453454	let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =455		sc_service::build_network(sc_service::BuildNetworkParams {456			config: &parachain_config,457			net_config,458			client: client.clone(),459			transaction_pool: transaction_pool.clone(),460			spawn_handle: task_manager.spawn_handle(),461			import_queue: params.import_queue,462			block_announce_validator_builder: Some(Box::new(|_| {463				Box::new(block_announce_validator)464			})),465			warp_sync_params: None,466		})?;467468	let select_chain = params.select_chain.clone();469470	let runtime_id = parachain_config.chain_spec.runtime_id();471472	// Frontier473	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));474	let fee_history_limit = 2048;475476	let eth_pubsub_notification_sinks: Arc<477		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,478	> = Default::default();479480	let overrides = overrides_handle(client.clone());481	let eth_block_data_cache = spawn_frontier_tasks(482		FrontierTaskParams {483			client: client.clone(),484			substrate_backend: backend.clone(),485			eth_filter_pool: eth_filter_pool.clone(),486			eth_backend: eth_backend.clone(),487			fee_history_limit,488			fee_history_cache: fee_history_cache.clone(),489			task_manager: &task_manager,490			prometheus_registry: prometheus_registry.clone(),491			overrides: overrides.clone(),492			sync_strategy: SyncStrategy::Parachain,493		},494		sync_service.clone(),495		eth_pubsub_notification_sinks.clone(),496	);497498	// Rpc499	let rpc_builder = Box::new({500		clone!(501			client,502			backend,503			eth_backend,504			eth_pubsub_notification_sinks,505			fee_history_cache,506			eth_block_data_cache,507			overrides,508			transaction_pool,509			network,510			sync_service,511		);512		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {513			clone!(514				backend,515				eth_block_data_cache,516				client,517				eth_backend,518				eth_filter_pool,519				eth_pubsub_notification_sinks,520				fee_history_cache,521				eth_block_data_cache,522				network,523				runtime_id,524				transaction_pool,525				select_chain,526				overrides,527			);528529			#[cfg(not(feature = "pov-estimate"))]530			let _ = backend;531532			let mut rpc_handle = RpcModule::new(());533534			let full_deps = unique_rpc::FullDeps {535				client: client.clone(),536				runtime_id,537538				#[cfg(feature = "pov-estimate")]539				exec_params: uc_rpc::pov_estimate::ExecutorParams {540					wasm_method: parachain_config.wasm_method,541					default_heap_pages: parachain_config.default_heap_pages,542					max_runtime_instances: parachain_config.max_runtime_instances,543					runtime_cache_size: parachain_config.runtime_cache_size,544				},545546				#[cfg(feature = "pov-estimate")]547				backend,548549				deny_unsafe,550				pool: transaction_pool.clone(),551				select_chain,552			};553554			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;555556			let eth_deps = unique_rpc::EthDeps {557				client,558				graph: transaction_pool.pool().clone(),559				pool: transaction_pool,560				is_authority: validator,561				network,562				eth_backend,563				// TODO: Unhardcode564				max_past_logs: 10000,565				fee_history_limit,566				fee_history_cache,567				eth_block_data_cache,568				// TODO: Unhardcode569				enable_dev_signer: false,570				eth_filter_pool,571				eth_pubsub_notification_sinks,572				overrides,573				sync: sync_service.clone(),574			};575576			unique_rpc::create_eth(577				&mut rpc_handle,578				eth_deps,579				subscription_task_executor.clone(),580			)?;581582			Ok(rpc_handle)583		}584	});585586	sc_service::spawn_tasks(sc_service::SpawnTasksParams {587		rpc_builder,588		client: client.clone(),589		transaction_pool: transaction_pool.clone(),590		task_manager: &mut task_manager,591		config: parachain_config,592		keystore: params.keystore_container.keystore(),593		backend: backend.clone(),594		network: network.clone(),595		sync_service: sync_service.clone(),596		system_rpc_tx,597		telemetry: telemetry.as_mut(),598		tx_handler_controller,599	})?;600601	if let Some(hwbench) = hwbench {602		sc_sysinfo::print_hwbench(&hwbench);603604		if let Some(ref mut telemetry) = telemetry {605			let telemetry_handle = telemetry.handle();606			task_manager.spawn_handle().spawn(607				"telemetry_hwbench",608				None,609				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),610			);611		}612	}613614	let announce_block = {615		let sync_service = sync_service.clone();616		Arc::new(Box::new(move |hash, data| {617			sync_service.announce_block(hash, data)618		}))619	};620621	let relay_chain_slot_duration = Duration::from_secs(6);622623	let overseer_handle = relay_chain_interface624		.overseer_handle()625		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;626627	if validator {628		let parachain_consensus = build_consensus(629			client.clone(),630			backend.clone(),631			prometheus_registry.as_ref(),632			telemetry.as_ref().map(|t| t.handle()),633			&task_manager,634			relay_chain_interface.clone(),635			transaction_pool,636			sync_service.clone(),637			params.keystore_container.keystore(),638			force_authoring,639		)?;640641		let spawner = task_manager.spawn_handle();642643		let params = StartCollatorParams {644			para_id: id,645			block_status: client.clone(),646			announce_block,647			client: client.clone(),648			task_manager: &mut task_manager,649			spawner,650			parachain_consensus,651			import_queue: import_queue_service,652			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),653			relay_chain_interface,654			relay_chain_slot_duration,655			recovery_handle: Box::new(overseer_handle),656			sync_service,657		};658659		start_collator(params).await?;660	} else {661		let params = StartFullNodeParams {662			client: client.clone(),663			announce_block,664			task_manager: &mut task_manager,665			para_id: id,666			import_queue: import_queue_service,667			relay_chain_interface,668			relay_chain_slot_duration,669			recovery_handle: Box::new(overseer_handle),670			sync_service,671		};672673		start_full_node(params)?;674	}675676	start_network.start_network();677678	Ok((task_manager, client))679}680681/// Build the import queue for the the parachain runtime.682pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(683	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,684	backend: Arc<FullBackend>,685	config: &Configuration,686	telemetry: Option<TelemetryHandle>,687	task_manager: &TaskManager,688) -> Result<689	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,690	sc_service::Error,691>692where693	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>694		+ Send695		+ Sync696		+ 'static,697	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>698		+ sp_block_builder::BlockBuilder<Block>699		+ sp_consensus_aura::AuraApi<Block, AuraId>700		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,701	ExecutorDispatch: NativeExecutionDispatch + 'static,702{703	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;704705	let block_import = ParachainBlockImport::new(client.clone(), backend);706707	cumulus_client_consensus_aura::import_queue::<708		sp_consensus_aura::sr25519::AuthorityPair,709		_,710		_,711		_,712		_,713		_,714	>(cumulus_client_consensus_aura::ImportQueueParams {715		block_import,716		client,717		create_inherent_data_providers: move |_, _| async move {718			let time = sp_timestamp::InherentDataProvider::from_system_time();719720			let slot =721				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(722					*time,723					slot_duration,724				);725726			Ok((slot, time))727		},728		registry: config.prometheus_registry(),729		spawner: &task_manager.spawn_essential_handle(),730		telemetry,731	})732	.map_err(Into::into)733}734735/// Start a normal parachain node.736pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(737	parachain_config: Configuration,738	polkadot_config: Configuration,739	collator_options: CollatorOptions,740	id: ParaId,741	hwbench: Option<sc_sysinfo::HwBench>,742) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>743where744	Runtime: RuntimeInstance + Send + Sync + 'static,745	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,746	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,747	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>748		+ Send749		+ Sync750		+ 'static,751	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>752		+ fp_rpc::EthereumRuntimeRPCApi<Block>753		+ fp_rpc::ConvertTransactionRuntimeApi<Block>754		+ sp_session::SessionKeys<Block>755		+ sp_block_builder::BlockBuilder<Block>756		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>757		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>758		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>759		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>760		+ up_pov_estimate_rpc::PovEstimateApi<Block>761		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>762		+ sp_api::Metadata<Block>763		+ sp_offchain::OffchainWorkerApi<Block>764		+ cumulus_primitives_core::CollectCollationInfo<Block>765		+ sp_consensus_aura::AuraApi<Block, AuraId>,766	ExecutorDispatch: NativeExecutionDispatch + 'static,767{768	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(769		parachain_config,770		polkadot_config,771		collator_options,772		id,773		parachain_build_import_queue,774		|client,775		 backend,776		 prometheus_registry,777		 telemetry,778		 task_manager,779		 relay_chain_interface,780		 transaction_pool,781		 sync_oracle,782		 keystore,783		 force_authoring| {784			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;785786			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(787				task_manager.spawn_handle(),788				client.clone(),789				transaction_pool,790				prometheus_registry,791				telemetry.clone(),792			);793794			let block_import = ParachainBlockImport::new(client.clone(), backend);795796			Ok(AuraConsensus::build::<797				sp_consensus_aura::sr25519::AuthorityPair,798				_,799				_,800				_,801				_,802				_,803				_,804			>(BuildAuraConsensusParams {805				proposer_factory,806				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {807					let relay_chain_interface = relay_chain_interface.clone();808					async move {809						let parachain_inherent =810						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(811							relay_parent,812							&relay_chain_interface,813							&validation_data,814							id,815						).await;816817						let time = sp_timestamp::InherentDataProvider::from_system_time();818819						let slot =820						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(821							*time,822							slot_duration,823						);824825						let parachain_inherent = parachain_inherent.ok_or_else(|| {826							Box::<dyn std::error::Error + Send + Sync>::from(827								"Failed to create parachain inherent",828							)829						})?;830						Ok((slot, time, parachain_inherent))831					}832				},833				block_import,834				para_client: client,835				backoff_authoring_blocks: Option::<()>::None,836				sync_oracle,837				keystore,838				force_authoring,839				slot_duration,840				// We got around 500ms for proposing841				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),842				telemetry,843				max_block_proposal_slot_portion: None,844			}))845		},846		hwbench,847	)848	.await849}850851fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(852	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,853	_: Arc<FullBackend>,854	config: &Configuration,855	_: Option<TelemetryHandle>,856	task_manager: &TaskManager,857) -> Result<858	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,859	sc_service::Error,860>861where862	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>863		+ Send864		+ Sync865		+ 'static,866	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>867		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,868	ExecutorDispatch: NativeExecutionDispatch + 'static,869{870	Ok(sc_consensus_manual_seal::import_queue(871		Box::new(client),872		&task_manager.spawn_essential_handle(),873		config.prometheus_registry(),874	))875}876877pub struct OtherPartial {878	pub telemetry: Option<Telemetry>,879	pub telemetry_worker_handle: Option<TelemetryWorkerHandle>,880	pub eth_filter_pool: Option<FilterPool>,881	pub eth_backend: Arc<fc_db::kv::Backend<Block>>,882}883884/// Builds a new development service. This service uses instant seal, and mocks885/// the parachain inherent886pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(887	config: Configuration,888	autoseal_interval: Duration,889) -> sc_service::error::Result<TaskManager>890where891	Runtime: RuntimeInstance + Send + Sync + 'static,892	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,893	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,894	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>895		+ Send896		+ Sync897		+ 'static,898	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>899		+ fp_rpc::EthereumRuntimeRPCApi<Block>900		+ fp_rpc::ConvertTransactionRuntimeApi<Block>901		+ sp_session::SessionKeys<Block>902		+ sp_block_builder::BlockBuilder<Block>903		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>904		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>905		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>906		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>907		+ up_pov_estimate_rpc::PovEstimateApi<Block>908		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>909		+ sp_api::Metadata<Block>910		+ sp_offchain::OffchainWorkerApi<Block>911		+ cumulus_primitives_core::CollectCollationInfo<Block>912		+ sp_consensus_aura::AuraApi<Block, AuraId>,913	ExecutorDispatch: NativeExecutionDispatch + 'static,914{915	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};916	use fc_consensus::FrontierBlockImport;917918	let sc_service::PartialComponents {919		client,920		backend,921		mut task_manager,922		import_queue,923		keystore_container,924		select_chain: maybe_select_chain,925		transaction_pool,926		other:927			OtherPartial {928				telemetry,929				eth_filter_pool,930				eth_backend,931				telemetry_worker_handle: _,932			},933	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(934		&config,935		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,936	)?;937	let net_config = sc_network::config::FullNetworkConfiguration::new(&config.network);938	let prometheus_registry = config.prometheus_registry().cloned();939940	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =941		sc_service::build_network(sc_service::BuildNetworkParams {942			config: &config,943			net_config,944			client: client.clone(),945			transaction_pool: transaction_pool.clone(),946			spawn_handle: task_manager.spawn_handle(),947			import_queue,948			block_announce_validator_builder: None,949			warp_sync_params: None,950		})?;951952	if config.offchain_worker.enabled {953		sc_service::build_offchain_workers(954			&config,955			task_manager.spawn_handle(),956			client.clone(),957			network.clone(),958		);959	}960961	let collator = config.role.is_authority();962963	let select_chain = maybe_select_chain;964965	if collator {966		let block_import = FrontierBlockImport::new(client.clone(), client.clone());967968		let env = sc_basic_authorship::ProposerFactory::new(969			task_manager.spawn_handle(),970			client.clone(),971			transaction_pool.clone(),972			prometheus_registry.as_ref(),973			telemetry.as_ref().map(|x| x.handle()),974		);975976		let transactions_commands_stream: Box<977			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,978		> = Box::new(979			transaction_pool980				.pool()981				.validated_pool()982				.import_notification_stream()983				.map(|_| EngineCommand::SealNewBlock {984					create_empty: true,985					finalize: false, // todo:collator finalize true986					parent_hash: None,987					sender: None,988				}),989		);990991		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));992		let idle_commands_stream: Box<993			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,994		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {995			create_empty: true,996			finalize: false, // todo:collator finalize true997			parent_hash: None,998			sender: None,999		}));10001001		let commands_stream = select(transactions_commands_stream, idle_commands_stream);10021003		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;1004		let client_set_aside_for_cidp = client.clone();10051006		task_manager.spawn_essential_handle().spawn_blocking(1007			"authorship_task",1008			Some("block-authoring"),1009			run_manual_seal(ManualSealParams {1010				block_import,1011				env,1012				client: client.clone(),1013				pool: transaction_pool.clone(),1014				commands_stream,1015				select_chain: select_chain.clone(),1016				consensus_data_provider: None,1017				create_inherent_data_providers: move |block: Hash, ()| {1018					let current_para_block = client_set_aside_for_cidp1019						.number(block)1020						.expect("Header lookup should succeed")1021						.expect("Header passed in as parent should be present in backend.");10221023					let client_for_xcm = client_set_aside_for_cidp.clone();1024					async move {1025						let time = sp_timestamp::InherentDataProvider::from_system_time();10261027						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {1028							current_para_block,1029							relay_offset: 1000,1030							relay_blocks_per_para_block: 2,1031							para_blocks_per_relay_epoch: 0,1032							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(1033								&*client_for_xcm,1034								block,1035								Default::default(),1036								Default::default(),1037							),1038							relay_randomness_config: (),1039							raw_downward_messages: vec![],1040							raw_horizontal_messages: vec![],1041						};10421043						let slot =1044						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(1045							*time,1046							slot_duration,1047						);10481049						Ok((time, slot, mocked_parachain))1050					}1051				},1052			}),1053		);1054	}10551056	#[cfg(feature = "pov-estimate")]1057	let rpc_backend = backend.clone();10581059	let runtime_id = config.chain_spec.runtime_id();10601061	// Frontier1062	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));1063	let fee_history_limit = 2048;10641065	let eth_pubsub_notification_sinks: Arc<1066		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,1067	> = Default::default();10681069	let overrides = overrides_handle(client.clone());1070	let eth_block_data_cache = spawn_frontier_tasks(1071		FrontierTaskParams {1072			client: client.clone(),1073			substrate_backend: backend.clone(),1074			eth_filter_pool: eth_filter_pool.clone(),1075			eth_backend: eth_backend.clone(),1076			fee_history_limit,1077			fee_history_cache: fee_history_cache.clone(),1078			task_manager: &task_manager,1079			prometheus_registry,1080			overrides: overrides.clone(),1081			sync_strategy: SyncStrategy::Normal,1082		},1083		sync_service.clone(),1084		eth_pubsub_notification_sinks.clone(),1085	);10861087	// Rpc1088	let rpc_builder = Box::new({1089		clone!(1090			client,1091			backend,1092			eth_backend,1093			eth_pubsub_notification_sinks,1094			fee_history_cache,1095			eth_block_data_cache,1096			overrides,1097			transaction_pool,1098			network,1099			sync_service,1100		);1101		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {1102			clone!(1103				backend,1104				eth_block_data_cache,1105				client,1106				eth_backend,1107				eth_filter_pool,1108				eth_pubsub_notification_sinks,1109				fee_history_cache,1110				eth_block_data_cache,1111				network,1112				runtime_id,1113				transaction_pool,1114				select_chain,1115				overrides,1116			);11171118			#[cfg(not(feature = "pov-estimate"))]1119			let _ = backend;11201121			let mut rpc_module = RpcModule::new(());11221123			let full_deps = unique_rpc::FullDeps {1124				runtime_id,11251126				#[cfg(feature = "pov-estimate")]1127				exec_params: uc_rpc::pov_estimate::ExecutorParams {1128					wasm_method: config.wasm_method,1129					default_heap_pages: config.default_heap_pages,1130					max_runtime_instances: config.max_runtime_instances,1131					runtime_cache_size: config.runtime_cache_size,1132				},11331134				#[cfg(feature = "pov-estimate")]1135				backend,1136				// eth_backend,1137				deny_unsafe,1138				client: client.clone(),1139				pool: transaction_pool.clone(),1140				select_chain,1141			};11421143			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;11441145			let eth_deps = unique_rpc::EthDeps {1146				client,1147				graph: transaction_pool.pool().clone(),1148				pool: transaction_pool,1149				is_authority: true,1150				network,1151				eth_backend,1152				// TODO: Unhardcode1153				max_past_logs: 10000,1154				fee_history_limit,1155				fee_history_cache,1156				eth_block_data_cache,1157				// TODO: Unhardcode1158				enable_dev_signer: false,1159				eth_filter_pool,1160				eth_pubsub_notification_sinks,1161				overrides,1162				sync: sync_service.clone(),1163			};11641165			unique_rpc::create_eth(1166				&mut rpc_module,1167				eth_deps,1168				subscription_task_executor.clone(),1169			)?;11701171			Ok(rpc_module)1172		}1173	});11741175	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1176		network,1177		sync_service,1178		client,1179		keystore: keystore_container.keystore(),1180		task_manager: &mut task_manager,1181		transaction_pool,1182		rpc_builder,1183		backend,1184		system_rpc_tx,1185		config,1186		telemetry: None,1187		tx_handler_controller,1188	})?;11891190	network_starter.start_network();1191	Ok(task_manager)1192}11931194fn overrides_handle<C, BE>(client: Arc<C>) -> Arc<OverrideHandle<Block>>1195where1196	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,1197	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,1198	C: Send + Sync + 'static,1199	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,1200	BE: Backend<Block> + 'static,1201	BE::State: StateBackend<BlakeTwo256>,1202{1203	let mut overrides_map = BTreeMap::new();1204	overrides_map.insert(1205		EthereumStorageSchema::V1,1206		Box::new(SchemaV1Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1207	);1208	overrides_map.insert(1209		EthereumStorageSchema::V2,1210		Box::new(SchemaV2Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1211	);1212	overrides_map.insert(1213		EthereumStorageSchema::V3,1214		Box::new(SchemaV3Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1215	);12161217	Arc::new(OverrideHandle {1218		schemas: overrides_map,1219		fallback: Box::new(RuntimeApiStorageOverride::new(client)),1220	})1221}12221223pub struct FrontierTaskParams<'a, B: BlockT, C, BE> {1224	pub task_manager: &'a TaskManager,1225	pub client: Arc<C>,1226	pub substrate_backend: Arc<BE>,1227	pub eth_backend: Arc<fc_db::kv::Backend<B>>,1228	pub eth_filter_pool: Option<FilterPool>,1229	pub overrides: Arc<OverrideHandle<B>>,1230	pub fee_history_limit: u64,1231	pub fee_history_cache: FeeHistoryCache,1232	pub sync_strategy: SyncStrategy,1233	pub prometheus_registry: Option<Registry>,1234}12351236pub fn spawn_frontier_tasks<B, C, BE>(1237	params: FrontierTaskParams<B, C, BE>,1238	sync: Arc<SyncingService<B>>,1239	pubsub_notification_sinks: Arc<1240		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<B>>,1241	>,1242) -> Arc<EthBlockDataCacheTask<B>>1243where1244	C: ProvideRuntimeApi<B> + BlockOf,1245	C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,1246	C: BlockchainEvents<B> + StorageProvider<B, BE>,1247	C: Send + Sync + 'static,1248	C::Api: EthereumRuntimeRPCApi<B>,1249	C::Api: BlockBuilder<B>,1250	B: BlockT<Hash = H256> + Send + Sync + 'static,1251	B::Header: HeaderT<Number = u32>,1252	BE: Backend<B> + 'static,1253	BE::State: StateBackend<BlakeTwo256>,1254{1255	let FrontierTaskParams {1256		task_manager,1257		client,1258		substrate_backend,1259		eth_backend,1260		eth_filter_pool,1261		overrides,1262		fee_history_limit,1263		fee_history_cache,1264		sync_strategy,1265		prometheus_registry,1266	} = params;1267	// Frontier offchain DB task. Essential.1268	// Maps emulated ethereum data to substrate native data.1269	params.task_manager.spawn_essential_handle().spawn(1270		"frontier-mapping-sync-worker",1271		Some("frontier"),1272		MappingSyncWorker::new(1273			client.import_notification_stream(),1274			Duration::new(6, 0),1275			client.clone(),1276			substrate_backend,1277			overrides.clone(),1278			eth_backend,1279			3,1280			0,1281			sync_strategy,1282			sync,1283			pubsub_notification_sinks,1284		)1285		.for_each(|()| futures::future::ready(())),1286	);12871288	// Frontier `EthFilterApi` maintenance.1289	// Manages the pool of user-created Filters.1290	if let Some(eth_filter_pool) = eth_filter_pool {1291		// Each filter is allowed to stay in the pool for 100 blocks.1292		const FILTER_RETAIN_THRESHOLD: u64 = 100;1293		params.task_manager.spawn_essential_handle().spawn(1294			"frontier-filter-pool",1295			Some("frontier"),1296			EthTask::filter_pool_task(client.clone(), eth_filter_pool, FILTER_RETAIN_THRESHOLD),1297		);1298	}12991300	// Spawn Frontier FeeHistory cache maintenance task.1301	params.task_manager.spawn_essential_handle().spawn(1302		"frontier-fee-history",1303		Some("frontier"),1304		EthTask::fee_history_task(1305			client,1306			overrides.clone(),1307			fee_history_cache,1308			fee_history_limit,1309		),1310	);13111312	Arc::new(EthBlockDataCacheTask::new(1313		task_manager.spawn_handle(),1314		overrides,1315		50,1316		50,1317		prometheus_registry,1318	))1319}
modifiednode/rpc/Cargo.tomldiffbeforeafterboth
--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -14,7 +14,6 @@
 # pallet-contracts-rpc = { git = 'https://github.com/paritytech/substrate', branch = 'master' }
 pallet-transaction-payment-rpc = { workspace = true }
 sc-client-api = { workspace = true }
-sc-consensus-grandpa = { workspace = true }
 sc-network = { workspace = true }
 sc-network-sync = { workspace = true }
 sc-rpc = { workspace = true }
@@ -41,6 +40,7 @@
 up-data-structs = { workspace = true }
 up-pov-estimate-rpc = { workspace = true, default-features = true }
 up-rpc = { workspace = true }
+pallet-ethereum.workspace = true
 
 [features]
 default = []
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -14,6 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
+use fc_mapping_sync::{EthereumBlockNotificationSinks, EthereumBlockNotification};
 use sp_runtime::traits::BlakeTwo256;
 use fc_rpc::{
 	EthBlockDataCacheTask, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override,
@@ -26,9 +27,6 @@
 	backend::{AuxStore, StorageProvider},
 	client::BlockchainEvents,
 	StateBackend, Backend,
-};
-use sc_consensus_grandpa::{
-	FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,
 };
 use sc_network::NetworkService;
 use sc_network_sync::SyncingService;
@@ -46,42 +44,16 @@
 #[cfg(feature = "pov-estimate")]
 type FullBackend = sc_service::TFullBackend<Block>;
 
-/// Extra dependencies for GRANDPA
-pub struct GrandpaDeps<B> {
-	/// Voting round info.
-	pub shared_voter_state: SharedVoterState,
-	/// Authority set info.
-	pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,
-	/// Receives notifications about justification events from Grandpa.
-	pub justification_stream: GrandpaJustificationStream<Block>,
-	/// Executor to drive the subscription manager in the Grandpa RPC handler.
-	pub subscription_executor: SubscriptionTaskExecutor,
-	/// Finality proof provider.
-	pub finality_provider: Arc<FinalityProofProvider<B, Block>>,
-}
-
 /// Full client dependencies.
-pub struct FullDeps<C, P, SC, CA: ChainApi> {
+pub struct FullDeps<C, P, SC> {
 	/// The client instance to use.
 	pub client: Arc<C>,
 	/// Transaction pool instance.
 	pub pool: Arc<P>,
-	/// Graph pool instance.
-	pub graph: Arc<Pool<CA>>,
 	/// The SelectChain Strategy
 	pub select_chain: SC,
-	/// The Node authority flag
-	pub is_authority: bool,
-	/// Whether to enable dev signer
-	pub enable_dev_signer: bool,
-	/// Network service
-	pub network: Arc<NetworkService<Block, Hash>>,
-	/// Syncing service
-	pub sync: Arc<SyncingService<Block>>,
 	/// Whether to deny unsafe calls
 	pub deny_unsafe: DenyUnsafe,
-	/// EthFilterApi pool.
-	pub filter_pool: Option<FilterPool>,
 
 	/// Runtime identification (read from the chain spec)
 	pub runtime_id: RuntimeId,
@@ -91,23 +63,6 @@
 	/// Substrate Backend.
 	#[cfg(feature = "pov-estimate")]
 	pub backend: Arc<FullBackend>,
-
-	/// Ethereum Backend.
-	pub eth_backend: Arc<dyn fc_db::BackendReader<Block> + Send + Sync>,
-	/// Maximum number of logs in a query.
-	pub max_past_logs: u32,
-	/// Maximum fee history cache size.
-	pub fee_history_limit: u64,
-	/// Fee history cache.
-	pub fee_history_cache: FeeHistoryCache,
-	/// Cache for Ethereum block data.
-	pub block_data_cache: Arc<EthBlockDataCacheTask<Block>>,
-
-	pub pubsub_notification_sinks: Arc<
-		fc_mapping_sync::EthereumBlockNotificationSinks<
-			fc_mapping_sync::EthereumBlockNotification<Block>,
-		>,
-	>,
 }
 
 pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>
@@ -142,10 +97,10 @@
 }
 
 /// Instantiate all Full RPC extensions.
-pub fn create_full<C, P, SC, CA, R, A, B>(
-	deps: FullDeps<C, P, SC, CA>,
-	subscription_task_executor: SubscriptionTaskExecutor,
-) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>
+pub fn create_full<C, P, SC, R, A, B>(
+	io: &mut RpcModule<()>,
+	deps: FullDeps<C, P, SC>,
+) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
 where
 	C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,
 	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
@@ -155,8 +110,6 @@
 	C::Api: BlockBuilder<Block>,
 	// C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,
 	C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
-	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
-	C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,
 	C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,
 	C::Api: app_promotion_rpc::AppPromotionApi<
 		Block,
@@ -168,7 +121,6 @@
 	B: sc_client_api::Backend<Block> + Send + Sync + 'static,
 	B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,
 	P: TransactionPool<Block = Block> + 'static,
-	CA: ChainApi<Block = Block> + 'static,
 	R: RuntimeInstance + Send + Sync + 'static,
 	<R as RuntimeInstance>::CrossAccountId: serde::Serialize,
 	C: sp_api::CallApiAt<
@@ -179,10 +131,6 @@
 	>,
 	for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,
 {
-	use fc_rpc::{
-		Eth, EthApiServer, EthDevSigner, EthFilter, EthFilterApiServer, EthPubSub,
-		EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer, TxPool, TxPoolApiServer
-	};
 	use uc_rpc::{UniqueApiServer, Unique};
 
 	use uc_rpc::{AppPromotionApiServer, AppPromotion};
@@ -194,21 +142,11 @@
 	use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
 	use substrate_frame_rpc_system::{System, SystemApiServer};
 
-	let mut io = RpcModule::new(());
 	let FullDeps {
 		client,
 		pool,
-		graph,
 		select_chain: _,
-		fee_history_limit,
-		fee_history_cache,
-		block_data_cache,
-		enable_dev_signer,
-		is_authority,
-		network,
-		sync,
 		deny_unsafe,
-		filter_pool,
 
 		runtime_id: _,
 
@@ -217,37 +155,137 @@
 
 		#[cfg(feature = "pov-estimate")]
 		backend,
-
-		eth_backend,
-		max_past_logs,
-		pubsub_notification_sinks,
 	} = deps;
 
 	io.merge(System::new(Arc::clone(&client), Arc::clone(&pool), deny_unsafe).into_rpc())?;
 	io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;
 
-	// io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));
+	io.merge(Unique::new(client.clone()).into_rpc())?;
+
+	io.merge(AppPromotion::new(client.clone()).into_rpc())?;
+
+	#[cfg(feature = "pov-estimate")]
+	io.merge(
+		PovEstimate::new(
+			client.clone(),
+			backend,
+			deny_unsafe,
+			exec_params,
+			runtime_id,
+		)
+		.into_rpc(),
+	)?;
+
+	Ok(())
+}
+
+pub struct EthDeps<C, P, CA: ChainApi> {
+	/// The client instance to use.
+	pub client: Arc<C>,
+	/// Transaction pool instance.
+	pub pool: Arc<P>,
+	/// Graph pool instance.
+	pub graph: Arc<Pool<CA>>,
+	/// Syncing service
+	pub sync: Arc<SyncingService<Block>>,
+	/// The Node authority flag
+	pub is_authority: bool,
+	/// Network service
+	pub network: Arc<NetworkService<Block, Hash>>,
+
+	/// Ethereum Backend.
+	pub eth_backend: Arc<dyn fc_db::BackendReader<Block> + Send + Sync>,
+	/// Maximum number of logs in a query.
+	pub max_past_logs: u32,
+	/// Maximum fee history cache size.
+	pub fee_history_limit: u64,
+	/// Fee history cache.
+	pub fee_history_cache: FeeHistoryCache,
+	pub eth_block_data_cache: Arc<EthBlockDataCacheTask<Block>>,
+	/// EthFilterApi pool.
+	pub eth_filter_pool: Option<FilterPool>,
+	pub eth_pubsub_notification_sinks: Arc<EthereumBlockNotificationSinks<EthereumBlockNotification<Block>>>,
+	/// Whether to enable eth dev signer
+	pub enable_dev_signer: bool,
+
+	pub overrides: Arc<OverrideHandle<Block>>,
+}
+
+/// This converter is never used, but we have a generic
+/// Option<T>, where T should implement ConvertTransaction
+///
+/// TODO: remove after never-type (`!`) stabilization
+enum NeverConvert {}
+impl<T> fp_rpc::ConvertTransaction<T> for NeverConvert {
+	fn convert_transaction(&self, _transaction: pallet_ethereum::Transaction) -> T {
+		unreachable!()
+	}
+}
 
+pub fn create_eth<C, P, CA, B>(
+	io: &mut RpcModule<()>,
+	deps: EthDeps<C, P, CA>,
+	subscription_task_executor: SubscriptionTaskExecutor,
+) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
+where
+	C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,
+	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
+	C: Send + Sync + 'static,
+	C: BlockchainEvents<Block>,
+	C::Api: BlockBuilder<Block>,
+	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
+	C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,
+	P: TransactionPool<Block = Block> + 'static,
+	CA: ChainApi<Block = Block> + 'static,
+	B: sc_client_api::Backend<Block> + Send + Sync + 'static,
+	C: sp_api::CallApiAt<
+		sp_runtime::generic::Block<
+			sp_runtime::generic::Header<u32, BlakeTwo256>,
+			sp_runtime::OpaqueExtrinsic,
+		>,
+	>,
+{
+	use fc_rpc::{
+		Eth, EthApiServer, EthDevSigner, EthFilter, EthFilterApiServer, EthPubSub,
+		EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer, TxPool, TxPoolApiServer,
+	};
+
+	let EthDeps {
+		client,
+		pool,
+		graph,
+		eth_backend,
+		max_past_logs,
+		fee_history_limit,
+		fee_history_cache,
+		eth_block_data_cache,
+		eth_filter_pool,
+		eth_pubsub_notification_sinks,
+		enable_dev_signer,
+		sync,
+		is_authority,
+		network,
+		overrides,
+	} = deps;
+
 	let mut signers = Vec::new();
 	if enable_dev_signer {
 		signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);
 	}
-
-	let overrides = overrides_handle::<_, _, R>(client.clone());
-
 	let execute_gas_limit_multiplier = 10;
 	io.merge(
 		Eth::new(
 			client.clone(),
 			pool.clone(),
 			graph.clone(),
-			Some(<R as RuntimeInstance>::get_transaction_converter()),
+			// We have no runtimes old enough to only accept converted transactions
+			None::<NeverConvert>,
 			sync.clone(),
 			signers,
 			overrides.clone(),
 			eth_backend.clone(),
 			is_authority,
-			block_data_cache.clone(),
+			eth_block_data_cache.clone(),
 			fee_history_cache,
 			fee_history_limit,
 			execute_gas_limit_multiplier,
@@ -256,24 +294,12 @@
 		.into_rpc(),
 	)?;
 
-	io.merge(Unique::new(client.clone()).into_rpc())?;
-
-	io.merge(AppPromotion::new(client.clone()).into_rpc())?;
+	let tx_pool = TxPool::new(
+		client.clone(),
+		graph,
+		);
 
-	#[cfg(feature = "pov-estimate")]
-	io.merge(
-		PovEstimate::new(
-			client.clone(),
-			backend,
-			deny_unsafe,
-			exec_params,
-			runtime_id,
-		)
-		.into_rpc(),
-	)?;
-
-	let tx_pool = TxPool::new(client.clone(), graph);
-	if let Some(filter_pool) = filter_pool {
+	if let Some(filter_pool) = eth_filter_pool {
 		io.merge(
 			EthFilter::new(
 				client.clone(),
@@ -282,12 +308,11 @@
 				filter_pool,
 				500_usize, // max stored filters
 				max_past_logs,
-				block_data_cache,
+				eth_block_data_cache,
 			)
 			.into_rpc(),
 		)?;
 	}
-
 	io.merge(
 		Net::new(
 			client.clone(),
@@ -297,9 +322,7 @@
 		)
 		.into_rpc(),
 	)?;
-
 	io.merge(Web3::new(client.clone()).into_rpc())?;
-
 	io.merge(
 		EthPubSub::new(
 			pool,
@@ -307,12 +330,11 @@
 			sync,
 			subscription_task_executor,
 			overrides,
-			pubsub_notification_sinks,
+			eth_pubsub_notification_sinks,
 		)
 		.into_rpc(),
 	)?;
-
 	io.merge(tx_pool.into_rpc())?;
 
-	Ok(io)
+	Ok(())
 }