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

difftreelog

fix remove from_ref_time usages

Yaroslav Bolyukin2023-04-17parent: #07a293d.patch.diff
in: master

9 files changed

modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -19,7 +19,7 @@
 	// Read collection
 	<T as frame_system::Config>::DbWeight::get().reads(1)
 	// Dynamic dispatch?
-	+ Weight::from_ref_time(6_000_000)
+	+ Weight::from_parts(6_000_000, 0)
 	// submit_logs is measured as part of collection pallets
 }
 
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -92,6 +92,7 @@
 pub mod dispatch;
 pub mod erc;
 pub mod eth;
+#[allow(missing_docs)]
 pub mod weights;
 
 /// Weight info.
@@ -157,10 +158,12 @@
 		reads: u64,
 	) -> pallet_evm_coder_substrate::execution::Result<()> {
 		self.recorder
-			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(
+			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
 				<T as frame_system::Config>::DbWeight::get()
 					.read
 					.saturating_mul(reads),
+				// TODO: measure proof
+				0,
 			)))
 	}
 
@@ -170,10 +173,12 @@
 		writes: u64,
 	) -> pallet_evm_coder_substrate::execution::Result<()> {
 		self.recorder
-			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(
+			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
 				<T as frame_system::Config>::DbWeight::get()
 					.write
 					.saturating_mul(writes),
+				// TODO: measure proof
+				0,
 			)))
 	}
 
@@ -187,8 +192,10 @@
 		let reads = weight.read.saturating_mul(reads);
 		let writes = weight.read.saturating_mul(writes);
 		self.recorder
-			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(
+			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
 				reads.saturating_add(writes),
+				// TODO: measure proof
+				0,
 			)))
 	}
 
modifiedpallets/evm-coder-substrate/src/execution.rsdiffbeforeafterboth
--- a/pallets/evm-coder-substrate/src/execution.rs
+++ b/pallets/evm-coder-substrate/src/execution.rs
@@ -61,7 +61,7 @@
 	fn dispatch_info(&self) -> DispatchInfo {
 		DispatchInfo {
 			// ERC165 impl should be cheap
-			weight: Weight::from_ref_time(200),
+			weight: Weight::from_parts(200, 0),
 		}
 	}
 }
@@ -77,10 +77,11 @@
 		Self { weight }
 	}
 }
+// TODO: use 2-dimensional weight after frontier upgrade
 impl From<u64> for DispatchInfo {
 	fn from(weight: u64) -> Self {
 		Self {
-			weight: Weight::from_ref_time(weight),
+			weight: Weight::from_parts(weight, 0),
 		}
 	}
 }
modifiedpallets/evm-migration/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-migration/src/lib.rs
+++ b/pallets/evm-migration/src/lib.rs
@@ -21,6 +21,7 @@
 pub use pallet::*;
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
+#[allow(missing_docs)]
 pub mod weights;
 
 #[frame_support::pallet]
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -26,6 +26,11 @@
 	Config as CommonConfig,
 	benchmarking::{create_data, create_u16_data},
 };
+use up_data_structs::{
+	CollectionId, CollectionMode, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+	MAX_COLLECTION_DESCRIPTION_LENGTH, CollectionLimits,
+};
+use pallet_common::erc::CrossAccountId;
 
 const SEED: u32 = 1;
 
