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