frequency_runtime/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
3#![recursion_limit = "256"]
4
5extern crate alloc;
6#[cfg(feature = "runtime-benchmarks")]
7#[macro_use]
8extern crate frame_benchmarking; // Make the WASM binary available.
9#[cfg(feature = "std")]
10include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
11
12#[cfg(feature = "std")]
13#[allow(clippy::expect_used)]
14/// Wasm binary unwrapped. If built with `WASM_BINARY`, the function panics.
15pub fn wasm_binary_unwrap() -> &'static [u8] {
16	WASM_BINARY.expect(
17		"wasm binary is not available. This means the client is \
18                        built with `WASM_BINARY` flag and it is only usable for \
19                        production chains. Please rebuild with the flag disabled.",
20	)
21}
22
23#[cfg(feature = "frequency-bridging")]
24pub mod xcm;
25
26#[cfg(feature = "frequency-bridging")]
27use frame_support::traits::AsEnsureOriginWithArg;
28
29#[cfg(feature = "frequency-bridging")]
30use frame_system::EnsureNever;
31
32#[cfg(feature = "frequency-bridging")]
33use xcm::{
34	parameters::{
35		ForeignAssetsAssetId, NativeToken, RelayLocation, RelayOrigin, ReservedDmpWeight,
36		ReservedXcmpWeight,
37	},
38	queue::XcmRouter,
39	LocationToAccountId, XcmConfig,
40};
41
42#[cfg(test)]
43mod migration_tests;
44
45use alloc::borrow::Cow;
46use common_runtime::constants::currency::UNITS;
47
48#[cfg(feature = "frequency-bridging")]
49use staging_xcm::{
50	prelude::AssetId as AssetLocationId, Version as XcmVersion, VersionedAsset, VersionedAssetId,
51	VersionedAssets, VersionedLocation, VersionedXcm,
52};
53
54#[cfg(feature = "frequency-bridging")]
55use xcm_runtime_apis::{
56	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
57	fees::Error as XcmPaymentApiError,
58};
59
60#[cfg(any(
61	not(feature = "frequency-no-relay"),
62	feature = "frequency-lint-check",
63	feature = "frequency-bridging"
64))]
65use cumulus_pallet_parachain_system::{
66	DefaultCoreSelector, RelayNumberMonotonicallyIncreases, RelaychainDataProvider,
67};
68#[cfg(any(feature = "runtime-benchmarks", feature = "test"))]
69use frame_support::traits::MapSuccess;
70use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
71#[cfg(any(feature = "runtime-benchmarks", feature = "test"))]
72use sp_runtime::traits::Replace;
73use sp_runtime::{
74	generic, impl_opaque_keys,
75	traits::{AccountIdConversion, BlakeTwo256, Block as BlockT, ConvertInto, IdentityLookup},
76	transaction_validity::{TransactionSource, TransactionValidity},
77	ApplyExtrinsicResult, DispatchError,
78};
79
80use pallet_collective::Members;
81
82#[cfg(any(feature = "runtime-benchmarks", feature = "test"))]
83use pallet_collective::ProposalCount;
84
85use parity_scale_codec::Encode;
86
87#[cfg(feature = "std")]
88use sp_version::NativeVersion;
89
90use sp_version::RuntimeVersion;
91use static_assertions::const_assert;
92
93use common_primitives::{
94	handles::{
95		BaseHandle, CheckHandleResponse, DisplayHandle, HandleResponse, PresumptiveSuffixesResponse,
96	},
97	messages::MessageResponse,
98	msa::{
99		AccountId20Response, ApplicationIndex, DelegationResponse, DelegationValidator,
100		DelegatorId, MessageSourceId, ProviderApplicationContext, ProviderId, SchemaGrant,
101		SchemaGrantValidator, H160,
102	},
103	node::{
104		AccountId, Address, Balance, BlockNumber, Hash, Header, Index, ProposalProvider, Signature,
105		UtilityProvider,
106	},
107	rpc::RpcEvent,
108	schema::{PayloadLocation, SchemaId, SchemaResponse, SchemaVersionResponse},
109	stateful_storage::{ItemizedStoragePageResponse, PaginatedStorageResponse},
110};
111
112pub use common_runtime::{
113	constants::{
114		currency::{CENTS, EXISTENTIAL_DEPOSIT},
115		*,
116	},
117	fee::WeightToFee,
118	prod_or_testnet_or_local,
119	proxy::ProxyType,
120};
121
122use frame_support::{
123	construct_runtime,
124	dispatch::{DispatchClass, GetDispatchInfo, Pays},
125	genesis_builder_helper::{build_state, get_preset},
126	pallet_prelude::DispatchResultWithPostInfo,
127	parameter_types,
128	traits::{
129		fungible::HoldConsideration,
130		schedule::LOWEST_PRIORITY,
131		tokens::{PayFromAccount, UnityAssetBalanceConversion},
132		ConstBool, ConstU128, ConstU32, ConstU64, EitherOfDiverse, EnsureOrigin,
133		EqualPrivilegeOnly, GetStorageVersion, InstanceFilter, LinearStoragePrice,
134		OnRuntimeUpgrade,
135	},
136	weights::{constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, Weight},
137	Twox128,
138};
139
140use frame_system::{
141	limits::{BlockLength, BlockWeights},
142	EnsureRoot, EnsureSigned,
143};
144
145use alloc::{boxed::Box, vec, vec::Vec};
146
147pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
148pub use sp_runtime::Perbill;
149
150#[cfg(any(feature = "std", test))]
151pub use sp_runtime::BuildStorage;
152
153pub use pallet_capacity;
154pub use pallet_frequency_tx_payment::{capacity_stable_weights, types::GetStableWeight};
155pub use pallet_msa;
156pub use pallet_passkey;
157pub use pallet_schemas;
158pub use pallet_time_release::types::{ScheduleName, SchedulerProviderTrait};
159
160// Polkadot Imports
161use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
162
163use common_primitives::capacity::UnclaimedRewardInfo;
164use common_runtime::weights::rocksdb_weights::constants::RocksDbWeight;
165pub use common_runtime::{
166	constants::MaxSchemaGrants,
167	weights,
168	weights::{block_weights::BlockExecutionWeight, extrinsic_weights::ExtrinsicBaseWeight},
169};
170use frame_support::traits::Contains;
171#[cfg(feature = "try-runtime")]
172use frame_support::traits::{TryStateSelect, UpgradeCheckSelect};
173
174mod ethereum;
175mod genesis;
176
177pub mod polkadot_xcm_fee {
178	use crate::{Balance, ExtrinsicBaseWeight, WEIGHT_REF_TIME_PER_SECOND};
179	pub const MICRO_DOT: Balance = 10_000;
180	pub const MILLI_DOT: Balance = 1_000 * MICRO_DOT;
181
182	pub fn default_fee_per_second() -> u128 {
183		let base_weight = Balance::from(ExtrinsicBaseWeight::get().ref_time());
184		let base_tx_per_second = (WEIGHT_REF_TIME_PER_SECOND as u128) / base_weight;
185		base_tx_per_second * base_relay_tx_fee()
186	}
187
188	pub fn base_relay_tx_fee() -> Balance {
189		MILLI_DOT
190	}
191}
192
193pub struct SchedulerProvider;
194
195impl SchedulerProviderTrait<RuntimeOrigin, BlockNumber, RuntimeCall> for SchedulerProvider {
196	fn schedule(
197		origin: RuntimeOrigin,
198		id: ScheduleName,
199		when: BlockNumber,
200		call: Box<RuntimeCall>,
201	) -> Result<(), DispatchError> {
202		Scheduler::schedule_named(origin, id, when, None, LOWEST_PRIORITY, call)?;
203
204		Ok(())
205	}
206
207	fn cancel(origin: RuntimeOrigin, id: [u8; 32]) -> Result<(), DispatchError> {
208		Scheduler::cancel_named(origin, id)?;
209
210		Ok(())
211	}
212}
213
214pub struct CouncilProposalProvider;
215
216impl ProposalProvider<AccountId, RuntimeCall> for CouncilProposalProvider {
217	fn propose(
218		who: AccountId,
219		threshold: u32,
220		proposal: Box<RuntimeCall>,
221	) -> Result<(u32, u32), DispatchError> {
222		let length_bound: u32 = proposal.using_encoded(|p| p.len() as u32);
223		Council::do_propose_proposed(who, threshold, proposal, length_bound)
224	}
225
226	fn propose_with_simple_majority(
227		who: AccountId,
228		proposal: Box<RuntimeCall>,
229	) -> Result<(u32, u32), DispatchError> {
230		let members = Members::<Runtime, CouncilCollective>::get();
231		let threshold: u32 = ((members.len() / 2) + 1) as u32;
232		let length_bound: u32 = proposal.using_encoded(|p| p.len() as u32);
233		Council::do_propose_proposed(who, threshold, proposal, length_bound)
234	}
235
236	#[cfg(any(feature = "runtime-benchmarks", feature = "test"))]
237	fn proposal_count() -> u32 {
238		ProposalCount::<Runtime, CouncilCollective>::get()
239	}
240}
241
242pub struct CapacityBatchProvider;
243
244impl UtilityProvider<RuntimeOrigin, RuntimeCall> for CapacityBatchProvider {
245	fn batch_all(origin: RuntimeOrigin, calls: Vec<RuntimeCall>) -> DispatchResultWithPostInfo {
246		Utility::batch_all(origin, calls)
247	}
248}
249
250/// Base filter to only allow calls to specified transactions to be executed
251pub struct BaseCallFilter;
252
253impl Contains<RuntimeCall> for BaseCallFilter {
254	fn contains(call: &RuntimeCall) -> bool {
255		#[cfg(not(feature = "frequency"))]
256		{
257			match call {
258				RuntimeCall::Utility(pallet_utility_call) =>
259					Self::is_utility_call_allowed(pallet_utility_call),
260				_ => true,
261			}
262		}
263		#[cfg(feature = "frequency")]
264		{
265			match call {
266				RuntimeCall::Utility(pallet_utility_call) =>
267					Self::is_utility_call_allowed(pallet_utility_call),
268				// Create provider, create application, and create schema are not allowed in mainnet for now. See propose functions.
269				RuntimeCall::Msa(pallet_msa::Call::create_provider { .. }) |
270				RuntimeCall::Msa(pallet_msa::Call::create_application { .. }) |
271				RuntimeCall::Schemas(pallet_schemas::Call::create_schema_v3 { .. }) => false,
272				#[cfg(feature = "frequency-bridging")]
273				RuntimeCall::PolkadotXcm(pallet_xcm_call) => Self::is_xcm_call_allowed(pallet_xcm_call),
274				// Everything else is allowed on Mainnet
275				_ => true,
276			}
277		}
278	}
279}
280
281impl BaseCallFilter {
282	#[cfg(all(feature = "frequency", feature = "frequency-bridging"))]
283	fn is_xcm_call_allowed(call: &pallet_xcm::Call<Runtime>) -> bool {
284		!matches!(
285			call,
286			pallet_xcm::Call::transfer_assets { .. } |
287				pallet_xcm::Call::teleport_assets { .. } |
288				pallet_xcm::Call::limited_teleport_assets { .. } |
289				pallet_xcm::Call::reserve_transfer_assets { .. } |
290				pallet_xcm::Call::add_authorized_alias { .. } |
291				pallet_xcm::Call::remove_authorized_alias { .. } |
292				pallet_xcm::Call::remove_all_authorized_aliases { .. }
293		)
294	}
295
296	fn is_utility_call_allowed(call: &pallet_utility::Call<Runtime>) -> bool {
297		match call {
298			pallet_utility::Call::batch { calls, .. } |
299			pallet_utility::Call::batch_all { calls, .. } |
300			pallet_utility::Call::force_batch { calls, .. } => calls.iter().any(Self::is_batch_call_allowed),
301			_ => true,
302		}
303	}
304
305	fn is_batch_call_allowed(call: &RuntimeCall) -> bool {
306		match call {
307			// Block all nested `batch` calls from utility batch
308			RuntimeCall::Utility(pallet_utility::Call::batch { .. }) |
309			RuntimeCall::Utility(pallet_utility::Call::batch_all { .. }) |
310			RuntimeCall::Utility(pallet_utility::Call::force_batch { .. }) => false,
311
312			// Block all `FrequencyTxPayment` calls from utility batch
313			RuntimeCall::FrequencyTxPayment(..) => false,
314
315			// Block `create_provider`, `create_application` and `create_schema` calls from utility batch
316			RuntimeCall::Msa(pallet_msa::Call::create_provider { .. }) |
317			RuntimeCall::Msa(pallet_msa::Call::create_application { .. }) |
318			RuntimeCall::Schemas(pallet_schemas::Call::create_schema_v3 { .. }) => false,
319
320			// Block `Pays::No` calls from utility batch
321			_ if Self::is_pays_no_call(call) => false,
322
323			// Allow all other calls
324			_ => true,
325		}
326	}
327
328	fn is_pays_no_call(call: &RuntimeCall) -> bool {
329		call.get_dispatch_info().pays_fee == Pays::No
330	}
331}
332
333// Proxy Pallet Filters
334impl InstanceFilter<RuntimeCall> for ProxyType {
335	fn filter(&self, c: &RuntimeCall) -> bool {
336		match self {
337			ProxyType::Any => true,
338			ProxyType::NonTransfer => matches!(
339				c,
340				// Sorted
341				// Skip: RuntimeCall::Balances
342				RuntimeCall::Capacity(..)
343				| RuntimeCall::CollatorSelection(..)
344				| RuntimeCall::Council(..)
345				| RuntimeCall::Democracy(..)
346				| RuntimeCall::FrequencyTxPayment(..) // Capacity Tx never transfer
347				| RuntimeCall::Handles(..)
348				| RuntimeCall::Messages(..)
349				| RuntimeCall::Msa(..)
350				| RuntimeCall::Multisig(..)
351				// Skip: ParachainSystem(..)
352				| RuntimeCall::Preimage(..)
353				| RuntimeCall::Scheduler(..)
354				| RuntimeCall::Schemas(..)
355				| RuntimeCall::Session(..)
356				| RuntimeCall::StatefulStorage(..)
357				// Skip: RuntimeCall::Sudo
358				// Skip: RuntimeCall::System
359				| RuntimeCall::TechnicalCommittee(..)
360				// Specifically omitting TimeRelease `transfer`, and `update_release_schedules`
361				| RuntimeCall::TimeRelease(pallet_time_release::Call::claim{..})
362				| RuntimeCall::TimeRelease(pallet_time_release::Call::claim_for{..})
363				// Skip: RuntimeCall::Timestamp
364				| RuntimeCall::Treasury(..)
365				| RuntimeCall::Utility(..) // Calls inside a batch are also run through filters
366			),
367			ProxyType::Governance => matches!(
368				c,
369				RuntimeCall::Treasury(..) |
370					RuntimeCall::Democracy(..) |
371					RuntimeCall::TechnicalCommittee(..) |
372					RuntimeCall::Council(..) |
373					RuntimeCall::Utility(..) // Calls inside a batch are also run through filters
374			),
375			ProxyType::Staking => {
376				matches!(
377					c,
378					RuntimeCall::Capacity(
379						pallet_capacity::Call::stake { .. } |
380							pallet_capacity::Call::claim_staking_rewards { .. } |
381							pallet_capacity::Call::provider_boost { .. } |
382							pallet_capacity::Call::unstake { .. }
383					) | RuntimeCall::CollatorSelection(
384						pallet_collator_selection::Call::set_candidacy_bond { .. }
385					)
386				)
387			},
388			ProxyType::CancelProxy => {
389				matches!(c, RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }))
390			},
391		}
392	}
393	fn is_superset(&self, o: &Self) -> bool {
394		match (self, o) {
395			(x, y) if x == y => true,
396			(ProxyType::Any, _) => true,
397			(_, ProxyType::Any) => false,
398			(ProxyType::NonTransfer, _) => true,
399			_ => false,
400		}
401	}
402}
403
404/// PasskeyCallFilter to only allow calls to specified transactions to be executed
405pub struct PasskeyCallFilter;
406
407impl Contains<RuntimeCall> for PasskeyCallFilter {
408	fn contains(call: &RuntimeCall) -> bool {
409		match call {
410			#[cfg(feature = "runtime-benchmarks")]
411			RuntimeCall::System(frame_system::Call::remark { .. }) => true,
412
413			RuntimeCall::Balances(_) | RuntimeCall::Capacity(_) => true,
414			_ => false,
415		}
416	}
417}
418
419pub struct MsaCallFilter;
420use pallet_frequency_tx_payment::types::GetAddKeyData;
421impl GetAddKeyData<RuntimeCall, AccountId, MessageSourceId> for MsaCallFilter {
422	fn get_add_key_data(call: &RuntimeCall) -> Option<(AccountId, AccountId, MessageSourceId)> {
423		match call {
424			RuntimeCall::Msa(MsaCall::add_public_key_to_msa {
425				add_key_payload,
426				new_key_owner_proof: _,
427				msa_owner_public_key,
428				msa_owner_proof: _,
429			}) => {
430				let new_key = add_key_payload.clone().new_public_key;
431				Some((msa_owner_public_key.clone(), new_key, add_key_payload.msa_id))
432			},
433			_ => None,
434		}
435	}
436}
437
438/// The TransactionExtension to the basic transaction logic.
439pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
440	Runtime,
441	(
442		frame_system::CheckNonZeroSender<Runtime>,
443		// merging these types so that we can have more than 12 extensions
444		(frame_system::CheckSpecVersion<Runtime>, frame_system::CheckTxVersion<Runtime>),
445		frame_system::CheckGenesis<Runtime>,
446		frame_system::CheckEra<Runtime>,
447		common_runtime::extensions::check_nonce::CheckNonce<Runtime>,
448		pallet_frequency_tx_payment::ChargeFrqTransactionPayment<Runtime>,
449		pallet_msa::CheckFreeExtrinsicUse<Runtime>,
450		pallet_handles::handles_signed_extension::HandlesSignedExtension<Runtime>,
451		frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
452		frame_system::CheckWeight<Runtime>,
453	),
454>;
455
456/// A Block signed with a Justification
457pub type SignedBlock = generic::SignedBlock<Block>;
458
459/// BlockId type as expected by this runtime.
460pub type BlockId = generic::BlockId<Block>;
461
462/// Block type as expected by this runtime.
463pub type Block = generic::Block<Header, UncheckedExtrinsic>;
464
465#[cfg(feature = "frequency-bridging")]
466pub type AssetBalance = Balance;
467
468/// Unchecked extrinsic type as expected by this runtime.
469pub type UncheckedExtrinsic =
470	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
471
472/// Executive: handles dispatch to the various modules.
473#[cfg(feature = "frequency-bridging")]
474pub type Executive = frame_executive::Executive<
475	Runtime,
476	Block,
477	frame_system::ChainContext<Runtime>,
478	Runtime,
479	AllPalletsWithSystem,
480	(MigratePalletsCurrentStorage<Runtime>, SetSafeXcmVersion<Runtime>),
481>;
482
483#[cfg(not(feature = "frequency-bridging"))]
484pub type Executive = frame_executive::Executive<
485	Runtime,
486	Block,
487	frame_system::ChainContext<Runtime>,
488	Runtime,
489	AllPalletsWithSystem,
490	(MigratePalletsCurrentStorage<Runtime>,),
491>;
492
493pub struct MigratePalletsCurrentStorage<T>(core::marker::PhantomData<T>);
494
495impl<T: pallet_collator_selection::Config> OnRuntimeUpgrade for MigratePalletsCurrentStorage<T> {
496	fn on_runtime_upgrade() -> Weight {
497		use sp_core::Get;
498
499		if pallet_collator_selection::Pallet::<T>::on_chain_storage_version() !=
500			pallet_collator_selection::Pallet::<T>::in_code_storage_version()
501		{
502			pallet_collator_selection::Pallet::<T>::in_code_storage_version()
503				.put::<pallet_collator_selection::Pallet<T>>();
504
505			log::info!("Setting version on pallet_collator_selection");
506		}
507
508		T::DbWeight::get().reads_writes(1, 1)
509	}
510}
511
512/// Migration to set the initial safe XCM version for the XCM pallet.
513pub struct SetSafeXcmVersion<T>(core::marker::PhantomData<T>);
514
515#[cfg(feature = "frequency-bridging")]
516use common_runtime::constants::xcm_version::SAFE_XCM_VERSION;
517
518#[cfg(feature = "frequency-bridging")]
519impl<T: pallet_xcm::Config> OnRuntimeUpgrade for SetSafeXcmVersion<T> {
520	fn on_runtime_upgrade() -> Weight {
521		use sp_core::Get;
522
523		// Access storage directly using storage key because `pallet_xcm` does not provide a direct API to get the safe XCM version.
524		let storage_key = frame_support::storage::storage_prefix(b"PolkadotXcm", b"SafeXcmVersion");
525		log::info!("Checking SafeXcmVersion in storage with key: {storage_key:?}");
526
527		let current_version = frame_support::storage::unhashed::get::<u32>(&storage_key);
528		match current_version {
529			Some(version) if version == SAFE_XCM_VERSION => {
530				log::info!("SafeXcmVersion already set to {version}, skipping migration.");
531				T::DbWeight::get().reads(1)
532			},
533			Some(version) => {
534				log::info!(
535					"SafeXcmVersion currently set to {version}, updating to {SAFE_XCM_VERSION}"
536				);
537				// Set the safe XCM version directly in storage
538				frame_support::storage::unhashed::put(&storage_key, &(SAFE_XCM_VERSION));
539				T::DbWeight::get().reads(1).saturating_add(T::DbWeight::get().writes(1))
540			},
541			None => {
542				log::info!("SafeXcmVersion not set, setting to {SAFE_XCM_VERSION}");
543				// Set the safe XCM version directly in storage
544				frame_support::storage::unhashed::put(&storage_key, &(SAFE_XCM_VERSION));
545				T::DbWeight::get().reads(1).saturating_add(T::DbWeight::get().writes(1))
546			},
547		}
548	}
549
550	#[cfg(feature = "try-runtime")]
551	fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
552		use parity_scale_codec::Encode;
553
554		// Check pallet state before migration
555		pallet_xcm::Pallet::<T>::do_try_state()?;
556		log::info!("pre_upgrade: PolkadotXcm pallet state is valid before migration");
557
558		// Read the actual current SafeXcmVersion from storage
559		let storage_key = frame_support::storage::storage_prefix(b"PolkadotXcm", b"SafeXcmVersion");
560		let current_version = frame_support::storage::unhashed::get::<u32>(&storage_key);
561
562		log::info!("pre_upgrade: Current SafeXcmVersion = {:?}", current_version);
563
564		// Return the actual current state encoded for post_upgrade verification
565		Ok(current_version.encode())
566	}
567
568	#[cfg(feature = "try-runtime")]
569	fn post_upgrade(state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
570		use parity_scale_codec::Decode;
571
572		// Decode the pre-upgrade state
573		let pre_upgrade_version = Option::<u32>::decode(&mut &state[..])
574			.map_err(|_| "Failed to decode pre-upgrade state")?;
575
576		let storage_key = frame_support::storage::storage_prefix(b"PolkadotXcm", b"SafeXcmVersion");
577		let current_version = frame_support::storage::unhashed::get::<u32>(&storage_key);
578
579		log::info!(
580			"post_upgrade: Pre-upgrade version = {pre_upgrade_version:?}, Current version = {current_version:?}",
581		);
582
583		// Verify the migration worked correctly
584		match current_version {
585			Some(version) if version == SAFE_XCM_VERSION => {
586				log::info!(
587					"post_upgrade: Migration successful - SafeXcmVersion correctly set to {}",
588					version
589				);
590			},
591			Some(version) => {
592				log::error!("post_upgrade: Migration failed - SafeXcmVersion was set to {}, but expected {}", version, SAFE_XCM_VERSION);
593				return Err(sp_runtime::TryRuntimeError::Other(
594					"SafeXcmVersion was set to incorrect version after migration",
595				));
596			},
597			None => {
598				return Err(sp_runtime::TryRuntimeError::Other(
599					"SafeXcmVersion should be set after migration but found None",
600				));
601			},
602		}
603
604		// Check pallet state after migration
605		pallet_xcm::Pallet::<T>::do_try_state()?;
606		log::info!("post_upgrade: PolkadotXcm pallet state is valid after migration");
607
608		Ok(())
609	}
610}
611
612/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
613/// the specifics of the runtime. They can then be made to be agnostic over specific formats
614/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
615/// to even the core data structures.
616pub mod opaque {
617	use super::*;
618	use sp_runtime::{
619		generic,
620		traits::{BlakeTwo256, Hash as HashT},
621	};
622
623	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
624	/// Opaque block header type.
625	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
626	/// Opaque block type.
627	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
628	/// Opaque block identifier type.
629	pub type BlockId = generic::BlockId<Block>;
630	/// Opaque block hash type.
631	pub type Hash = <BlakeTwo256 as HashT>::Output;
632}
633
634impl_opaque_keys! {
635	pub struct SessionKeys {
636		pub aura: Aura,
637	}
638}
639
640// IMPORTANT: Remember to update spec_version in BOTH structs below
641#[cfg(feature = "frequency")]
642#[sp_version::runtime_version]
643pub const VERSION: RuntimeVersion = RuntimeVersion {
644	spec_name: Cow::Borrowed("frequency"),
645	impl_name: Cow::Borrowed("frequency"),
646	authoring_version: 1,
647	spec_version: 183,
648	impl_version: 0,
649	apis: RUNTIME_API_VERSIONS,
650	transaction_version: 1,
651	system_version: 1,
652};
653
654// IMPORTANT: Remember to update spec_version in above struct too
655#[cfg(not(feature = "frequency"))]
656#[sp_version::runtime_version]
657pub const VERSION: RuntimeVersion = RuntimeVersion {
658	spec_name: Cow::Borrowed("frequency-testnet"),
659	impl_name: Cow::Borrowed("frequency"),
660	authoring_version: 1,
661	spec_version: 183,
662	impl_version: 0,
663	apis: RUNTIME_API_VERSIONS,
664	transaction_version: 1,
665	system_version: 1,
666};
667
668/// The version information used to identify this runtime when compiled natively.
669#[cfg(feature = "std")]
670pub fn native_version() -> NativeVersion {
671	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
672}
673
674// Needs parameter_types! for the complex logic
675parameter_types! {
676	pub const Version: RuntimeVersion = VERSION;
677
678	// This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
679	//  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
680	// `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
681	// the lazy contract deletion.
682	pub RuntimeBlockLength: BlockLength =
683		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
684
685	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
686		.base_block(BlockExecutionWeight::get())
687		.for_class(DispatchClass::all(), |weights| {
688			weights.base_extrinsic = ExtrinsicBaseWeight::get();
689		})
690		.for_class(DispatchClass::Normal, |weights| {
691			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
692		})
693		.for_class(DispatchClass::Operational, |weights| {
694			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
695			// Operational transactions have some extra reserved space, so that they
696			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
697			weights.reserved = Some(
698				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
699			);
700		})
701		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
702		.build_or_panic();
703}
704
705// ---------- Foreign Assets pallet parameters ----------
706#[cfg(feature = "frequency-bridging")]
707parameter_types! {
708	pub const AssetDeposit: Balance = 0;
709	pub const AssetAccountDeposit: Balance = 0;
710	pub const MetadataDepositBase: Balance = 0;
711	pub const MetadataDepositPerByte: Balance = 0;
712	pub const ApprovalDeposit: Balance = 0;
713	pub const AssetsStringLimit: u32 = 50;
714
715	// we just reuse the same deposits
716	pub const ForeignAssetsAssetDeposit: Balance = AssetDeposit::get();
717	pub const ForeignAssetsAssetAccountDeposit: Balance = AssetAccountDeposit::get();
718	pub const ForeignAssetsApprovalDeposit: Balance = ApprovalDeposit::get();
719	pub const ForeignAssetsAssetsStringLimit: u32 = AssetsStringLimit::get();
720	pub const ForeignAssetsMetadataDepositBase: Balance = MetadataDepositBase::get();
721	pub const ForeignAssetsMetadataDepositPerByte: Balance = MetadataDepositPerByte::get();
722}
723
724// Configure FRAME pallets to include in runtime.
725
726impl frame_system::Config for Runtime {
727	type RuntimeTask = RuntimeTask;
728	/// The identifier used to distinguish between accounts.
729	type AccountId = AccountId;
730	/// Base call filter to use in dispatchable.
731	// enable for cfg feature "frequency" only
732	type BaseCallFilter = BaseCallFilter;
733	/// The aggregated dispatch type that is available for extrinsics.
734	type RuntimeCall = RuntimeCall;
735	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
736	type Lookup = EthereumCompatibleAccountIdLookup<AccountId, ()>;
737	/// The index type for storing how many extrinsics an account has signed.
738	type Nonce = Index;
739	/// The block type.
740	type Block = Block;
741	/// The type for hashing blocks and tries.
742	type Hash = Hash;
743	/// The hashing algorithm used.
744	type Hashing = BlakeTwo256;
745	/// The ubiquitous event type.
746	type RuntimeEvent = RuntimeEvent;
747	/// The ubiquitous origin type.
748	type RuntimeOrigin = RuntimeOrigin;
749	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
750	type BlockHashCount = BlockHashCount;
751	/// Runtime version.
752	type Version = Version;
753	/// Converts a module to an index of this module in the runtime.
754	type PalletInfo = PalletInfo;
755	/// The data to be stored in an account.
756	type AccountData = pallet_balances::AccountData<Balance>;
757	/// What to do if a new account is created.
758	type OnNewAccount = ();
759	/// What to do if an account is fully reaped from the system.
760	type OnKilledAccount = ();
761	/// The weight of database operations that the runtime can invoke.
762	type DbWeight = RocksDbWeight;
763	/// Weight information for the extrinsics of this pallet.
764	type SystemWeightInfo = ();
765	/// Block & extrinsics weights: base values and limits.
766	type BlockWeights = RuntimeBlockWeights;
767	/// The maximum length of a block (in bytes).
768	type BlockLength = RuntimeBlockLength;
769	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
770	type SS58Prefix = Ss58Prefix;
771	/// The action to take on a Runtime Upgrade
772	#[cfg(any(
773		not(feature = "frequency-no-relay"),
774		feature = "frequency-lint-check",
775		feature = "frequency-bridging"
776	))]
777	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
778	#[cfg(feature = "frequency-no-relay")]
779	type OnSetCode = ();
780	type MaxConsumers = FrameSystemMaxConsumers;
781	///  A new way of configuring migrations that run in a single block.
782	type SingleBlockMigrations = ();
783	/// The migrator that is used to run Multi-Block-Migrations.
784	type MultiBlockMigrator = ();
785	/// A callback that executes in *every block* directly before all inherents were applied.
786	type PreInherents = ();
787	/// A callback that executes in *every block* directly after all inherents were applied.
788	type PostInherents = ();
789	/// A callback that executes in *every block* directly after all transactions were applied.
790	type PostTransactions = ();
791	type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
792}
793
794impl pallet_msa::Config for Runtime {
795	type RuntimeEvent = RuntimeEvent;
796	type WeightInfo = pallet_msa::weights::SubstrateWeight<Runtime>;
797	// The conversion to a 32 byte AccountId
798	type ConvertIntoAccountId32 = ConvertInto;
799	// The maximum number of public keys per MSA
800	type MaxPublicKeysPerMsa = MsaMaxPublicKeysPerMsa;
801	// The maximum number of schema grants per delegation
802	type MaxSchemaGrantsPerDelegation = MaxSchemaGrants;
803	// The maximum provider name size (in bytes)
804	type MaxProviderNameSize = MsaMaxProviderNameSize;
805	// The type that provides schema related info
806	type SchemaValidator = Schemas;
807	// The type that provides `Handle` related info for a given `MessageSourceAccount`
808	type HandleProvider = Handles;
809	// The number of blocks per virtual bucket
810	type MortalityWindowSize = MSAMortalityWindowSize;
811	// The maximum number of signatures that can be stored in the payload signature registry
812	type MaxSignaturesStored = MSAMaxSignaturesStored;
813	// The proposal type
814	type Proposal = RuntimeCall;
815	// The Council proposal provider interface
816	type ProposalProvider = CouncilProposalProvider;
817	// The origin that is allowed to approve recovery providers
818	#[cfg(any(feature = "frequency", feature = "runtime-benchmarks"))]
819	type RecoveryProviderApprovalOrigin = EitherOfDiverse<
820		EnsureRoot<AccountId>,
821		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 2, 3>,
822	>;
823	#[cfg(not(any(feature = "frequency", feature = "runtime-benchmarks")))]
824	type RecoveryProviderApprovalOrigin = EnsureSigned<AccountId>;
825	// The origin that is allowed to create providers via governance
826	type CreateProviderViaGovernanceOrigin = EitherOfDiverse<
827		EnsureRoot<AccountId>,
828		pallet_collective::EnsureMembers<AccountId, CouncilCollective, 1>,
829	>;
830	// The Currency type for managing MSA token balances
831	type Currency = Balances;
832	// The maximum language code size (in bytes)
833	type MaxLanguageCodeSize = MsaMaxLanguageCodeSize;
834	// The maximum logo CID size (in bytes)
835	type MaxLogoCidSize = MsaMaxLogoCidSize;
836	// The maximum locale count
837	type MaxLocaleCount = MsaMaxLocaleCount;
838	// The maximum logo size (in bytes)
839	type MaxLogoSize = MsaMaxLogoSize;
840}
841
842parameter_types! {
843	/// The maximum number of eras over which one can claim rewards
844	pub const ProviderBoostHistoryLimit : u32 = 30;
845	/// The number of chunks of Reward Pool history we expect to store
846	pub const RewardPoolChunkLength: u32 = 5;
847}
848// RewardPoolChunkLength MUST be a divisor of ProviderBoostHistoryLimit
849const_assert!(ProviderBoostHistoryLimit::get() % RewardPoolChunkLength::get() == 0);
850
851impl pallet_capacity::Config for Runtime {
852	type RuntimeEvent = RuntimeEvent;
853	type WeightInfo = pallet_capacity::weights::SubstrateWeight<Runtime>;
854	type Currency = Balances;
855	type MinimumStakingAmount = CapacityMinimumStakingAmount;
856	type MinimumTokenBalance = CapacityMinimumTokenBalance;
857	type TargetValidator = Msa;
858	type MaxUnlockingChunks = CapacityMaxUnlockingChunks;
859	#[cfg(feature = "runtime-benchmarks")]
860	type BenchmarkHelper = Msa;
861	type UnstakingThawPeriod = CapacityUnstakingThawPeriod;
862	type MaxEpochLength = CapacityMaxEpochLength;
863	type EpochNumber = u32;
864	type CapacityPerToken = CapacityPerToken;
865	type RuntimeFreezeReason = RuntimeFreezeReason;
866	type EraLength = CapacityRewardEraLength;
867	type ProviderBoostHistoryLimit = ProviderBoostHistoryLimit;
868	type RewardsProvider = Capacity;
869	type MaxRetargetsPerRewardEra = ConstU32<2>;
870	// Value determined by desired inflation rate limits for chosen economic model
871	type RewardPoolPerEra = ConstU128<{ currency::CENTS.saturating_mul(153_424_650u128) }>;
872	type RewardPercentCap = CapacityRewardCap;
873	// Must evenly divide ProviderBoostHistoryLimit
874	type RewardPoolChunkLength = RewardPoolChunkLength;
875}
876
877impl pallet_schemas::Config for Runtime {
878	type RuntimeEvent = RuntimeEvent;
879	type WeightInfo = pallet_schemas::weights::SubstrateWeight<Runtime>;
880	// The minimum size (in bytes) for a schema model
881	type MinSchemaModelSizeBytes = SchemasMinModelSizeBytes;
882	// The maximum number of schemas that can be registered
883	type MaxSchemaRegistrations = SchemasMaxRegistrations;
884	// The maximum length of a schema model (in bytes)
885	type SchemaModelMaxBytesBoundedVecLimit = SchemasMaxBytesBoundedVecLimit;
886	// The proposal type
887	type Proposal = RuntimeCall;
888	// The Council proposal provider interface
889	type ProposalProvider = CouncilProposalProvider;
890	// The origin that is allowed to create schemas via governance
891	type CreateSchemaViaGovernanceOrigin = EitherOfDiverse<
892		EnsureRoot<AccountId>,
893		pallet_collective::EnsureProportionMoreThan<AccountId, CouncilCollective, 1, 2>,
894	>;
895	// Maximum number of schema grants that are allowed per schema
896	type MaxSchemaSettingsPerSchema = MaxSchemaSettingsPerSchema;
897}
898
899// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
900pub type DepositBase = ConstU128<{ currency::deposit(1, 88) }>;
901// Additional storage item size of 32 bytes.
902pub type DepositFactor = ConstU128<{ currency::deposit(0, 32) }>;
903pub type MaxSignatories = ConstU32<100>;
904
905// See https://paritytech.github.io/substrate/master/pallet_multisig/pallet/trait.Config.html for
906// the descriptions of these configs.
907impl pallet_multisig::Config for Runtime {
908	type BlockNumberProvider = System;
909	type RuntimeEvent = RuntimeEvent;
910	type RuntimeCall = RuntimeCall;
911	type Currency = Balances;
912	type DepositBase = DepositBase;
913	type DepositFactor = DepositFactor;
914	type MaxSignatories = MaxSignatories;
915	type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
916}
917
918impl cumulus_pallet_weight_reclaim::Config for Runtime {
919	type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
920}
921
922/// Need this declaration method for use + type safety in benchmarks
923pub type MaxReleaseSchedules = ConstU32<{ MAX_RELEASE_SCHEDULES }>;
924
925pub struct EnsureTimeReleaseOrigin;
926
927impl EnsureOrigin<RuntimeOrigin> for EnsureTimeReleaseOrigin {
928	type Success = AccountId;
929
930	fn try_origin(o: RuntimeOrigin) -> Result<Self::Success, RuntimeOrigin> {
931		match o.clone().into() {
932			Ok(pallet_time_release::Origin::<Runtime>::TimeRelease(who)) => Ok(who),
933			_ => Err(o),
934		}
935	}
936
937	#[cfg(feature = "runtime-benchmarks")]
938	fn try_successful_origin() -> Result<RuntimeOrigin, ()> {
939		Ok(RuntimeOrigin::root())
940	}
941}
942
943// See https://paritytech.github.io/substrate/master/pallet_vesting/index.html for
944// the descriptions of these configs.
945impl pallet_time_release::Config for Runtime {
946	type RuntimeEvent = RuntimeEvent;
947	type Balance = Balance;
948	type Currency = Balances;
949	type RuntimeOrigin = RuntimeOrigin;
950	type RuntimeHoldReason = RuntimeHoldReason;
951	type MinReleaseTransfer = MinReleaseTransfer;
952	type TransferOrigin = EnsureSigned<AccountId>;
953	type WeightInfo = pallet_time_release::weights::SubstrateWeight<Runtime>;
954	type MaxReleaseSchedules = MaxReleaseSchedules;
955	#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
956	type BlockNumberProvider = RelaychainDataProvider<Runtime>;
957	#[cfg(feature = "frequency-no-relay")]
958	type BlockNumberProvider = System;
959	type RuntimeFreezeReason = RuntimeFreezeReason;
960	type SchedulerProvider = SchedulerProvider;
961	type RuntimeCall = RuntimeCall;
962	type TimeReleaseOrigin = EnsureTimeReleaseOrigin;
963}
964
965// See https://paritytech.github.io/substrate/master/pallet_timestamp/index.html for
966// the descriptions of these configs.
967impl pallet_timestamp::Config for Runtime {
968	/// A timestamp: milliseconds since the unix epoch.
969	type Moment = u64;
970	#[cfg(not(feature = "frequency-no-relay"))]
971	type OnTimestampSet = Aura;
972	#[cfg(feature = "frequency-no-relay")]
973	type OnTimestampSet = ();
974	type MinimumPeriod = MinimumPeriod;
975	type WeightInfo = weights::pallet_timestamp::SubstrateWeight<Runtime>;
976}
977
978// See https://paritytech.github.io/substrate/master/pallet_authorship/index.html for
979// the descriptions of these configs.
980impl pallet_authorship::Config for Runtime {
981	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
982	type EventHandler = (CollatorSelection,);
983}
984
985parameter_types! {
986	pub const ExistentialDeposit: u128 = EXISTENTIAL_DEPOSIT;
987}
988
989impl pallet_balances::Config for Runtime {
990	type MaxLocks = BalancesMaxLocks;
991	/// The type for recording an account's balance.
992	type Balance = Balance;
993	/// The ubiquitous event type.
994	type RuntimeEvent = RuntimeEvent;
995	type DustRemoval = ();
996	type ExistentialDeposit = ExistentialDeposit;
997	type AccountStore = System;
998	type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
999	type MaxReserves = BalancesMaxReserves;
1000	type ReserveIdentifier = [u8; 8];
1001	type MaxFreezes = BalancesMaxFreezes;
1002	type RuntimeHoldReason = RuntimeHoldReason;
1003	type RuntimeFreezeReason = RuntimeFreezeReason;
1004	type FreezeIdentifier = RuntimeFreezeReason;
1005	type DoneSlashHandler = ();
1006}
1007// Needs parameter_types! for the Weight type
1008parameter_types! {
1009	// The maximum weight that may be scheduled per block for any dispatchables of less priority than schedule::HARD_DEADLINE.
1010	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(30) * RuntimeBlockWeights::get().max_block;
1011	pub MaxCollectivesProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block;
1012}
1013
1014// See also https://docs.rs/pallet-scheduler/latest/pallet_scheduler/trait.Config.html
1015impl pallet_scheduler::Config for Runtime {
1016	type BlockNumberProvider = System;
1017	type RuntimeEvent = RuntimeEvent;
1018	type RuntimeOrigin = RuntimeOrigin;
1019	type PalletsOrigin = OriginCaller;
1020	type RuntimeCall = RuntimeCall;
1021	type MaximumWeight = MaximumSchedulerWeight;
1022	/// Origin to schedule or cancel calls
1023	/// Set to Root or a simple majority of the Frequency Council
1024	type ScheduleOrigin = EitherOfDiverse<
1025		EitherOfDiverse<
1026			EnsureRoot<AccountId>,
1027			pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 2>,
1028		>,
1029		EnsureTimeReleaseOrigin,
1030	>;
1031
1032	type MaxScheduledPerBlock = SchedulerMaxScheduledPerBlock;
1033	type WeightInfo = weights::pallet_scheduler::SubstrateWeight<Runtime>;
1034	type OriginPrivilegeCmp = EqualPrivilegeOnly;
1035	type Preimages = Preimage;
1036}
1037
1038parameter_types! {
1039	pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
1040}
1041
1042// See https://paritytech.github.io/substrate/master/pallet_preimage/index.html for
1043// the descriptions of these configs.
1044impl pallet_preimage::Config for Runtime {
1045	type WeightInfo = weights::pallet_preimage::SubstrateWeight<Runtime>;
1046	type RuntimeEvent = RuntimeEvent;
1047	type Currency = Balances;
1048	// Allow the Technical council to request preimages without deposit or fees
1049	type ManagerOrigin = EitherOfDiverse<
1050		EnsureRoot<AccountId>,
1051		pallet_collective::EnsureMember<AccountId, TechnicalCommitteeCollective>,
1052	>;
1053
1054	type Consideration = HoldConsideration<
1055		AccountId,
1056		Balances,
1057		PreimageHoldReason,
1058		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
1059	>;
1060}
1061
1062// See https://paritytech.github.io/substrate/master/pallet_collective/index.html for
1063// the descriptions of these configs.
1064type CouncilCollective = pallet_collective::Instance1;
1065impl pallet_collective::Config<CouncilCollective> for Runtime {
1066	type RuntimeOrigin = RuntimeOrigin;
1067	type Proposal = RuntimeCall;
1068	type RuntimeEvent = RuntimeEvent;
1069	type MotionDuration = CouncilMotionDuration;
1070	type MaxProposals = CouncilMaxProposals;
1071	type MaxMembers = CouncilMaxMembers;
1072	type DefaultVote = pallet_collective::PrimeDefaultVote;
1073	type WeightInfo = weights::pallet_collective_council::SubstrateWeight<Runtime>;
1074	type SetMembersOrigin = EnsureRoot<Self::AccountId>;
1075	type MaxProposalWeight = MaxCollectivesProposalWeight;
1076	type DisapproveOrigin = EitherOfDiverse<
1077		EnsureRoot<AccountId>,
1078		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 2, 3>,
1079	>;
1080	type KillOrigin = EitherOfDiverse<
1081		EnsureRoot<AccountId>,
1082		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 2, 3>,
1083	>;
1084	type Consideration = ();
1085}
1086
1087type TechnicalCommitteeCollective = pallet_collective::Instance2;
1088impl pallet_collective::Config<TechnicalCommitteeCollective> for Runtime {
1089	type RuntimeOrigin = RuntimeOrigin;
1090	type Proposal = RuntimeCall;
1091	type RuntimeEvent = RuntimeEvent;
1092	type MotionDuration = TCMotionDuration;
1093	type MaxProposals = TCMaxProposals;
1094	type MaxMembers = TCMaxMembers;
1095	type DefaultVote = pallet_collective::PrimeDefaultVote;
1096	type WeightInfo = weights::pallet_collective_technical_committee::SubstrateWeight<Runtime>;
1097	type SetMembersOrigin = EnsureRoot<Self::AccountId>;
1098	type MaxProposalWeight = MaxCollectivesProposalWeight;
1099	type DisapproveOrigin = EitherOfDiverse<
1100		EnsureRoot<AccountId>,
1101		pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCommitteeCollective, 2, 3>,
1102	>;
1103	type KillOrigin = EitherOfDiverse<
1104		EnsureRoot<AccountId>,
1105		pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCommitteeCollective, 2, 3>,
1106	>;
1107	type Consideration = ();
1108}
1109
1110// see https://paritytech.github.io/substrate/master/pallet_democracy/pallet/trait.Config.html
1111// for the definitions of these configs
1112impl pallet_democracy::Config for Runtime {
1113	type CooloffPeriod = CooloffPeriod;
1114	type Currency = Balances;
1115	type EnactmentPeriod = EnactmentPeriod;
1116	type RuntimeEvent = RuntimeEvent;
1117	type FastTrackVotingPeriod = FastTrackVotingPeriod;
1118	type InstantAllowed = ConstBool<true>;
1119	type LaunchPeriod = LaunchPeriod;
1120	type MaxProposals = DemocracyMaxProposals;
1121	type MaxVotes = DemocracyMaxVotes;
1122	type MinimumDeposit = MinimumDeposit;
1123	type Scheduler = Scheduler;
1124	type Slash = ();
1125	// Treasury;
1126	type WeightInfo = weights::pallet_democracy::SubstrateWeight<Runtime>;
1127	type VoteLockingPeriod = EnactmentPeriod;
1128	// Same as EnactmentPeriod
1129	type VotingPeriod = VotingPeriod;
1130	type Preimages = Preimage;
1131	type MaxDeposits = ConstU32<100>;
1132	type MaxBlacklisted = ConstU32<100>;
1133
1134	// See https://paritytech.github.io/substrate/master/pallet_democracy/index.html for
1135	// the descriptions of these origins.
1136	// See https://paritytech.github.io/substrate/master/pallet_democracy/pallet/trait.Config.html for
1137	// the definitions of these config traits.
1138	/// A unanimous council can have the next scheduled referendum be a straight default-carries
1139	/// (NTB) vote.
1140	type ExternalDefaultOrigin = EitherOfDiverse<
1141		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 1>,
1142		frame_system::EnsureRoot<AccountId>,
1143	>;
1144
1145	/// A simple-majority of 50% + 1 can have the next scheduled referendum be a straight majority-carries vote.
1146	type ExternalMajorityOrigin = EitherOfDiverse<
1147		pallet_collective::EnsureProportionMoreThan<AccountId, CouncilCollective, 1, 2>,
1148		frame_system::EnsureRoot<AccountId>,
1149	>;
1150	/// A straight majority (at least 50%) of the council can decide what their next motion is.
1151	type ExternalOrigin = EitherOfDiverse<
1152		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 2>,
1153		frame_system::EnsureRoot<AccountId>,
1154	>;
1155	// Origin from which the new proposal can be made.
1156	// The success variant is the account id of the depositor.
1157	type SubmitOrigin = frame_system::EnsureSigned<AccountId>;
1158
1159	/// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote
1160	/// be tabled immediately and with a shorter voting/enactment period.
1161	type FastTrackOrigin = EitherOfDiverse<
1162		pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCommitteeCollective, 2, 3>,
1163		frame_system::EnsureRoot<AccountId>,
1164	>;
1165	/// Origin from which the next majority-carries (or more permissive) referendum may be tabled to
1166	/// vote immediately and asynchronously in a similar manner to the emergency origin.
1167	/// Requires TechnicalCommittee to be unanimous.
1168	type InstantOrigin = EitherOfDiverse<
1169		pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCommitteeCollective, 1, 1>,
1170		frame_system::EnsureRoot<AccountId>,
1171	>;
1172	/// Overarching type of all pallets origins
1173	type PalletsOrigin = OriginCaller;
1174
1175	/// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
1176	type CancellationOrigin = EitherOfDiverse<
1177		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 2, 3>,
1178		EnsureRoot<AccountId>,
1179	>;
1180	/// To cancel a proposal before it has been passed, the technical committee must be unanimous or
1181	/// Root must agree.
1182	type CancelProposalOrigin = EitherOfDiverse<
1183		EnsureRoot<AccountId>,
1184		pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCommitteeCollective, 1, 1>,
1185	>;
1186
1187	/// This origin can blacklist proposals.
1188	type BlacklistOrigin = EnsureRoot<AccountId>;
1189
1190	/// Any single technical committee member may veto a coming council proposal, however they can
1191	/// only do it once and it lasts only for the cool-off period.
1192	type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCommitteeCollective>;
1193}
1194
1195parameter_types! {
1196	pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating();
1197	pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS;
1198	pub const MaxSpending : Balance = 100_000_000 * UNITS;
1199}
1200
1201// See https://paritytech.github.io/substrate/master/pallet_treasury/index.html for
1202// the descriptions of these configs.
1203impl pallet_treasury::Config for Runtime {
1204	/// Treasury Account: 5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z
1205	type PalletId = TreasuryPalletId;
1206	type Currency = Balances;
1207	type RuntimeEvent = RuntimeEvent;
1208	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;
1209
1210	/// Who approves treasury proposals?
1211	/// - Root (sudo or governance)
1212	/// - 3/5ths of the Frequency Council
1213	type ApproveOrigin = EitherOfDiverse<
1214		EnsureRoot<AccountId>,
1215		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 3, 5>,
1216	>;
1217
1218	/// Who rejects treasury proposals?
1219	/// - Root (sudo or governance)
1220	/// - Simple majority of the Frequency Council
1221	type RejectOrigin = EitherOfDiverse<
1222		EnsureRoot<AccountId>,
1223		pallet_collective::EnsureProportionMoreThan<AccountId, CouncilCollective, 1, 2>,
1224	>;
1225
1226	/// Spending funds outside of the proposal?
1227	/// Nobody
1228	#[cfg(not(feature = "runtime-benchmarks"))]
1229	type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>;
1230	#[cfg(feature = "runtime-benchmarks")]
1231	type SpendOrigin = MapSuccess<EnsureSigned<AccountId>, Replace<MaxSpending>>;
1232
1233	/// Rejected proposals lose their bond
1234	/// This takes the slashed amount and is often set to the Treasury
1235	/// We burn it so there is no incentive to the treasury to reject to enrich itself
1236	type OnSlash = ();
1237
1238	/// Bond 5% of a treasury proposal
1239	type ProposalBond = ProposalBondPercent;
1240
1241	/// Minimum bond of 100 Tokens
1242	type ProposalBondMinimum = ProposalBondMinimum;
1243
1244	/// Max bond of 1_000 Tokens
1245	type ProposalBondMaximum = ProposalBondMaximum;
1246
1247	/// Pay out on a 4-week basis
1248	type SpendPeriod = SpendPeriod;
1249
1250	/// Do not burn any unused funds
1251	type Burn = ();
1252
1253	/// Where should tokens burned from the treasury go?
1254	/// Set to go to /dev/null
1255	type BurnDestination = ();
1256
1257	/// Runtime hooks to external pallet using treasury to compute spend funds.
1258	/// Set to Bounties often.
1259	/// Not currently in use
1260	type SpendFunds = ();
1261
1262	/// 64
1263	type MaxApprovals = MaxApprovals;
1264
1265	type AssetKind = ();
1266	type Beneficiary = AccountId;
1267	type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
1268	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
1269	type BalanceConverter = UnityAssetBalanceConversion;
1270	type PayoutPeriod = PayoutSpendPeriod;
1271	#[cfg(feature = "runtime-benchmarks")]
1272	type BenchmarkHelper = ();
1273}
1274
1275// See https://paritytech.github.io/substrate/master/pallet_transaction_payment/index.html for
1276// the descriptions of these configs.
1277impl pallet_transaction_payment::Config for Runtime {
1278	type RuntimeEvent = RuntimeEvent;
1279	type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
1280	type WeightToFee = WeightToFee;
1281	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
1282	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
1283	type OperationalFeeMultiplier = TransactionPaymentOperationalFeeMultiplier;
1284	type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
1285}
1286
1287use crate::ethereum::EthereumCompatibleAccountIdLookup;
1288use pallet_frequency_tx_payment::Call as FrequencyPaymentCall;
1289use pallet_handles::Call as HandlesCall;
1290use pallet_messages::Call as MessagesCall;
1291use pallet_msa::Call as MsaCall;
1292use pallet_stateful_storage::Call as StatefulStorageCall;
1293
1294pub struct CapacityEligibleCalls;
1295impl GetStableWeight<RuntimeCall, Weight> for CapacityEligibleCalls {
1296	fn get_stable_weight(call: &RuntimeCall) -> Option<Weight> {
1297		use pallet_frequency_tx_payment::capacity_stable_weights::WeightInfo;
1298		match call {
1299			RuntimeCall::Msa(MsaCall::add_public_key_to_msa { .. }) => Some(
1300				capacity_stable_weights::SubstrateWeight::<Runtime>::add_public_key_to_msa()
1301			),
1302			RuntimeCall::Msa(MsaCall::create_sponsored_account_with_delegation {  add_provider_payload, .. }) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::create_sponsored_account_with_delegation(add_provider_payload.schema_ids.len() as u32)),
1303			RuntimeCall::Msa(MsaCall::grant_delegation { add_provider_payload, .. }) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::grant_delegation(add_provider_payload.schema_ids.len() as u32)),
1304			&RuntimeCall::Msa(MsaCall::add_recovery_commitment { .. }) => Some(
1305				capacity_stable_weights::SubstrateWeight::<Runtime>::add_recovery_commitment()
1306			),
1307			&RuntimeCall::Msa(MsaCall::recover_account { .. }) => Some(
1308				capacity_stable_weights::SubstrateWeight::<Runtime>::recover_account()
1309			),
1310			RuntimeCall::Messages(MessagesCall::add_ipfs_message { .. }) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::add_ipfs_message()),
1311			RuntimeCall::Messages(MessagesCall::add_onchain_message { payload, .. }) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::add_onchain_message(payload.len() as u32)),
1312			RuntimeCall::StatefulStorage(StatefulStorageCall::apply_item_actions { actions, ..}) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::apply_item_actions(StatefulStorage::sum_add_actions_bytes(actions))),
1313			RuntimeCall::StatefulStorage(StatefulStorageCall::upsert_page { payload, ..}) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::upsert_page(payload.len() as u32)),
1314			RuntimeCall::StatefulStorage(StatefulStorageCall::delete_page { .. }) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::delete_page()),
1315			RuntimeCall::StatefulStorage(StatefulStorageCall::apply_item_actions_with_signature_v2 { payload, ..}) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::apply_item_actions_with_signature(StatefulStorage::sum_add_actions_bytes(&payload.actions))),
1316            RuntimeCall::StatefulStorage(StatefulStorageCall::upsert_page_with_signature_v2 { payload, ..}) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::upsert_page_with_signature(payload.payload.len() as u32 )),
1317            RuntimeCall::StatefulStorage(StatefulStorageCall::delete_page_with_signature_v2 { .. }) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::delete_page_with_signature()),			RuntimeCall::Handles(HandlesCall::claim_handle { payload, .. }) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::claim_handle(payload.base_handle.len() as u32)),
1318			RuntimeCall::Handles(HandlesCall::change_handle { payload, .. }) => Some(capacity_stable_weights::SubstrateWeight::<Runtime>::change_handle(payload.base_handle.len() as u32)),
1319			_ => None,
1320		}
1321	}
1322
1323	fn get_inner_calls(outer_call: &RuntimeCall) -> Option<Vec<&RuntimeCall>> {
1324		match outer_call {
1325			RuntimeCall::FrequencyTxPayment(FrequencyPaymentCall::pay_with_capacity {
1326				call,
1327				..
1328			}) => Some(vec![call]),
1329			RuntimeCall::FrequencyTxPayment(
1330				FrequencyPaymentCall::pay_with_capacity_batch_all { calls, .. },
1331			) => Some(calls.iter().collect()),
1332			_ => Some(vec![outer_call]),
1333		}
1334	}
1335}
1336
1337impl pallet_frequency_tx_payment::Config for Runtime {
1338	type RuntimeEvent = RuntimeEvent;
1339	type RuntimeCall = RuntimeCall;
1340	type Capacity = Capacity;
1341	type WeightInfo = pallet_frequency_tx_payment::weights::SubstrateWeight<Runtime>;
1342	type CapacityCalls = CapacityEligibleCalls;
1343	type OnChargeCapacityTransaction = pallet_frequency_tx_payment::CapacityAdapter<Balances, Msa>;
1344	type BatchProvider = CapacityBatchProvider;
1345	type MaximumCapacityBatchLength = MaximumCapacityBatchLength;
1346	type MsaKeyProvider = Msa;
1347	type MsaCallFilter = MsaCallFilter;
1348}
1349
1350/// Configurations for passkey pallet
1351impl pallet_passkey::Config for Runtime {
1352	type RuntimeEvent = RuntimeEvent;
1353	type RuntimeCall = RuntimeCall;
1354	type WeightInfo = pallet_passkey::weights::SubstrateWeight<Runtime>;
1355	type ConvertIntoAccountId32 = ConvertInto;
1356	type PasskeyCallFilter = PasskeyCallFilter;
1357	#[cfg(feature = "runtime-benchmarks")]
1358	type Currency = Balances;
1359}
1360
1361#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
1362/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
1363/// into the relay chain.
1364const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
1365
1366#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
1367/// How many parachain blocks are processed by the relay chain per parent. Limits the
1368/// number of blocks authored per slot.
1369const BLOCK_PROCESSING_VELOCITY: u32 = 1;
1370#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
1371/// Relay chain slot duration, in milliseconds.
1372const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6_000;
1373
1374// See https://paritytech.github.io/substrate/master/pallet_parachain_system/index.html for
1375// the descriptions of these configs.
1376#[cfg(any(
1377	not(feature = "frequency-no-relay"),
1378	feature = "frequency-lint-check",
1379	feature = "frequency-bridging"
1380))]
1381impl cumulus_pallet_parachain_system::Config for Runtime {
1382	type RuntimeEvent = RuntimeEvent;
1383	type OnSystemEvent = ();
1384	type SelfParaId = parachain_info::Pallet<Runtime>;
1385
1386	#[cfg(feature = "frequency-bridging")]
1387	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
1388
1389	#[cfg(not(feature = "frequency-bridging"))]
1390	type DmpQueue = frame_support::traits::EnqueueWithOrigin<(), sp_core::ConstU8<0>>;
1391
1392	#[cfg(not(feature = "frequency-bridging"))]
1393	type ReservedDmpWeight = ();
1394
1395	#[cfg(feature = "frequency-bridging")]
1396	type ReservedDmpWeight = ReservedDmpWeight;
1397
1398	#[cfg(not(feature = "frequency-bridging"))]
1399	type OutboundXcmpMessageSource = ();
1400
1401	#[cfg(feature = "frequency-bridging")]
1402	type OutboundXcmpMessageSource = XcmpQueue;
1403
1404	#[cfg(not(feature = "frequency-bridging"))]
1405	type XcmpMessageHandler = ();
1406
1407	#[cfg(feature = "frequency-bridging")]
1408	type XcmpMessageHandler = XcmpQueue;
1409
1410	#[cfg(not(feature = "frequency-bridging"))]
1411	type ReservedXcmpWeight = ();
1412
1413	#[cfg(feature = "frequency-bridging")]
1414	type ReservedXcmpWeight = ReservedXcmpWeight;
1415
1416	type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
1417	type WeightInfo = ();
1418	type ConsensusHook = ConsensusHook;
1419	type SelectCore = DefaultCoreSelector<Runtime>;
1420	type RelayParentOffset = ConstU32<0>;
1421}
1422
1423#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
1424pub type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
1425	Runtime,
1426	RELAY_CHAIN_SLOT_DURATION_MILLIS,
1427	BLOCK_PROCESSING_VELOCITY,
1428	UNINCLUDED_SEGMENT_CAPACITY,
1429>;
1430
1431impl parachain_info::Config for Runtime {}
1432
1433impl cumulus_pallet_aura_ext::Config for Runtime {}
1434
1435// See https://paritytech.github.io/substrate/master/pallet_session/index.html for
1436// the descriptions of these configs.
1437impl pallet_session::Config for Runtime {
1438	type RuntimeEvent = RuntimeEvent;
1439	type ValidatorId = <Self as frame_system::Config>::AccountId;
1440	// we don't have stash and controller, thus we don't need the convert as well.
1441	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
1442	type ShouldEndSession = pallet_session::PeriodicSessions<SessionPeriod, SessionOffset>;
1443	type NextSessionRotation = pallet_session::PeriodicSessions<SessionPeriod, SessionOffset>;
1444	type SessionManager = CollatorSelection;
1445	// Essentially just Aura, but lets be pedantic.
1446	type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
1447	type Keys = SessionKeys;
1448	type DisablingStrategy = ();
1449	type WeightInfo = weights::pallet_session::SubstrateWeight<Runtime>;
1450}
1451
1452// See https://paritytech.github.io/substrate/master/pallet_aura/index.html for
1453// the descriptions of these configs.
1454impl pallet_aura::Config for Runtime {
1455	type AuthorityId = AuraId;
1456	type DisabledValidators = ();
1457	type MaxAuthorities = AuraMaxAuthorities;
1458	type AllowMultipleBlocksPerSlot = ConstBool<true>;
1459	type SlotDuration = ConstU64<SLOT_DURATION>;
1460}
1461
1462// See https://paritytech.github.io/substrate/master/pallet_collator_selection/index.html for
1463// the descriptions of these configs.
1464impl pallet_collator_selection::Config for Runtime {
1465	type RuntimeEvent = RuntimeEvent;
1466	type Currency = Balances;
1467
1468	// Origin that can dictate updating parameters of this pallet.
1469	// Currently only root or a 3/5ths council vote.
1470	type UpdateOrigin = EitherOfDiverse<
1471		EnsureRoot<AccountId>,
1472		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 3, 5>,
1473	>;
1474
1475	// Account Identifier from which the internal Pot is generated.
1476	// Set to something that NEVER gets a balance i.e. No block rewards.
1477	type PotId = NeverDepositIntoId;
1478
1479	// Maximum number of candidates that we should have. This is enforced in code.
1480	//
1481	// This does not take into account the invulnerables.
1482	type MaxCandidates = CollatorMaxCandidates;
1483
1484	// Minimum number of candidates that we should have. This is used for disaster recovery.
1485	//
1486	// This does not take into account the invulnerables.
1487	type MinEligibleCollators = CollatorMinCandidates;
1488
1489	// Maximum number of invulnerables. This is enforced in code.
1490	type MaxInvulnerables = CollatorMaxInvulnerables;
1491
1492	// Will be kicked if block is not produced in threshold.
1493	// should be a multiple of session or things will get inconsistent
1494	type KickThreshold = CollatorKickThreshold;
1495
1496	/// A stable ID for a validator.
1497	type ValidatorId = <Self as frame_system::Config>::AccountId;
1498
1499	// A conversion from account ID to validator ID.
1500	//
1501	// Its cost must be at most one storage read.
1502	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
1503
1504	// Validate a user is registered
1505	type ValidatorRegistration = Session;
1506
1507	type WeightInfo = weights::pallet_collator_selection::SubstrateWeight<Runtime>;
1508}
1509
1510// https://paritytech.github.io/polkadot-sdk/master/pallet_proxy/pallet/trait.Config.html
1511impl pallet_proxy::Config for Runtime {
1512	type RuntimeEvent = RuntimeEvent;
1513	type RuntimeCall = RuntimeCall;
1514	type Currency = Balances;
1515	type ProxyType = ProxyType;
1516	type ProxyDepositBase = ProxyDepositBase;
1517	type ProxyDepositFactor = ProxyDepositFactor;
1518	type MaxProxies = MaxProxies;
1519	type MaxPending = MaxPending;
1520	type CallHasher = BlakeTwo256;
1521	type AnnouncementDepositBase = AnnouncementDepositBase;
1522	type AnnouncementDepositFactor = AnnouncementDepositFactor;
1523	type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
1524	type BlockNumberProvider = System;
1525}
1526
1527// End Proxy Pallet Config
1528
1529impl pallet_messages::Config for Runtime {
1530	type RuntimeEvent = RuntimeEvent;
1531	type WeightInfo = pallet_messages::weights::SubstrateWeight<Runtime>;
1532	// The type that supplies MSA info
1533	type MsaInfoProvider = Msa;
1534	// The type that validates schema grants
1535	type SchemaGrantValidator = Msa;
1536	// The type that provides schema info
1537	type SchemaProvider = Schemas;
1538	// The maximum message payload in bytes
1539	type MessagesMaxPayloadSizeBytes = MessagesMaxPayloadSizeBytes;
1540
1541	/// A set of helper functions for benchmarking.
1542	#[cfg(feature = "runtime-benchmarks")]
1543	type MsaBenchmarkHelper = Msa;
1544	#[cfg(feature = "runtime-benchmarks")]
1545	type SchemaBenchmarkHelper = Schemas;
1546}
1547
1548impl pallet_stateful_storage::Config for Runtime {
1549	type RuntimeEvent = RuntimeEvent;
1550	type WeightInfo = pallet_stateful_storage::weights::SubstrateWeight<Runtime>;
1551	/// The maximum size of a page (in bytes) for an Itemized storage model
1552	type MaxItemizedPageSizeBytes = MaxItemizedPageSizeBytes;
1553	/// The maximum size of a page (in bytes) for a Paginated storage model
1554	type MaxPaginatedPageSizeBytes = MaxPaginatedPageSizeBytes;
1555	/// The maximum size of a single item in an itemized storage model (in bytes)
1556	type MaxItemizedBlobSizeBytes = MaxItemizedBlobSizeBytes;
1557	/// The maximum number of pages in a Paginated storage model
1558	type MaxPaginatedPageId = MaxPaginatedPageId;
1559	/// The maximum number of actions in itemized actions
1560	type MaxItemizedActionsCount = MaxItemizedActionsCount;
1561	/// The type that supplies MSA info
1562	type MsaInfoProvider = Msa;
1563	/// The type that validates schema grants
1564	type SchemaGrantValidator = Msa;
1565	/// The type that provides schema info
1566	type SchemaProvider = Schemas;
1567	/// Hasher for Child Tree keys
1568	type KeyHasher = Twox128;
1569	/// The conversion to a 32 byte AccountId
1570	type ConvertIntoAccountId32 = ConvertInto;
1571	/// The number of blocks per virtual bucket
1572	type MortalityWindowSize = StatefulMortalityWindowSize;
1573
1574	/// A set of helper functions for benchmarking.
1575	#[cfg(feature = "runtime-benchmarks")]
1576	type MsaBenchmarkHelper = Msa;
1577	#[cfg(feature = "runtime-benchmarks")]
1578	type SchemaBenchmarkHelper = Schemas;
1579}
1580
1581impl pallet_handles::Config for Runtime {
1582	/// The overarching event type.
1583	type RuntimeEvent = RuntimeEvent;
1584	/// Weight information for extrinsics in this pallet.
1585	type WeightInfo = pallet_handles::weights::SubstrateWeight<Runtime>;
1586	/// The type that supplies MSA info
1587	type MsaInfoProvider = Msa;
1588	/// The minimum suffix value
1589	type HandleSuffixMin = HandleSuffixMin;
1590	/// The maximum suffix value
1591	type HandleSuffixMax = HandleSuffixMax;
1592	/// The conversion to a 32 byte AccountId
1593	type ConvertIntoAccountId32 = ConvertInto;
1594	// The number of blocks per virtual bucket
1595	type MortalityWindowSize = MSAMortalityWindowSize;
1596	/// A set of helper functions for benchmarking.
1597	#[cfg(feature = "runtime-benchmarks")]
1598	type MsaBenchmarkHelper = Msa;
1599}
1600
1601// ---------- Foreign Assets pallet configuration ----------
1602#[cfg(feature = "frequency-bridging")]
1603impl pallet_assets::Config for Runtime {
1604	type RuntimeEvent = RuntimeEvent;
1605	type Balance = Balance;
1606	type AssetId = ForeignAssetsAssetId;
1607	type AssetIdParameter = ForeignAssetsAssetId;
1608	type Currency = Balances;
1609
1610	type CreateOrigin = AsEnsureOriginWithArg<EnsureNever<AccountId>>;
1611	type ForceOrigin = EnsureRoot<AccountId>;
1612
1613	type AssetDeposit = ForeignAssetsAssetDeposit;
1614	type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
1615	type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
1616	type ApprovalDeposit = ForeignAssetsApprovalDeposit;
1617	type StringLimit = ForeignAssetsAssetsStringLimit;
1618
1619	type Freezer = ();
1620	type Extra = ();
1621	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
1622	type CallbackHandle = ();
1623	type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
1624	type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
1625
1626	#[cfg(feature = "runtime-benchmarks")]
1627	type BenchmarkHelper = xcm::xcm_config::XcmBenchmarkHelper;
1628	type Holder = ();
1629}
1630
1631// See https://paritytech.github.io/substrate/master/pallet_sudo/index.html for
1632// the descriptions of these configs.
1633#[cfg(any(not(feature = "frequency"), feature = "frequency-lint-check"))]
1634impl pallet_sudo::Config for Runtime {
1635	type RuntimeEvent = RuntimeEvent;
1636	type RuntimeCall = RuntimeCall;
1637	/// using original weights from sudo pallet
1638	type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
1639}
1640
1641// See https://paritytech.github.io/substrate/master/pallet_utility/index.html for
1642// the descriptions of these configs.
1643impl pallet_utility::Config for Runtime {
1644	type RuntimeEvent = RuntimeEvent;
1645	type RuntimeCall = RuntimeCall;
1646	type PalletsOrigin = OriginCaller;
1647	type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
1648}
1649
1650// Create the runtime by composing the FRAME pallets that were previously configured.
1651construct_runtime!(
1652	pub enum Runtime {
1653		// System support stuff.
1654		System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>} = 0,
1655		#[cfg(any(
1656			not(feature = "frequency-no-relay"),
1657			feature = "frequency-lint-check",
1658			feature = "frequency-bridging"
1659		))]
1660		ParachainSystem: cumulus_pallet_parachain_system::{ Pallet, Call, Config<T>, Storage, Inherent, Event<T> } = 1,
1661		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2,
1662		ParachainInfo: parachain_info::{Pallet, Storage, Config<T>} = 3,
1663
1664		// Sudo removed from mainnet Jan 2023
1665		#[cfg(any(not(feature = "frequency"), feature = "frequency-lint-check"))]
1666		Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T> }= 4,
1667
1668		Preimage: pallet_preimage::{Pallet, Call, Storage, Event<T>, HoldReason} = 5,
1669		Democracy: pallet_democracy::{Pallet, Call, Config<T>, Storage, Event<T> } = 6,
1670		Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T> } = 8,
1671		Utility: pallet_utility::{Pallet, Call, Event} = 9,
1672
1673		// Monetary stuff.
1674		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 10,
1675		TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event<T>} = 11,
1676
1677		// Collectives
1678		Council: pallet_collective::<Instance1>::{Pallet, Call, Config<T,I>, Storage, Event<T>, Origin<T>} = 12,
1679		TechnicalCommittee: pallet_collective::<Instance2>::{Pallet, Call, Config<T,I>, Storage, Event<T>, Origin<T>} = 13,
1680
1681		// Treasury
1682		Treasury: pallet_treasury::{Pallet, Call, Storage, Config<T>, Event<T>} = 14,
1683
1684		// Collator support. The order of these 4 are important and shall not change.
1685		Authorship: pallet_authorship::{Pallet, Storage} = 20,
1686		CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event<T>, Config<T>} = 21,
1687		Session: pallet_session::{Pallet, Call, Storage, Event<T>, Config<T>} = 22,
1688		Aura: pallet_aura::{Pallet, Storage, Config<T>} = 23,
1689		AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config<T>} = 24,
1690
1691		// Signatures
1692		Multisig: pallet_multisig::{Pallet, Call, Storage, Event<T>} = 30,
1693
1694		// FRQCY Update
1695		TimeRelease: pallet_time_release::{Pallet, Call, Storage, Event<T>, Config<T>, Origin<T>, FreezeReason, HoldReason} = 40,
1696
1697		// Allowing accounts to give permission to other accounts to dispatch types of calls from their signed origin
1698		Proxy: pallet_proxy = 43,
1699
1700		// Substrate weights
1701		WeightReclaim: cumulus_pallet_weight_reclaim::{Pallet, Storage} = 50,
1702
1703		// Frequency related pallets
1704		Msa: pallet_msa::{Pallet, Call, Storage, Event<T>} = 60,
1705		Messages: pallet_messages::{Pallet, Call, Storage, Event<T>} = 61,
1706		Schemas: pallet_schemas::{Pallet, Call, Storage, Event<T>, Config<T>} = 62,
1707		StatefulStorage: pallet_stateful_storage::{Pallet, Call, Storage, Event<T>} = 63,
1708		Capacity: pallet_capacity::{Pallet, Call, Storage, Event<T>, FreezeReason} = 64,
1709		FrequencyTxPayment: pallet_frequency_tx_payment::{Pallet, Call, Event<T>} = 65,
1710		Handles: pallet_handles::{Pallet, Call, Storage, Event<T>} = 66,
1711		Passkey: pallet_passkey::{Pallet, Call, Storage, Event<T>, ValidateUnsigned} = 67,
1712
1713		#[cfg(feature = "frequency-bridging")]
1714		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 71,
1715
1716		#[cfg(feature = "frequency-bridging")]
1717		PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin } = 72,
1718
1719		#[cfg(feature = "frequency-bridging")]
1720		CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 73,
1721
1722		#[cfg(feature = "frequency-bridging")]
1723		MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
1724
1725		#[cfg(feature = "frequency-bridging")]
1726		ForeignAssets: pallet_assets::{Pallet, Call, Storage, Event<T>} = 75,
1727	}
1728);
1729
1730#[cfg(feature = "runtime-benchmarks")]
1731mod benches {
1732	define_benchmarks!(
1733		// Substrate
1734		[frame_system, SystemBench::<Runtime>]
1735		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
1736		[cumulus_pallet_weight_reclaim, WeightReclaim]
1737		[pallet_assets, ForeignAssets]
1738		[pallet_balances, Balances]
1739		[pallet_collective, Council]
1740		[pallet_collective, TechnicalCommittee]
1741		[pallet_preimage, Preimage]
1742		[pallet_democracy, Democracy]
1743		[pallet_scheduler, Scheduler]
1744		[pallet_session, SessionBench::<Runtime>]
1745		[pallet_timestamp, Timestamp]
1746		[pallet_collator_selection, CollatorSelection]
1747		[pallet_multisig, Multisig]
1748		[pallet_utility, Utility]
1749		[pallet_proxy, Proxy]
1750		[pallet_transaction_payment, TransactionPayment]
1751		[cumulus_pallet_xcmp_queue, XcmpQueue]
1752		[pallet_message_queue, MessageQueue]
1753
1754		// Frequency
1755		[pallet_msa, Msa]
1756		[pallet_schemas, Schemas]
1757		[pallet_messages, Messages]
1758		[pallet_stateful_storage, StatefulStorage]
1759		[pallet_handles, Handles]
1760		[pallet_time_release, TimeRelease]
1761		[pallet_treasury, Treasury]
1762		[pallet_capacity, Capacity]
1763		[pallet_frequency_tx_payment, FrequencyTxPayment]
1764		[pallet_passkey, Passkey]
1765
1766		[pallet_xcm_benchmarks::fungible, XcmBalances]
1767		[pallet_xcm_benchmarks::generic, XcmGeneric]
1768	);
1769}
1770
1771#[cfg(any(
1772	not(feature = "frequency-no-relay"),
1773	feature = "frequency-lint-check",
1774	feature = "frequency-bridging"
1775))]
1776cumulus_pallet_parachain_system::register_validate_block! {
1777	Runtime = Runtime,
1778	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
1779}
1780
1781// The implementation has to be here due to the linking in the macro.
1782// It CANNOT be extracted into a separate file
1783sp_api::impl_runtime_apis! {
1784	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
1785		fn slot_duration() -> sp_consensus_aura::SlotDuration {
1786			sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
1787		}
1788
1789		fn authorities() -> Vec<AuraId> {
1790			pallet_aura::Authorities::<Runtime>::get().into_inner()
1791		}
1792	}
1793
1794	#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
1795	impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
1796		fn can_build_upon(
1797			included_hash: <Block as BlockT>::Hash,
1798			slot: cumulus_primitives_aura::Slot,
1799		) -> bool {
1800			ConsensusHook::can_build_upon(included_hash, slot)
1801		}
1802	}
1803
1804	impl sp_api::Core<Block> for Runtime {
1805		fn version() -> RuntimeVersion {
1806			VERSION
1807		}
1808
1809		fn execute_block(block: Block) {
1810			Executive::execute_block(block)
1811		}
1812
1813		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
1814			Executive::initialize_block(header)
1815		}
1816	}
1817
1818	impl sp_api::Metadata<Block> for Runtime {
1819		fn metadata() -> OpaqueMetadata {
1820			OpaqueMetadata::new(Runtime::metadata().into())
1821		}
1822
1823		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1824			Runtime::metadata_at_version(version)
1825		}
1826
1827		fn metadata_versions() -> Vec<u32> {
1828			Runtime::metadata_versions()
1829		}
1830	}
1831
1832	impl sp_block_builder::BlockBuilder<Block> for Runtime {
1833		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
1834			Executive::apply_extrinsic(extrinsic)
1835		}
1836
1837		fn finalize_block() -> <Block as BlockT>::Header {
1838			Executive::finalize_block()
1839		}
1840
1841		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
1842			data.create_extrinsics()
1843		}
1844
1845		fn check_inherents(
1846			block: Block,
1847			data: sp_inherents::InherentData,
1848		) -> sp_inherents::CheckInherentsResult {
1849			data.check_extrinsics(&block)
1850		}
1851	}
1852
1853	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1854		fn validate_transaction(
1855			source: TransactionSource,
1856			tx: <Block as BlockT>::Extrinsic,
1857			block_hash: <Block as BlockT>::Hash,
1858		) -> TransactionValidity {
1859			Executive::validate_transaction(source, tx, block_hash)
1860		}
1861	}
1862
1863	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1864		fn offchain_worker(header: &<Block as BlockT>::Header) {
1865			Executive::offchain_worker(header)
1866		}
1867	}
1868
1869	impl sp_session::SessionKeys<Block> for Runtime {
1870		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
1871			SessionKeys::generate(seed)
1872		}
1873
1874		fn decode_session_keys(
1875			encoded: Vec<u8>,
1876		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
1877			SessionKeys::decode_into_raw_public_keys(&encoded)
1878		}
1879	}
1880
1881	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1882		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1883			build_state::<RuntimeGenesisConfig>(config)
1884		}
1885
1886		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1887			get_preset::<RuntimeGenesisConfig>(id,  &crate::genesis::presets::get_preset)
1888		}
1889
1890		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1891			let mut presets = vec![];
1892
1893			#[cfg(any(
1894				feature = "frequency-no-relay",
1895				feature = "frequency-local",
1896				feature = "frequency-lint-check"
1897			))]
1898			presets.extend(
1899			vec![
1900				sp_genesis_builder::PresetId::from("development"),
1901				sp_genesis_builder::PresetId::from("frequency-local"),
1902				sp_genesis_builder::PresetId::from("frequency"),
1903				sp_genesis_builder::PresetId::from("frequency-westend-local"),
1904			]);
1905
1906
1907			#[cfg(feature = "frequency-testnet")]
1908			presets.push(sp_genesis_builder::PresetId::from("frequency-testnet"));
1909
1910			#[cfg(feature = "frequency-westend")]
1911			presets.push(sp_genesis_builder::PresetId::from("frequency-westend"));
1912
1913			#[cfg(feature = "frequency")]
1914			presets.push(sp_genesis_builder::PresetId::from("frequency"));
1915
1916			presets
1917		}
1918	}
1919
1920	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
1921		fn account_nonce(account: AccountId) -> Index {
1922			System::account_nonce(account)
1923		}
1924	}
1925
1926	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
1927	// THIS QUERY_INFO IS FAILING AFTER THE CHANGES I MADE.
1928	// TO TEST: DID THIS ACTUALLY WORK ON LOCAL BEFORE THE CHANGES?
1929	// ERROR: `Bad input data provided to query_info: Codec error`
1930		fn query_info(
1931			uxt: <Block as BlockT>::Extrinsic,
1932			len: u32,
1933		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
1934			TransactionPayment::query_info(uxt, len)
1935		}
1936		fn query_fee_details(
1937			uxt: <Block as BlockT>::Extrinsic,
1938			len: u32,
1939		) -> pallet_transaction_payment::FeeDetails<Balance> {
1940			TransactionPayment::query_fee_details(uxt, len)
1941		}
1942		fn query_weight_to_fee(weight: Weight) -> Balance {
1943			TransactionPayment::weight_to_fee(weight)
1944		}
1945		fn query_length_to_fee(len: u32) -> Balance {
1946			TransactionPayment::length_to_fee(len)
1947		}
1948	}
1949
1950	impl pallet_frequency_tx_payment_runtime_api::CapacityTransactionPaymentRuntimeApi<Block, Balance> for Runtime {
1951		fn compute_capacity_fee(
1952			uxt: <Block as BlockT>::Extrinsic,
1953			len: u32,
1954		) ->pallet_transaction_payment::FeeDetails<Balance> {
1955
1956			// if the call is wrapped in a batch, we need to get the weight of the outer call
1957			// and use that to compute the fee with the inner call's stable weight(s)
1958			let capacity_overhead_weight = match &uxt.function {
1959				RuntimeCall::FrequencyTxPayment(pallet_frequency_tx_payment::Call::pay_with_capacity { .. }) =>
1960					<() as pallet_frequency_tx_payment::WeightInfo>::pay_with_capacity(),
1961				RuntimeCall::FrequencyTxPayment(pallet_frequency_tx_payment::Call::pay_with_capacity_batch_all { calls, .. }) =>
1962					<() as pallet_frequency_tx_payment::WeightInfo>::pay_with_capacity_batch_all(calls.len() as u32),
1963				_ => {
1964					Weight::zero()
1965				}
1966			};
1967			FrequencyTxPayment::compute_capacity_fee_details(&uxt.function, &capacity_overhead_weight, len)
1968		}
1969	}
1970
1971	#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
1972	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
1973		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
1974			ParachainSystem::collect_collation_info(header)
1975		}
1976	}
1977
1978	// Frequency runtime APIs
1979	impl pallet_messages_runtime_api::MessagesRuntimeApi<Block> for Runtime {
1980		fn get_messages_by_schema_and_block(schema_id: SchemaId, schema_payload_location: PayloadLocation, block_number: BlockNumber,) ->
1981			Vec<MessageResponse> {
1982			Messages::get_messages_by_schema_and_block(schema_id, schema_payload_location, block_number)
1983		}
1984
1985		fn get_schema_by_id(schema_id: SchemaId) -> Option<SchemaResponse> {
1986			Schemas::get_schema_by_id(schema_id)
1987		}
1988	}
1989
1990	impl pallet_schemas_runtime_api::SchemasRuntimeApi<Block> for Runtime {
1991		fn get_by_schema_id(schema_id: SchemaId) -> Option<SchemaResponse> {
1992			Schemas::get_schema_by_id(schema_id)
1993		}
1994
1995		fn get_schema_versions_by_name(schema_name: Vec<u8>) -> Option<Vec<SchemaVersionResponse>> {
1996			Schemas::get_schema_versions(schema_name)
1997		}
1998	}
1999
2000	impl system_runtime_api::AdditionalRuntimeApi<Block> for Runtime {
2001		fn get_events() -> Vec<RpcEvent> {
2002			System::read_events_no_consensus().map(|e| (*e).into()).collect()
2003		}
2004	}
2005
2006	#[api_version(4)]
2007	impl pallet_msa_runtime_api::MsaRuntimeApi<Block, AccountId> for Runtime {
2008		fn has_delegation(delegator: DelegatorId, provider: ProviderId, block_number: BlockNumber, schema_id: Option<SchemaId>) -> bool {
2009			match schema_id {
2010				Some(sid) => Msa::ensure_valid_schema_grant(provider, delegator, sid, block_number).is_ok(),
2011				None => Msa::ensure_valid_delegation(provider, delegator, Some(block_number)).is_ok(),
2012			}
2013		}
2014
2015		fn get_granted_schemas_by_msa_id(delegator: DelegatorId, provider: ProviderId) -> Option<Vec<SchemaGrant<SchemaId, BlockNumber>>> {
2016			match Msa::get_granted_schemas_by_msa_id(delegator, Some(provider)) {
2017				Ok(res) => match res.into_iter().next() {
2018					Some(delegation) => Some(delegation.permissions),
2019					None => None,
2020				},
2021				_ => None,
2022			}
2023		}
2024
2025		fn get_all_granted_delegations_by_msa_id(delegator: DelegatorId) -> Vec<DelegationResponse<SchemaId, BlockNumber>> {
2026			Msa::get_granted_schemas_by_msa_id(delegator, None).unwrap_or_default()
2027		}
2028
2029		fn get_ethereum_address_for_msa_id(msa_id: MessageSourceId) -> AccountId20Response {
2030			let account_id = Msa::msa_id_to_eth_address(msa_id);
2031			let account_id_checksummed = Msa::eth_address_to_checksummed_string(&account_id);
2032			AccountId20Response { account_id, account_id_checksummed }
2033		}
2034
2035		fn validate_eth_address_for_msa(address: &H160, msa_id: MessageSourceId) -> bool {
2036			Msa::validate_eth_address_for_msa(address, msa_id)
2037		}
2038
2039		fn get_provider_application_context(provider_id: ProviderId, application_id: Option<ApplicationIndex>, locale: Option<Vec<u8>>) -> Option<ProviderApplicationContext> {
2040			Msa::get_provider_application_context(provider_id, application_id, locale)
2041		}
2042	}
2043
2044	impl pallet_stateful_storage_runtime_api::StatefulStorageRuntimeApi<Block> for Runtime {
2045		fn get_paginated_storage(msa_id: MessageSourceId, schema_id: SchemaId) -> Result<Vec<PaginatedStorageResponse>, DispatchError> {
2046			StatefulStorage::get_paginated_storage(msa_id, schema_id)
2047		}
2048
2049		fn get_itemized_storage(msa_id: MessageSourceId, schema_id: SchemaId) -> Result<ItemizedStoragePageResponse, DispatchError> {
2050			StatefulStorage::get_itemized_storage(msa_id, schema_id)
2051		}
2052	}
2053
2054	#[api_version(3)]
2055	impl pallet_handles_runtime_api::HandlesRuntimeApi<Block> for Runtime {
2056		fn get_handle_for_msa(msa_id: MessageSourceId) -> Option<HandleResponse> {
2057			Handles::get_handle_for_msa(msa_id)
2058		}
2059
2060		fn get_next_suffixes(base_handle: BaseHandle, count: u16) -> PresumptiveSuffixesResponse {
2061			Handles::get_next_suffixes(base_handle, count)
2062		}
2063
2064		fn get_msa_for_handle(display_handle: DisplayHandle) -> Option<MessageSourceId> {
2065			Handles::get_msa_id_for_handle(display_handle)
2066		}
2067		fn validate_handle(base_handle: BaseHandle) -> bool {
2068			Handles::validate_handle(base_handle.to_vec())
2069		}
2070		fn check_handle(base_handle: BaseHandle) -> CheckHandleResponse {
2071			Handles::check_handle(base_handle.to_vec())
2072		}
2073	}
2074
2075	impl pallet_capacity_runtime_api::CapacityRuntimeApi<Block, AccountId, Balance, BlockNumber> for Runtime {
2076		fn list_unclaimed_rewards(who: AccountId) -> Vec<UnclaimedRewardInfo<Balance, BlockNumber>> {
2077			match Capacity::list_unclaimed_rewards(&who) {
2078				Ok(rewards) => rewards.into_inner(),
2079				Err(_) => Vec::new(),
2080			}
2081		}
2082	}
2083
2084	#[cfg(feature = "try-runtime")]
2085	impl frame_try_runtime::TryRuntime<Block> for Runtime {
2086		fn on_runtime_upgrade(checks: UpgradeCheckSelect) -> (Weight, Weight) {
2087			log::info!("try-runtime::on_runtime_upgrade frequency.");
2088			let weight = Executive::try_runtime_upgrade(checks).unwrap();
2089			(weight, RuntimeBlockWeights::get().max_block)
2090		}
2091
2092		fn execute_block(block: Block,
2093						state_root_check: bool,
2094						signature_check: bool,
2095						try_state: TryStateSelect,
2096		) -> Weight {
2097			log::info!(
2098				target: "runtime::frequency", "try-runtime: executing block #{} ({:?}) / root checks: {:?} / sanity-checks: {:?}",
2099				block.header.number,
2100				block.header.hash(),
2101				state_root_check,
2102				try_state,
2103			);
2104			Executive::try_execute_block(block, state_root_check, signature_check, try_state).expect("try_execute_block failed")
2105		}
2106	}
2107
2108	#[cfg(feature = "runtime-benchmarks")]
2109	impl frame_benchmarking::Benchmark<Block> for Runtime {
2110		fn benchmark_metadata(extra: bool) -> (
2111			Vec<frame_benchmarking::BenchmarkList>,
2112			Vec<frame_support::traits::StorageInfo>,
2113		) {
2114			use frame_benchmarking::{BenchmarkList};
2115			use frame_support::traits::StorageInfoTrait;
2116			use frame_system_benchmarking::Pallet as SystemBench;
2117			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
2118			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
2119
2120			// This is defined once again in dispatch_benchmark, because list_benchmarks!
2121			// and add_benchmarks! are macros exported by define_benchmarks! macros and those types
2122			// are referenced in that call.
2123			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
2124			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
2125
2126			let mut list = Vec::<BenchmarkList>::new();
2127			list_benchmarks!(list, extra);
2128
2129			let storage_info = AllPalletsWithSystem::storage_info();
2130			(list, storage_info)
2131		}
2132
2133		#[allow(deprecated, non_local_definitions)]
2134		fn dispatch_benchmark(
2135			config: frame_benchmarking::BenchmarkConfig
2136		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
2137			use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
2138
2139			use frame_system_benchmarking::Pallet as SystemBench;
2140			impl frame_system_benchmarking::Config for Runtime {}
2141
2142			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
2143
2144			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
2145			impl cumulus_pallet_session_benchmarking::Config for Runtime {}
2146
2147			use frame_support::traits::{WhitelistedStorageKeys, TrackedStorageKey};
2148			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
2149
2150			#[cfg(feature = "frequency-bridging")]
2151			impl pallet_xcm_benchmarks::Config for Runtime {
2152				type XcmConfig = xcm::xcm_config::XcmConfig;
2153				type AccountIdConverter = xcm::LocationToAccountId;
2154				type DeliveryHelper = xcm::benchmarks::ParachainDeliveryHelper;
2155
2156				fn valid_destination() -> Result<xcm::benchmarks::Location, BenchmarkError> {
2157					xcm::benchmarks::create_foreign_asset_dot_on_frequency();
2158					Ok(xcm::benchmarks::AssetHubParachainLocation::get())
2159				}
2160
2161				fn worst_case_holding(_depositable_count: u32) -> xcm::benchmarks::Assets {
2162					let mut assets = xcm::benchmarks::Assets::new();
2163					assets.push(xcm::benchmarks::Asset { id: xcm::benchmarks::AssetId(xcm::benchmarks::HereLocation::get()), fun: xcm::benchmarks::Fungibility::Fungible(u128::MAX) });
2164					assets.push(xcm::benchmarks::Asset { id: xcm::benchmarks::RelayAssetId::get(), fun: xcm::benchmarks::Fungibility::Fungible(u128::MAX / 2) });
2165					assets
2166				}
2167			}
2168
2169			#[cfg(feature = "frequency-bridging")]
2170			impl pallet_xcm_benchmarks::fungible::Config for Runtime {
2171				type TransactAsset = Balances;
2172				type CheckedAccount = xcm::benchmarks::CheckAccount;
2173				type TrustedTeleporter = xcm::benchmarks::TrustedTeleporter;
2174				type TrustedReserve = xcm::benchmarks::TrustedReserve;
2175
2176				fn get_asset() -> xcm::benchmarks::Asset {
2177					xcm::benchmarks::create_foreign_asset_dot_on_frequency();
2178					xcm::benchmarks::RelayAsset::get()
2179				}
2180			}
2181
2182			#[cfg(feature = "frequency-bridging")]
2183			impl pallet_xcm_benchmarks::generic::Config for Runtime {
2184				type RuntimeCall = RuntimeCall;
2185				type TransactAsset = Balances;
2186
2187				fn worst_case_response() -> (u64, xcm::benchmarks::Response) {
2188					(0u64, xcm::benchmarks::Response::Version(Default::default()))
2189				}
2190
2191				// We do not support asset exchange on frequency
2192				fn worst_case_asset_exchange() -> Result<(xcm::benchmarks::Assets, xcm::benchmarks::Assets), BenchmarkError> {
2193					Err(BenchmarkError::Skip)
2194				}
2195
2196				// We do not support universal origin permissioning.
2197				fn universal_alias() -> Result<(xcm::benchmarks::Location, xcm::benchmarks::Junction), BenchmarkError> {
2198					Err(BenchmarkError::Skip)
2199				}
2200
2201				// We do not support transact instructions on frequency
2202				// But this helper also used to benchmark unsubscribe_version which we do support.
2203				fn transact_origin_and_runtime_call() -> Result<(xcm::benchmarks::Location, RuntimeCall), BenchmarkError> {
2204					Ok((xcm::benchmarks::RelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
2205				}
2206
2207				fn subscribe_origin() -> Result<xcm::benchmarks::Location, BenchmarkError> {
2208					Ok(xcm::benchmarks::RelayLocation::get())
2209				}
2210
2211				fn claimable_asset() -> Result<(xcm::benchmarks::Location, xcm::benchmarks::Location, xcm::benchmarks::Assets), BenchmarkError> {
2212					let origin = xcm::benchmarks::AssetHubParachainLocation::get();
2213					let assets = xcm::benchmarks::RelayAsset::get().into();
2214					let ticket = xcm::benchmarks::HereLocation::get();
2215					Ok((origin, ticket, assets))
2216				}
2217
2218				// We do not support locking and unlocking on Frequency
2219				fn unlockable_asset() -> Result<(xcm::benchmarks::Location, xcm::benchmarks::Location, xcm::benchmarks::Asset), BenchmarkError> {
2220					Err(BenchmarkError::Skip)
2221				}
2222
2223				// We do not support export message on Frequency
2224				fn export_message_origin_and_destination() -> Result<(xcm::benchmarks::Location, xcm::benchmarks::NetworkId, xcm::benchmarks::InteriorLocation), BenchmarkError> {
2225					Err(BenchmarkError::Skip)
2226				}
2227
2228				// We do not support alias origin on Frequency
2229				fn alias_origin() -> Result<(xcm::benchmarks::Location, xcm::benchmarks::Location), BenchmarkError> {
2230					Err(BenchmarkError::Skip)
2231				}
2232
2233				// We do not support worst case for trader on Frequency
2234				fn worst_case_for_trader() -> Result<(xcm::benchmarks::Asset, cumulus_primitives_core::WeightLimit), BenchmarkError> {
2235					Err(BenchmarkError::Skip)
2236				}
2237			}
2238
2239			#[cfg(feature = "frequency-bridging")]
2240			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
2241			#[cfg(feature = "frequency-bridging")]
2242			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
2243
2244
2245			let mut batches = Vec::<BenchmarkBatch>::new();
2246			let params = (&config, &whitelist);
2247			add_benchmarks!(params, batches);
2248
2249			Ok(batches)
2250		}
2251
2252
2253	}
2254
2255	#[cfg(feature = "frequency-bridging")]
2256	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
2257		fn query_acceptable_payment_assets(xcm_version: staging_xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
2258			let acceptable_assets = vec![AssetLocationId(RelayLocation::get())];
2259			PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
2260		}
2261
2262		// Frequency implementation of the query_weight_to_asset_fee function
2263		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
2264			use frame_support::weights::WeightToFee;
2265
2266			match asset.try_as::<AssetLocationId>() {
2267				Ok(asset_id) if asset_id.0 == NativeToken::get().0 => {
2268					// FRQCY/XRQCY, native token
2269					Ok(common_runtime::fee::WeightToFee::weight_to_fee(&weight))
2270				},
2271				Ok(asset_id) if asset_id.0 == RelayLocation::get() => {
2272					// DOT, WND, or KSM on the relay chain
2273					// calculate fee in DOT using Polkadot relay fee schedule
2274					let dot_fee = crate::polkadot_xcm_fee::default_fee_per_second()
2275						.saturating_mul(weight.ref_time() as u128)
2276						.saturating_div(WEIGHT_REF_TIME_PER_SECOND as u128);
2277					Ok(dot_fee)
2278				},
2279				Ok(asset_id) => {
2280					log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!");
2281					Err(XcmPaymentApiError::AssetNotFound)
2282				},
2283				Err(_) => {
2284					log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!");
2285					Err(XcmPaymentApiError::VersionedConversionFailed)
2286				}
2287			}
2288		}
2289
2290		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
2291			PolkadotXcm::query_xcm_weight(message)
2292		}
2293
2294		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
2295			PolkadotXcm::query_delivery_fees(destination, message)
2296		}
2297	}
2298
2299	#[cfg(feature = "frequency-bridging")]
2300	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
2301		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
2302			PolkadotXcm::dry_run_call::<Runtime, XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
2303		}
2304
2305		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
2306			PolkadotXcm::dry_run_xcm::<Runtime, XcmRouter, RuntimeCall, XcmConfig>(origin_location, xcm)
2307		}
2308	}
2309
2310	#[cfg(feature = "frequency-bridging")]
2311	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
2312		fn convert_location(location: VersionedLocation) -> Result<
2313			AccountId,
2314			xcm_runtime_apis::conversions::Error
2315		> {
2316			xcm_runtime_apis::conversions::LocationToAccountHelper::<
2317				AccountId,
2318				LocationToAccountId,
2319			>::convert_location(location)
2320		}
2321	}
2322
2323	#[cfg(feature = "frequency-bridging")]
2324	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
2325		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
2326			PolkadotXcm::is_trusted_reserve(asset, location)
2327		}
2328		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
2329			PolkadotXcm::is_trusted_teleporter(asset, location)
2330		}
2331	}
2332
2333	#[cfg(feature = "frequency-bridging")]
2334	impl xcm_runtime_apis::authorized_aliases::AuthorizedAliasersApi<Block> for Runtime {
2335		fn authorized_aliasers(target: VersionedLocation) -> Result<
2336			Vec<xcm_runtime_apis::authorized_aliases::OriginAliaser>,
2337			xcm_runtime_apis::authorized_aliases::Error
2338		> {
2339			PolkadotXcm::authorized_aliasers(target)
2340		}
2341		fn is_authorized_alias(origin: VersionedLocation, target: VersionedLocation) -> Result<
2342			bool,
2343			xcm_runtime_apis::authorized_aliases::Error
2344		> {
2345			PolkadotXcm::is_authorized_alias(origin, target)
2346		}
2347	}
2348}