@@ -34,9 +39,9 @@
 	mode: CollectionMode,
 ) -> Result<CollectionId, DispatchError> {
 	<T as CommonConfig>::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
-	let col_name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
-	let col_desc = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
-	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
+	let col_name = create_u16_data::<{ MAX_COLLECTION_NAME_LENGTH }>();
+	let col_desc = create_u16_data::<{ MAX_COLLECTION_DESCRIPTION_LENGTH }>();
+	let token_prefix = create_data::<{ MAX_TOKEN_PREFIX_LENGTH }>();
 	<Pallet<T>>::create_collection(
 		RawOrigin::Signed(owner).into(),
 		col_name,
@@ -54,9 +59,9 @@
 
 benchmarks! {
 	create_collection {
-		let col_name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
-		let col_desc = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
-		let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
+		let col_name = create_u16_data::<{MAX_COLLECTION_NAME_LENGTH}>();
+		let col_desc = create_u16_data::<{MAX_COLLECTION_DESCRIPTION_LENGTH}>();
+		let token_prefix = create_data::<{MAX_TOKEN_PREFIX_LENGTH}>();
 		let mode: CollectionMode = CollectionMode::NFT;
 		let caller: T::AccountId = account("caller", 0, SEED);
 		<T as CommonConfig>::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -89,14 +89,11 @@
 	use frame_support::{
 		dispatch::DispatchResult,
 		ensure, fail,
-		weights::{Weight},
-		pallet_prelude::{*},
 		BoundedVec,
 		storage::Key,
 	};
-	use frame_system::pallet_prelude::*;
 	use scale_info::TypeInfo;
-	use frame_system::{self as system, ensure_signed, ensure_root};
+	use frame_system::{ensure_signed, ensure_root};
 	use sp_std::{vec, vec::Vec};
 	use up_data_structs::{
 		MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
modifiedprimitives/common/src/constants.rsdiffbeforeafterboth
--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -64,9 +64,10 @@
 /// by  Operational  extrinsics.
 pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
 /// We allow for 2 seconds of compute with a 6 second average block time.
-pub const MAXIMUM_BLOCK_WEIGHT: Weight =
-	Weight::from_ref_time(WEIGHT_REF_TIME_PER_SECOND.saturating_div(2))
-		.set_proof_size(MAX_POV_SIZE as u64);
+pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
+	WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
+	MAX_POV_SIZE as u64,
+);
 
 parameter_types! {
 	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE / 2;
modifiedruntime/common/config/ethereum.rsdiffbeforeafterboth
--- a/runtime/common/config/ethereum.rs
+++ b/runtime/common/config/ethereum.rs
@@ -28,7 +28,7 @@
 	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;
 	pub const WeightTimePerGas: u64 = WEIGHT_REF_TIME_PER_SECOND / GasPerSecond::get();
 
-	pub const WeightPerGas: Weight = Weight::from_ref_time(WeightTimePerGas::get());
+	pub const WeightPerGas: Weight = Weight::from_parts(WeightTimePerGas::get(), 0);
 }
 
 /// Limiting EVM execution to 50% of block for substrate users and management tasks
modifiedruntime/common/mod.rsdiffbeforeafterboth
before · runtime/common/mod.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/>.1617pub mod config;18pub mod construct_runtime;19pub mod dispatch;20pub mod ethereum;21pub mod identity;22pub mod instance;23pub mod maintenance;24pub mod runtime_apis;2526#[cfg(feature = "scheduler")]27pub mod scheduler;2829pub mod sponsoring;30pub mod weights;3132#[cfg(test)]33pub mod tests;3435use sp_core::H160;36use frame_support::{37	traits::{Currency, OnUnbalanced, Imbalance},38	weights::Weight,39};40use sp_runtime::{41	generic,42	traits::{BlakeTwo256, BlockNumberProvider},43	impl_opaque_keys,44};45use sp_std::vec::Vec;4647#[cfg(feature = "std")]48use sp_version::NativeVersion;4950use crate::{51	Runtime, RuntimeCall, Balances, Treasury, Aura, Signature, AllPalletsWithSystem,52	InherentDataExt,53};54use up_common::types::{AccountId, BlockNumber};5556#[macro_export]57macro_rules! unsupported {58	() => {59		pallet_common::unsupported!($crate::Runtime)60	};61}6263/// The address format for describing accounts.64pub type Address = sp_runtime::MultiAddress<AccountId, ()>;65/// Block header type as expected by this runtime.66pub type Header = generic::Header<BlockNumber, BlakeTwo256>;67/// Block type as expected by this runtime.68pub type Block = generic::Block<Header, UncheckedExtrinsic>;69/// A Block signed with a Justification70pub type SignedBlock = generic::SignedBlock<Block>;71/// BlockId type as expected by this runtime.72pub type BlockId = generic::BlockId<Block>;7374impl_opaque_keys! {75	pub struct SessionKeys {76		pub aura: Aura,77	}78}7980/// The version information used to identify this runtime when compiled natively.81#[cfg(feature = "std")]82pub fn native_version() -> NativeVersion {83	NativeVersion {84		runtime_version: crate::VERSION,85		can_author_with: Default::default(),86	}87}8889pub type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;9091pub type SignedExtra = (92	frame_system::CheckSpecVersion<Runtime>,93	frame_system::CheckTxVersion<Runtime>,94	frame_system::CheckGenesis<Runtime>,95	frame_system::CheckEra<Runtime>,96	frame_system::CheckNonce<Runtime>,97	frame_system::CheckWeight<Runtime>,98	maintenance::CheckMaintenance,99	identity::DisableIdentityCalls,100	ChargeTransactionPayment,101	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,102	pallet_ethereum::FakeTransactionFinalizer<Runtime>,103);104105/// Unchecked extrinsic type as expected by this runtime.106pub type UncheckedExtrinsic =107	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;108109/// Extrinsic type that has already been checked.110pub type CheckedExtrinsic =111	fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;112113/// Executive: handles dispatch to the various modules.114pub type Executive = frame_executive::Executive<115	Runtime,116	Block,117	frame_system::ChainContext<Runtime>,118	Runtime,119	AllPalletsWithSystem,120	AuraToCollatorSelection,121>;122123type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;124125pub struct DealWithFees;126impl OnUnbalanced<NegativeImbalance> for DealWithFees {127	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {128		if let Some(fees) = fees_then_tips.next() {129			// for fees, 100% to treasury130			let mut split = fees.ration(100, 0);131			if let Some(tips) = fees_then_tips.next() {132				// for tips, if any, 100% to treasury133				tips.ration_merge_into(100, 0, &mut split);134			}135			Treasury::on_unbalanced(split.0);136			// Author::on_unbalanced(split.1);137		}138	}139}140141pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);142143impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider144	for RelayChainBlockNumberProvider<T>145{146	type BlockNumber = BlockNumber;147148	fn current_block_number() -> Self::BlockNumber {149		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()150			.map(|d| d.relay_parent_number)151			.unwrap_or_default()152	}153	#[cfg(feature = "runtime-benchmarks")]154	fn set_block_number(block: Self::BlockNumber) {155		cumulus_pallet_parachain_system::RelaychainBlockNumberProvider::<T>::set_block_number(block)156	}157}158159pub(crate) struct CheckInherents;160161impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {162	fn check_inherents(163		block: &Block,164		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,165	) -> sp_inherents::CheckInherentsResult {166		let relay_chain_slot = relay_state_proof167			.read_slot()168			.expect("Could not read the relay chain slot from the proof");169170		let inherent_data =171			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(172				relay_chain_slot,173				sp_std::time::Duration::from_secs(6),174			)175			.create_inherent_data()176			.expect("Could not create the timestamp inherent data");177178		inherent_data.check_extrinsics(block)179	}180}181182#[derive(codec::Encode, codec::Decode)]183pub enum XCMPMessage<XAccountId, XBalance> {184	/// Transfer tokens to the given account from the Parachain account.185	TransferToken(XAccountId, XBalance),186}187188pub struct AuraToCollatorSelection;189impl frame_support::traits::OnRuntimeUpgrade for AuraToCollatorSelection {190	fn on_runtime_upgrade() -> Weight {191		#[cfg(feature = "collator-selection")]192		{193			use frame_support::{BoundedVec, storage::migration};194			use sp_runtime::{traits::OpaqueKeys, RuntimeAppPublic};195			use pallet_session::SessionManager;196			use crate::config::pallets::MaxCollators;197198			let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);199200			let version = migration::get_storage_value::<()>(201				b"AuraToCollatorSelection",202				b"StorageVersion",203				&[],204			);205206			let should_upgrade = match version {207				None => true,208				Some(_) => false,209			};210211			if should_upgrade {212				log::info!(213					target: "runtime::aura_to_collator_selection",214					"Running migration of Aura authorities to Collator Selection invulnerables"215				);216217				let invulnerables = pallet_aura::Pallet::<Runtime>::authorities()218					.iter()219					.cloned()220					.filter_map(|authority_id| {221						weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));222						let vec = authority_id.clone().to_raw_vec();223						let slice = vec.as_slice();224						let array: Option<[u8; 32]> = match slice.try_into() {225							Ok(a) => Some(a),226							Err(_) => {227								log::error!("Failed to convert an Aura authority to a Collator Selection invulnerable: {:?}", authority_id);228								None229							},230						};231						array.map(|a| (AccountId::from(a), authority_id))232					})233					.collect::<Vec<_>>();234235				let bounded_invulnerables = BoundedVec::<_, MaxCollators>::try_from(236					invulnerables237						.iter()238						.cloned()239						.map(|(acc, _)| acc)240						.collect::<Vec<_>>(),241				)242				.expect("Existing collators/invulnerables are more than MaxCollators");243244				<pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);245246				let keys = invulnerables247					.into_iter()248					.map(|(acc, aura)| {249						(250							acc.clone(),                        // account id251							acc,                                // validator id252							SessionKeys { aura: aura.clone() }, // session keys253						)254					})255					.collect::<Vec<_>>();256257				for (account, val, keys) in keys.iter().cloned() {258					for id in <Runtime as pallet_session::Config>::Keys::key_ids() {259						<pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)260					}261					<pallet_session::NextKeys<Runtime>>::insert(&val, &keys);262					// todo exercise caution, the following is taken from genesis263					if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account)264						.is_err()265					{266						log::warn!(267							"We have entered an error with incrementing consumers without limit during the migration"268						);269						// This will leak a provider reference, however it only happens once (at270						// genesis) so it's really not a big deal and we assume that the user wants to271						// do this since it's the only way a non-endowed account can contain a session272						// key.273						frame_system::Pallet::<Runtime>::inc_providers(&account);274					}275				}276277				let initial_validators_0 =278					<Runtime as pallet_session::Config>::SessionManager::new_session(0)279						.unwrap_or_else(|| {280							frame_support::print(281								"No initial validator provided by `SessionManager`, use \282							session config keys to generate initial validator set.",283							);284							keys.iter().map(|x| x.1.clone()).collect()285						});286				/*assert!(287					!initial_validators_0.is_empty(),288					"Empty validator set for session 0 in (pseudo) genesis block!"289				);*/290291				let initial_validators_1 =292					<Runtime as pallet_session::Config>::SessionManager::new_session(1)293						.unwrap_or_else(|| initial_validators_0.clone());294				/*assert!(295					!initial_validators_1.is_empty(),296					"Empty validator set for session 1 in (pseudo) genesis block!"297				);*/298299				let queued_keys: Vec<_> = initial_validators_1300					.iter()301					.cloned()302					.map(|v| {303						(304							v.clone(),305							<pallet_session::NextKeys<Runtime>>::get(&v)306								.expect("Validator in session 1 missing keys!"),307						)308					})309					.collect();310311				// Tell everyone about the genesis session keys -- Aura must've already initialized it312				//<Runtime as pallet_session::Config>::SessionHandler::on_genesis_session::<<Runtime as pallet_session::Config>::Keys>(&queued_keys);313314				<pallet_session::Validators<Runtime>>::put(initial_validators_0);315				<pallet_session::QueuedKeys<Runtime>>::put(queued_keys);316317				<Runtime as pallet_session::Config>::SessionManager::start_session(0);318319				log::info!(320					target: "runtime::aura_to_collator_selection",321					"Migration of Aura authorities to Collator Selection invulnerables is complete."322				);323324				migration::put_storage_value::<()>(325					b"AuraToCollatorSelection",326					b"StorageVersion",327					&[],328					(),329				);330331				weight += <Runtime as frame_system::Config>::DbWeight::get().writes(1)332			} else {333				log::info!(334					target: "runtime::aura_to_collator_selection",335					"The storage migration has already been flagged as complete. No migration needs to be done.",336				);337			}338339			weight340		}341342		#[cfg(not(feature = "collator-selection"))]343		{344			Weight::zero()345		}346	}347}
after · runtime/common/mod.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/>.1617pub mod config;18pub mod construct_runtime;19pub mod dispatch;20pub mod ethereum;21pub mod identity;22pub mod instance;23pub mod maintenance;24pub mod runtime_apis;2526#[cfg(feature = "scheduler")]27pub mod scheduler;2829pub mod sponsoring;30#[allow(missing_docs)]31pub mod weights;3233#[cfg(test)]34pub mod tests;3536use sp_core::H160;37use frame_support::{38	traits::{Currency, OnUnbalanced, Imbalance},39	weights::Weight,40};41use sp_runtime::{42	generic,43	traits::{BlakeTwo256, BlockNumberProvider},44	impl_opaque_keys,45};46use sp_std::vec::Vec;4748#[cfg(feature = "std")]49use sp_version::NativeVersion;5051use crate::{52	Runtime, RuntimeCall, Balances, Treasury, Aura, Signature, AllPalletsWithSystem,53	InherentDataExt,54};55use up_common::types::{AccountId, BlockNumber};5657#[macro_export]58macro_rules! unsupported {59	() => {60		pallet_common::unsupported!($crate::Runtime)61	};62}6364/// The address format for describing accounts.65pub type Address = sp_runtime::MultiAddress<AccountId, ()>;66/// Block header type as expected by this runtime.67pub type Header = generic::Header<BlockNumber, BlakeTwo256>;68/// Block type as expected by this runtime.69pub type Block = generic::Block<Header, UncheckedExtrinsic>;70/// A Block signed with a Justification71pub type SignedBlock = generic::SignedBlock<Block>;72/// BlockId type as expected by this runtime.73pub type BlockId = generic::BlockId<Block>;7475impl_opaque_keys! {76	pub struct SessionKeys {77		pub aura: Aura,78	}79}8081/// The version information used to identify this runtime when compiled natively.82#[cfg(feature = "std")]83pub fn native_version() -> NativeVersion {84	NativeVersion {85		runtime_version: crate::VERSION,86		can_author_with: Default::default(),87	}88}8990pub type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;9192pub type SignedExtra = (93	frame_system::CheckSpecVersion<Runtime>,94	frame_system::CheckTxVersion<Runtime>,95	frame_system::CheckGenesis<Runtime>,96	frame_system::CheckEra<Runtime>,97	frame_system::CheckNonce<Runtime>,98	frame_system::CheckWeight<Runtime>,99	maintenance::CheckMaintenance,100	identity::DisableIdentityCalls,101	ChargeTransactionPayment,102	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,103	pallet_ethereum::FakeTransactionFinalizer<Runtime>,104);105106/// Unchecked extrinsic type as expected by this runtime.107pub type UncheckedExtrinsic =108	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;109110/// Extrinsic type that has already been checked.111pub type CheckedExtrinsic =112	fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;113114/// Executive: handles dispatch to the various modules.115pub type Executive = frame_executive::Executive<116	Runtime,117	Block,118	frame_system::ChainContext<Runtime>,119	Runtime,120	AllPalletsWithSystem,121	AuraToCollatorSelection,122>;123124type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;125126pub struct DealWithFees;127impl OnUnbalanced<NegativeImbalance> for DealWithFees {128	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {129		if let Some(fees) = fees_then_tips.next() {130			// for fees, 100% to treasury131			let mut split = fees.ration(100, 0);132			if let Some(tips) = fees_then_tips.next() {133				// for tips, if any, 100% to treasury134				tips.ration_merge_into(100, 0, &mut split);135			}136			Treasury::on_unbalanced(split.0);137			// Author::on_unbalanced(split.1);138		}139	}140}141142pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);143144impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider145	for RelayChainBlockNumberProvider<T>146{147	type BlockNumber = BlockNumber;148149	fn current_block_number() -> Self::BlockNumber {150		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()151			.map(|d| d.relay_parent_number)152			.unwrap_or_default()153	}154	#[cfg(feature = "runtime-benchmarks")]155	fn set_block_number(block: Self::BlockNumber) {156		cumulus_pallet_parachain_system::RelaychainDataProvider::<T>::set_block_number(block)157	}158}159160pub(crate) struct CheckInherents;161162impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {163	fn check_inherents(164		block: &Block,165		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,166	) -> sp_inherents::CheckInherentsResult {167		let relay_chain_slot = relay_state_proof168			.read_slot()169			.expect("Could not read the relay chain slot from the proof");170171		let inherent_data =172			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(173				relay_chain_slot,174				sp_std::time::Duration::from_secs(6),175			)176			.create_inherent_data()177			.expect("Could not create the timestamp inherent data");178179		inherent_data.check_extrinsics(block)180	}181}182183#[derive(codec::Encode, codec::Decode)]184pub enum XCMPMessage<XAccountId, XBalance> {185	/// Transfer tokens to the given account from the Parachain account.186	TransferToken(XAccountId, XBalance),187}188189pub struct AuraToCollatorSelection;190impl frame_support::traits::OnRuntimeUpgrade for AuraToCollatorSelection {191	fn on_runtime_upgrade() -> Weight {192		#[cfg(feature = "collator-selection")]193		{194			use frame_support::{BoundedVec, storage::migration};195			use sp_runtime::{traits::OpaqueKeys, RuntimeAppPublic};196			use pallet_session::SessionManager;197			use crate::config::pallets::MaxCollators;198199			let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);200201			let version = migration::get_storage_value::<()>(202				b"AuraToCollatorSelection",203				b"StorageVersion",204				&[],205			);206207			let should_upgrade = match version {208				None => true,209				Some(_) => false,210			};211212			if should_upgrade {213				log::info!(214					target: "runtime::aura_to_collator_selection",215					"Running migration of Aura authorities to Collator Selection invulnerables"216				);217218				let invulnerables = pallet_aura::Pallet::<Runtime>::authorities()219					.iter()220					.cloned()221					.filter_map(|authority_id| {222						weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));223						let vec = authority_id.clone().to_raw_vec();224						let slice = vec.as_slice();225						let array: Option<[u8; 32]> = match slice.try_into() {226							Ok(a) => Some(a),227							Err(_) => {228								log::error!("Failed to convert an Aura authority to a Collator Selection invulnerable: {:?}", authority_id);229								None230							},231						};232						array.map(|a| (AccountId::from(a), authority_id))233					})234					.collect::<Vec<_>>();235236				let bounded_invulnerables = BoundedVec::<_, MaxCollators>::try_from(237					invulnerables238						.iter()239						.cloned()240						.map(|(acc, _)| acc)241						.collect::<Vec<_>>(),242				)243				.expect("Existing collators/invulnerables are more than MaxCollators");244245				<pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);246247				let keys = invulnerables248					.into_iter()249					.map(|(acc, aura)| {250						(251							acc.clone(),                        // account id252							acc,                                // validator id253							SessionKeys { aura: aura.clone() }, // session keys254						)255					})256					.collect::<Vec<_>>();257258				for (account, val, keys) in keys.iter().cloned() {259					for id in <Runtime as pallet_session::Config>::Keys::key_ids() {260						<pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)261					}262					<pallet_session::NextKeys<Runtime>>::insert(&val, &keys);263					// todo exercise caution, the following is taken from genesis264					if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account)265						.is_err()266					{267						log::warn!(268							"We have entered an error with incrementing consumers without limit during the migration"269						);270						// This will leak a provider reference, however it only happens once (at271						// genesis) so it's really not a big deal and we assume that the user wants to272						// do this since it's the only way a non-endowed account can contain a session273						// key.274						frame_system::Pallet::<Runtime>::inc_providers(&account);275					}276				}277278				let initial_validators_0 =279					<Runtime as pallet_session::Config>::SessionManager::new_session(0)280						.unwrap_or_else(|| {281							frame_support::print(282								"No initial validator provided by `SessionManager`, use \283							session config keys to generate initial validator set.",284							);285							keys.iter().map(|x| x.1.clone()).collect()286						});287				/*assert!(288					!initial_validators_0.is_empty(),289					"Empty validator set for session 0 in (pseudo) genesis block!"290				);*/291292				let initial_validators_1 =293					<Runtime as pallet_session::Config>::SessionManager::new_session(1)294						.unwrap_or_else(|| initial_validators_0.clone());295				/*assert!(296					!initial_validators_1.is_empty(),297					"Empty validator set for session 1 in (pseudo) genesis block!"298				);*/299300				let queued_keys: Vec<_> = initial_validators_1301					.iter()302					.cloned()303					.map(|v| {304						(305							v.clone(),306							<pallet_session::NextKeys<Runtime>>::get(&v)307								.expect("Validator in session 1 missing keys!"),308						)309					})310					.collect();311312				// Tell everyone about the genesis session keys -- Aura must've already initialized it313				//<Runtime as pallet_session::Config>::SessionHandler::on_genesis_session::<<Runtime as pallet_session::Config>::Keys>(&queued_keys);314315				<pallet_session::Validators<Runtime>>::put(initial_validators_0);316				<pallet_session::QueuedKeys<Runtime>>::put(queued_keys);317318				<Runtime as pallet_session::Config>::SessionManager::start_session(0);319320				log::info!(321					target: "runtime::aura_to_collator_selection",322					"Migration of Aura authorities to Collator Selection invulnerables is complete."323				);324325				migration::put_storage_value::<()>(326					b"AuraToCollatorSelection",327					b"StorageVersion",328					&[],329					(),330				);331332				weight += <Runtime as frame_system::Config>::DbWeight::get().writes(1)333			} else {334				log::info!(335					target: "runtime::aura_to_collator_selection",336					"The storage migration has already been flagged as complete. No migration needs to be done.",337				);338			}339340			weight341		}342343		#[cfg(not(feature = "collator-selection"))]344		{345			Weight::zero()346		}347	}348}