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