frequency_runtime/
lib.rs

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