frequency_runtime/
lib.rs

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