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