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