referrerpolicy=no-referrer-when-downgrade

pallet_staking_async_parachain_runtime/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Staking Async Parachain Runtime
19
20#![cfg_attr(not(feature = "std"), no_std)]
21#![allow(non_local_definitions)]
22#![recursion_limit = "512"]
23
24// Make the WASM binary available.
25#[cfg(feature = "std")]
26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
27
28mod genesis_config_presets;
29mod weights;
30pub mod xcm_config;
31
32// Configurations for next functionality.
33mod bag_thresholds;
34pub mod governance;
35mod staking;
36
37extern crate alloc;
38
39use alloc::{vec, vec::Vec};
40use assets_common::{
41	foreign_creators::ForeignCreators,
42	local_and_foreign_assets::{LocalFromLeft, TargetFromLeft},
43	matching::{FromNetwork, FromSiblingParachain},
44	AssetIdForPoolAssets, AssetIdForPoolAssetsConvert, AssetIdForTrustBackedAssetsConvert,
45};
46use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
47use cumulus_pallet_parachain_system::{RelayNumberMonotonicallyIncreases, RelaychainDataProvider};
48use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
49use frame_support::{
50	construct_runtime, derive_impl,
51	dispatch::DispatchClass,
52	genesis_builder_helper::{build_state, get_preset},
53	ord_parameter_types, parameter_types,
54	traits::{
55		fungible,
56		fungible::HoldConsideration,
57		fungibles,
58		tokens::{imbalance::ResolveAssetTo, nonfungibles_v2::Inspect},
59		AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8,
60		ConstantStoragePrice, Equals, InstanceFilter, TransformOrigin, WithdrawReasons,
61	},
62	weights::{ConstantMultiplier, Weight, WeightToFee as _},
63	BoundedVec, PalletId,
64};
65use frame_system::{
66	limits::{BlockLength, BlockWeights},
67	EnsureRoot, EnsureSigned, EnsureSignedBy,
68};
69use governance::{pallet_custom_origins, FellowshipAdmin, GeneralAdmin, StakingAdmin, Treasurer};
70use pallet_asset_conversion_tx_payment::SwapAssetAdapter;
71use pallet_nfts::PalletFeatures;
72use pallet_nomination_pools::PoolId;
73use pallet_xcm::EnsureXcm;
74use parachains_common::{
75	impls::DealWithFees, message_queue::*, AccountId, AssetIdForTrustBackedAssets, AuraId, Balance,
76	BlockNumber, CollectionId, Hash, Header, ItemId, Nonce, Signature, AVERAGE_ON_INITIALIZE_RATIO,
77	NORMAL_DISPATCH_RATIO,
78};
79use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
80use sp_api::impl_runtime_apis;
81use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
82#[cfg(any(feature = "std", test))]
83pub use sp_runtime::BuildStorage;
84use sp_runtime::{
85	generic, impl_opaque_keys,
86	traits::{AccountIdConversion, BlakeTwo256, Block as BlockT, ConvertInto, Verify},
87	transaction_validity::{TransactionSource, TransactionValidity},
88	ApplyExtrinsicResult, Perbill, Permill, RuntimeDebug,
89};
90#[cfg(feature = "std")]
91use sp_version::NativeVersion;
92use sp_version::RuntimeVersion;
93use testnet_parachains_constants::westend::{
94	consensus::*, currency::*, fee::WeightToFee, snowbridge::EthereumNetwork, time::*,
95};
96use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
97use xcm::{
98	latest::prelude::AssetId,
99	prelude::{VersionedAsset, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm},
100};
101use xcm_config::{
102	ForeignAssetsConvertedConcreteId, LocationToAccountId, PoolAssetsConvertedConcreteId,
103	PoolAssetsPalletLocation, TrustBackedAssetsConvertedConcreteId,
104	TrustBackedAssetsPalletLocation, WestendLocation, XcmOriginToTransactDispatchOrigin,
105};
106
107#[cfg(feature = "runtime-benchmarks")]
108use frame_support::traits::PalletInfoAccess;
109
110#[cfg(feature = "runtime-benchmarks")]
111use xcm::latest::prelude::{
112	Asset, Assets as XcmAssets, Fungible, Here, InteriorLocation, Junction, Junction::*, Location,
113	NetworkId, NonFungible, Parent, ParentThen, Response, XCM_VERSION,
114};
115
116use xcm_runtime_apis::{
117	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
118	fees::Error as XcmPaymentApiError,
119};
120
121impl_opaque_keys! {
122	pub struct SessionKeys {
123		pub aura: Aura,
124	}
125}
126
127#[sp_version::runtime_version]
128pub const VERSION: RuntimeVersion = RuntimeVersion {
129	spec_name: alloc::borrow::Cow::Borrowed("staking-async-parachain"),
130	impl_name: alloc::borrow::Cow::Borrowed("staking-async-parachain"),
131	authoring_version: 1,
132	spec_version: 1_000_000,
133	impl_version: 0,
134	apis: RUNTIME_API_VERSIONS,
135	transaction_version: 16,
136	system_version: 1,
137};
138
139/// The version information used to identify this runtime when compiled natively.
140#[cfg(feature = "std")]
141pub fn native_version() -> NativeVersion {
142	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
143}
144
145type RelayChainBlockNumberProvider = RelaychainDataProvider<Runtime>;
146
147parameter_types! {
148	pub const Version: RuntimeVersion = VERSION;
149	pub RuntimeBlockLength: BlockLength =
150		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
151	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
152		.base_block(BlockExecutionWeight::get())
153		.for_class(DispatchClass::all(), |weights| {
154			weights.base_extrinsic = ExtrinsicBaseWeight::get();
155		})
156		.for_class(DispatchClass::Normal, |weights| {
157			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
158		})
159		.for_class(DispatchClass::Operational, |weights| {
160			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
161			// Operational transactions have some extra reserved space, so that they
162			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
163			weights.reserved = Some(
164				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
165			);
166		})
167		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
168		.build_or_panic();
169	pub const SS58Prefix: u8 = 42;
170}
171
172// Configure FRAME pallets to include in runtime.
173#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
174impl frame_system::Config for Runtime {
175	type BlockWeights = RuntimeBlockWeights;
176	type BlockLength = RuntimeBlockLength;
177	type AccountId = AccountId;
178	type Nonce = Nonce;
179	type Hash = Hash;
180	type Block = Block;
181	type BlockHashCount = BlockHashCount;
182	type DbWeight = RocksDbWeight;
183	type Version = Version;
184	type AccountData = pallet_balances::AccountData<Balance>;
185	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
186	type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
187	type SS58Prefix = SS58Prefix;
188	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
189	type MaxConsumers = frame_support::traits::ConstU32<16>;
190	type MultiBlockMigrator = MultiBlockMigrations;
191	type SingleBlockMigrations = Migrations;
192}
193
194impl cumulus_pallet_weight_reclaim::Config for Runtime {
195	type WeightInfo = weights::cumulus_pallet_weight_reclaim::WeightInfo<Runtime>;
196}
197
198impl pallet_timestamp::Config for Runtime {
199	/// A timestamp: milliseconds since the unix epoch.
200	type Moment = u64;
201	type OnTimestampSet = Aura;
202	type MinimumPeriod = ConstU64<0>;
203	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
204}
205
206impl pallet_authorship::Config for Runtime {
207	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
208	type EventHandler = (CollatorSelection,);
209}
210
211parameter_types! {
212	pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
213}
214
215impl pallet_balances::Config for Runtime {
216	type MaxLocks = ConstU32<50>;
217	/// The type for recording an account's balance.
218	type Balance = Balance;
219	/// The ubiquitous event type.
220	type RuntimeEvent = RuntimeEvent;
221	type DustRemoval = ();
222	type ExistentialDeposit = ExistentialDeposit;
223	type AccountStore = System;
224	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
225	type MaxReserves = ConstU32<50>;
226	type ReserveIdentifier = [u8; 8];
227	type RuntimeHoldReason = RuntimeHoldReason;
228	type RuntimeFreezeReason = RuntimeFreezeReason;
229	type FreezeIdentifier = RuntimeFreezeReason;
230	type MaxFreezes = frame_support::traits::VariantCountOf<RuntimeFreezeReason>;
231	type DoneSlashHandler = ();
232}
233
234parameter_types! {
235	/// Relay Chain `TransactionByteFee` / 10
236	pub const TransactionByteFee: Balance = MILLICENTS;
237}
238
239impl pallet_transaction_payment::Config for Runtime {
240	type RuntimeEvent = RuntimeEvent;
241	type OnChargeTransaction =
242		pallet_transaction_payment::FungibleAdapter<Balances, DealWithFees<Runtime>>;
243	type WeightToFee = WeightToFee;
244	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
245	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
246	type OperationalFeeMultiplier = ConstU8<5>;
247	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
248}
249
250parameter_types! {
251	pub const AssetDeposit: Balance = UNITS / 10; // 1 / 10 WND deposit to create asset
252	pub const AssetAccountDeposit: Balance = deposit(1, 16);
253	pub const ApprovalDeposit: Balance = EXISTENTIAL_DEPOSIT;
254	pub const AssetsStringLimit: u32 = 50;
255	/// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1)
256	// https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271
257	pub const MetadataDepositBase: Balance = deposit(1, 68);
258	pub const MetadataDepositPerByte: Balance = deposit(0, 1);
259}
260
261pub type AssetsForceOrigin = EnsureRoot<AccountId>;
262
263// Called "Trust Backed" assets because these are generally registered by some account, and users of
264// the asset assume it has some claimed backing. The pallet is called `Assets` in
265// `construct_runtime` to avoid breaking changes on storage reads.
266pub type TrustBackedAssetsInstance = pallet_assets::Instance1;
267type TrustBackedAssetsCall = pallet_assets::Call<Runtime, TrustBackedAssetsInstance>;
268impl pallet_assets::Config<TrustBackedAssetsInstance> for Runtime {
269	type RuntimeEvent = RuntimeEvent;
270	type Balance = Balance;
271	type AssetId = AssetIdForTrustBackedAssets;
272	type AssetIdParameter = codec::Compact<AssetIdForTrustBackedAssets>;
273	type Currency = Balances;
274	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
275	type ForceOrigin = AssetsForceOrigin;
276	type AssetDeposit = AssetDeposit;
277	type MetadataDepositBase = MetadataDepositBase;
278	type MetadataDepositPerByte = MetadataDepositPerByte;
279	type ApprovalDeposit = ApprovalDeposit;
280	type StringLimit = AssetsStringLimit;
281	type Holder = ();
282	type Freezer = AssetsFreezer;
283	type Extra = ();
284	type WeightInfo = weights::pallet_assets_local::WeightInfo<Runtime>;
285	type CallbackHandle = pallet_assets::AutoIncAssetId<Runtime, TrustBackedAssetsInstance>;
286	type AssetAccountDeposit = AssetAccountDeposit;
287	type RemoveItemsLimit = ConstU32<1000>;
288	#[cfg(feature = "runtime-benchmarks")]
289	type BenchmarkHelper = ();
290}
291
292// Allow Freezes for the `Assets` pallet
293pub type AssetsFreezerInstance = pallet_assets_freezer::Instance1;
294impl pallet_assets_freezer::Config<AssetsFreezerInstance> for Runtime {
295	type RuntimeFreezeReason = RuntimeFreezeReason;
296	type RuntimeEvent = RuntimeEvent;
297}
298
299parameter_types! {
300	pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon");
301	pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0);
302}
303
304ord_parameter_types! {
305	pub const AssetConversionOrigin: sp_runtime::AccountId32 =
306		AccountIdConversion::<sp_runtime::AccountId32>::into_account_truncating(&AssetConversionPalletId::get());
307}
308
309pub type PoolAssetsInstance = pallet_assets::Instance3;
310impl pallet_assets::Config<PoolAssetsInstance> for Runtime {
311	type RuntimeEvent = RuntimeEvent;
312	type Balance = Balance;
313	type RemoveItemsLimit = ConstU32<1000>;
314	type AssetId = u32;
315	type AssetIdParameter = u32;
316	type Currency = Balances;
317	type CreateOrigin =
318		AsEnsureOriginWithArg<EnsureSignedBy<AssetConversionOrigin, sp_runtime::AccountId32>>;
319	type ForceOrigin = AssetsForceOrigin;
320	type AssetDeposit = ConstU128<0>;
321	type AssetAccountDeposit = ConstU128<0>;
322	type MetadataDepositBase = ConstU128<0>;
323	type MetadataDepositPerByte = ConstU128<0>;
324	type ApprovalDeposit = ConstU128<0>;
325	type StringLimit = ConstU32<50>;
326	type Holder = ();
327	type Freezer = PoolAssetsFreezer;
328	type Extra = ();
329	type WeightInfo = weights::pallet_assets_pool::WeightInfo<Runtime>;
330	type CallbackHandle = ();
331	#[cfg(feature = "runtime-benchmarks")]
332	type BenchmarkHelper = ();
333}
334
335// Allow Freezes for the `PoolAssets` pallet
336pub type PoolAssetsFreezerInstance = pallet_assets_freezer::Instance3;
337impl pallet_assets_freezer::Config<PoolAssetsFreezerInstance> for Runtime {
338	type RuntimeFreezeReason = RuntimeFreezeReason;
339	type RuntimeEvent = RuntimeEvent;
340}
341
342/// Union fungibles implementation for `Assets` and `ForeignAssets`.
343pub type LocalAndForeignAssets = fungibles::UnionOf<
344	Assets,
345	ForeignAssets,
346	LocalFromLeft<
347		AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation, xcm::v5::Location>,
348		AssetIdForTrustBackedAssets,
349		xcm::v5::Location,
350	>,
351	xcm::v5::Location,
352	AccountId,
353>;
354
355/// Union fungibles implementation for `AssetsFreezer` and `ForeignAssetsFreezer`.
356pub type LocalAndForeignAssetsFreezer = fungibles::UnionOf<
357	AssetsFreezer,
358	ForeignAssetsFreezer,
359	LocalFromLeft<
360		AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation, xcm::v5::Location>,
361		AssetIdForTrustBackedAssets,
362		xcm::v5::Location,
363	>,
364	xcm::v5::Location,
365	AccountId,
366>;
367
368/// Union fungibles implementation for [`LocalAndForeignAssets`] and `Balances`.
369pub type NativeAndNonPoolAssets = fungible::UnionOf<
370	Balances,
371	LocalAndForeignAssets,
372	TargetFromLeft<WestendLocation, xcm::v5::Location>,
373	xcm::v5::Location,
374	AccountId,
375>;
376
377/// Union fungibles implementation for [`LocalAndForeignAssetsFreezer`] and [`Balances`].
378pub type NativeAndNonPoolAssetsFreezer = fungible::UnionOf<
379	Balances,
380	LocalAndForeignAssetsFreezer,
381	TargetFromLeft<WestendLocation, xcm::v5::Location>,
382	xcm::v5::Location,
383	AccountId,
384>;
385
386/// Union fungibles implementation for [`PoolAssets`] and [`NativeAndNonPoolAssets`].
387///
388/// NOTE: Should be kept updated to include ALL balances and assets in the runtime.
389pub type NativeAndAllAssets = fungibles::UnionOf<
390	PoolAssets,
391	NativeAndNonPoolAssets,
392	LocalFromLeft<
393		AssetIdForPoolAssetsConvert<PoolAssetsPalletLocation, xcm::v5::Location>,
394		AssetIdForPoolAssets,
395		xcm::v5::Location,
396	>,
397	xcm::v5::Location,
398	AccountId,
399>;
400
401/// Union fungibles implementation for [`PoolAssetsFreezer`] and [`NativeAndNonPoolAssetsFreezer`].
402///
403/// NOTE: Should be kept updated to include ALL balances and assets in the runtime.
404pub type NativeAndAllAssetsFreezer = fungibles::UnionOf<
405	PoolAssetsFreezer,
406	NativeAndNonPoolAssetsFreezer,
407	LocalFromLeft<
408		AssetIdForPoolAssetsConvert<PoolAssetsPalletLocation, xcm::v5::Location>,
409		AssetIdForPoolAssets,
410		xcm::v5::Location,
411	>,
412	xcm::v5::Location,
413	AccountId,
414>;
415
416pub type PoolIdToAccountId = pallet_asset_conversion::AccountIdConverter<
417	AssetConversionPalletId,
418	(xcm::v5::Location, xcm::v5::Location),
419>;
420
421impl pallet_asset_conversion::Config for Runtime {
422	type RuntimeEvent = RuntimeEvent;
423	type Balance = Balance;
424	type HigherPrecisionBalance = sp_core::U256;
425	type AssetKind = xcm::v5::Location;
426	type Assets = NativeAndNonPoolAssets;
427	type PoolId = (Self::AssetKind, Self::AssetKind);
428	type PoolLocator = pallet_asset_conversion::WithFirstAsset<
429		WestendLocation,
430		AccountId,
431		Self::AssetKind,
432		PoolIdToAccountId,
433	>;
434	type PoolAssetId = u32;
435	type PoolAssets = PoolAssets;
436	type PoolSetupFee = ConstU128<0>; // Asset class deposit fees are sufficient to prevent spam
437	type PoolSetupFeeAsset = WestendLocation;
438	type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
439	type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
440	type LPFee = ConstU32<3>;
441	type PalletId = AssetConversionPalletId;
442	type MaxSwapPathLength = ConstU32<3>;
443	type MintMinLiquidity = ConstU128<100>;
444	type WeightInfo = weights::pallet_asset_conversion::WeightInfo<Runtime>;
445	#[cfg(feature = "runtime-benchmarks")]
446	type BenchmarkHelper = assets_common::benchmarks::AssetPairFactory<
447		WestendLocation,
448		parachain_info::Pallet<Runtime>,
449		xcm_config::TrustBackedAssetsPalletIndex,
450		xcm::v5::Location,
451	>;
452}
453
454#[cfg(feature = "runtime-benchmarks")]
455pub struct PalletAssetRewardsBenchmarkHelper;
456
457#[cfg(feature = "runtime-benchmarks")]
458impl pallet_asset_rewards::benchmarking::BenchmarkHelper<xcm::v5::Location>
459	for PalletAssetRewardsBenchmarkHelper
460{
461	fn staked_asset() -> Location {
462		Location::new(
463			0,
464			[PalletInstance(<Assets as PalletInfoAccess>::index() as u8), GeneralIndex(100)],
465		)
466	}
467	fn reward_asset() -> Location {
468		Location::new(
469			0,
470			[PalletInstance(<Assets as PalletInfoAccess>::index() as u8), GeneralIndex(101)],
471		)
472	}
473}
474
475parameter_types! {
476	pub const MinVestedTransfer: Balance = 100 * CENTS;
477	pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
478		WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
479}
480
481impl pallet_vesting::Config for Runtime {
482	const MAX_VESTING_SCHEDULES: u32 = 100;
483	type BlockNumberProvider = RelayChainBlockNumberProvider;
484	type BlockNumberToBalance = ConvertInto;
485	type Currency = Balances;
486	type MinVestedTransfer = MinVestedTransfer;
487	type RuntimeEvent = RuntimeEvent;
488	type WeightInfo = weights::pallet_vesting::WeightInfo<Runtime>;
489	type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons;
490}
491
492parameter_types! {
493	pub const AssetRewardsPalletId: PalletId = PalletId(*b"py/astrd");
494	pub const RewardsPoolCreationHoldReason: RuntimeHoldReason =
495		RuntimeHoldReason::AssetRewards(pallet_asset_rewards::HoldReason::PoolCreation);
496	// 1 item, 135 bytes into the storage on pool creation.
497	pub const StakePoolCreationDeposit: Balance = deposit(1, 135);
498}
499
500impl pallet_asset_rewards::Config for Runtime {
501	type RuntimeEvent = RuntimeEvent;
502	type PalletId = AssetRewardsPalletId;
503	type Balance = Balance;
504	type Assets = NativeAndAllAssets;
505	type AssetsFreezer = NativeAndAllAssetsFreezer;
506	type AssetId = xcm::v5::Location;
507	type CreatePoolOrigin = EnsureSigned<AccountId>;
508	type RuntimeFreezeReason = RuntimeFreezeReason;
509	type Consideration = HoldConsideration<
510		AccountId,
511		Balances,
512		RewardsPoolCreationHoldReason,
513		ConstantStoragePrice<StakePoolCreationDeposit, Balance>,
514	>;
515	type WeightInfo = weights::pallet_asset_rewards::WeightInfo<Runtime>;
516	#[cfg(feature = "runtime-benchmarks")]
517	type BenchmarkHelper = PalletAssetRewardsBenchmarkHelper;
518}
519
520impl pallet_asset_conversion_ops::Config for Runtime {
521	type RuntimeEvent = RuntimeEvent;
522	type PriorAccountIdConverter = pallet_asset_conversion::AccountIdConverterNoSeed<
523		<Runtime as pallet_asset_conversion::Config>::PoolId,
524	>;
525	type AssetsRefund = <Runtime as pallet_asset_conversion::Config>::Assets;
526	type PoolAssetsRefund = <Runtime as pallet_asset_conversion::Config>::PoolAssets;
527	type PoolAssetsTeam = <Runtime as pallet_asset_conversion::Config>::PoolAssets;
528	type DepositAsset = Balances;
529	type WeightInfo = weights::pallet_asset_conversion_ops::WeightInfo<Runtime>;
530}
531
532parameter_types! {
533	// we just reuse the same deposits
534	pub const ForeignAssetsAssetDeposit: Balance = AssetDeposit::get();
535	pub const ForeignAssetsAssetAccountDeposit: Balance = AssetAccountDeposit::get();
536	pub const ForeignAssetsApprovalDeposit: Balance = ApprovalDeposit::get();
537	pub const ForeignAssetsAssetsStringLimit: u32 = AssetsStringLimit::get();
538	pub const ForeignAssetsMetadataDepositBase: Balance = MetadataDepositBase::get();
539	pub const ForeignAssetsMetadataDepositPerByte: Balance = MetadataDepositPerByte::get();
540}
541
542/// Assets managed by some foreign location. Note: we do not declare a `ForeignAssetsCall` type, as
543/// this type is used in proxy definitions. We assume that a foreign location would not want to set
544/// an individual, local account as a proxy for the issuance of their assets. This issuance should
545/// be managed by the foreign location's governance.
546pub type ForeignAssetsInstance = pallet_assets::Instance2;
547impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
548	type RuntimeEvent = RuntimeEvent;
549	type Balance = Balance;
550	type AssetId = xcm::v5::Location;
551	type AssetIdParameter = xcm::v5::Location;
552	type Currency = Balances;
553	type CreateOrigin = ForeignCreators<
554		(
555			FromSiblingParachain<parachain_info::Pallet<Runtime>, xcm::v5::Location>,
556			FromNetwork<xcm_config::UniversalLocation, EthereumNetwork, xcm::v5::Location>,
557			xcm_config::bridging::to_rococo::RococoAssetFromAssetHubRococo,
558		),
559		LocationToAccountId,
560		AccountId,
561		xcm::v5::Location,
562	>;
563	type ForceOrigin = AssetsForceOrigin;
564	type AssetDeposit = ForeignAssetsAssetDeposit;
565	type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
566	type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
567	type ApprovalDeposit = ForeignAssetsApprovalDeposit;
568	type StringLimit = ForeignAssetsAssetsStringLimit;
569	type Holder = ();
570	type Freezer = ForeignAssetsFreezer;
571	type Extra = ();
572	type WeightInfo = weights::pallet_assets_foreign::WeightInfo<Runtime>;
573	type CallbackHandle = ();
574	type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
575	type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
576	#[cfg(feature = "runtime-benchmarks")]
577	type BenchmarkHelper = xcm_config::XcmBenchmarkHelper;
578}
579
580// Allow Freezes for the `ForeignAssets` pallet
581pub type ForeignAssetsFreezerInstance = pallet_assets_freezer::Instance2;
582impl pallet_assets_freezer::Config<ForeignAssetsFreezerInstance> for Runtime {
583	type RuntimeFreezeReason = RuntimeFreezeReason;
584	type RuntimeEvent = RuntimeEvent;
585}
586
587parameter_types! {
588	// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
589	pub const DepositBase: Balance = deposit(1, 88);
590	// Additional storage item size of 32 bytes.
591	pub const DepositFactor: Balance = deposit(0, 32);
592	pub const MaxSignatories: u32 = 100;
593}
594
595impl pallet_multisig::Config for Runtime {
596	type RuntimeEvent = RuntimeEvent;
597	type RuntimeCall = RuntimeCall;
598	type Currency = Balances;
599	type DepositBase = DepositBase;
600	type DepositFactor = DepositFactor;
601	type MaxSignatories = MaxSignatories;
602	type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
603	// TODO add migration.
604	type BlockNumberProvider = RelayChainBlockNumberProvider;
605}
606
607impl pallet_utility::Config for Runtime {
608	type RuntimeEvent = RuntimeEvent;
609	type RuntimeCall = RuntimeCall;
610	type PalletsOrigin = OriginCaller;
611	type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
612}
613
614parameter_types! {
615	// One storage item; key size 32, value size 8; .
616	pub const ProxyDepositBase: Balance = deposit(1, 40);
617	// Additional storage item size of 33 bytes.
618	pub const ProxyDepositFactor: Balance = deposit(0, 33);
619	pub const MaxProxies: u16 = 32;
620	// One storage item; key size 32, value size 16
621	pub const AnnouncementDepositBase: Balance = deposit(1, 48);
622	pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
623	pub const MaxPending: u16 = 32;
624}
625
626/// The type used to represent the kinds of proxying allowed.
627#[derive(
628	Copy,
629	Clone,
630	Eq,
631	PartialEq,
632	Ord,
633	PartialOrd,
634	Encode,
635	Decode,
636	DecodeWithMemTracking,
637	RuntimeDebug,
638	MaxEncodedLen,
639	scale_info::TypeInfo,
640)]
641pub enum ProxyType {
642	/// Fully permissioned proxy. Can execute any call on behalf of _proxied_.
643	Any,
644	/// Can execute any call that does not transfer funds or assets.
645	NonTransfer,
646	/// Proxy with the ability to reject time-delay proxy announcements.
647	CancelProxy,
648	/// Assets proxy. Can execute any call from `assets`, **including asset transfers**.
649	Assets,
650	/// Owner proxy. Can execute calls related to asset ownership.
651	AssetOwner,
652	/// Asset manager. Can execute calls related to asset management.
653	AssetManager,
654	/// Collator selection proxy. Can execute calls related to collator selection mechanism.
655	Collator,
656}
657impl Default for ProxyType {
658	fn default() -> Self {
659		Self::Any
660	}
661}
662
663impl InstanceFilter<RuntimeCall> for ProxyType {
664	fn filter(&self, c: &RuntimeCall) -> bool {
665		match self {
666			ProxyType::Any => true,
667			ProxyType::NonTransfer => !matches!(
668				c,
669				RuntimeCall::Balances { .. } |
670					RuntimeCall::Assets { .. } |
671					RuntimeCall::NftFractionalization { .. } |
672					RuntimeCall::Nfts { .. } |
673					RuntimeCall::Uniques { .. }
674			),
675			ProxyType::CancelProxy => matches!(
676				c,
677				RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) |
678					RuntimeCall::Utility { .. } |
679					RuntimeCall::Multisig { .. }
680			),
681			ProxyType::Assets => {
682				matches!(
683					c,
684					RuntimeCall::Assets { .. } |
685						RuntimeCall::Utility { .. } |
686						RuntimeCall::Multisig { .. } |
687						RuntimeCall::NftFractionalization { .. } |
688						RuntimeCall::Nfts { .. } |
689						RuntimeCall::Uniques { .. }
690				)
691			},
692			ProxyType::AssetOwner => matches!(
693				c,
694				RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) |
695					RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) |
696					RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) |
697					RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) |
698					RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) |
699					RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) |
700					RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) |
701					RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) |
702					RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) |
703					RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) |
704					RuntimeCall::Nfts(pallet_nfts::Call::create { .. }) |
705					RuntimeCall::Nfts(pallet_nfts::Call::destroy { .. }) |
706					RuntimeCall::Nfts(pallet_nfts::Call::redeposit { .. }) |
707					RuntimeCall::Nfts(pallet_nfts::Call::transfer_ownership { .. }) |
708					RuntimeCall::Nfts(pallet_nfts::Call::set_team { .. }) |
709					RuntimeCall::Nfts(pallet_nfts::Call::set_collection_max_supply { .. }) |
710					RuntimeCall::Nfts(pallet_nfts::Call::lock_collection { .. }) |
711					RuntimeCall::Uniques(pallet_uniques::Call::create { .. }) |
712					RuntimeCall::Uniques(pallet_uniques::Call::destroy { .. }) |
713					RuntimeCall::Uniques(pallet_uniques::Call::transfer_ownership { .. }) |
714					RuntimeCall::Uniques(pallet_uniques::Call::set_team { .. }) |
715					RuntimeCall::Uniques(pallet_uniques::Call::set_metadata { .. }) |
716					RuntimeCall::Uniques(pallet_uniques::Call::set_attribute { .. }) |
717					RuntimeCall::Uniques(pallet_uniques::Call::set_collection_metadata { .. }) |
718					RuntimeCall::Uniques(pallet_uniques::Call::clear_metadata { .. }) |
719					RuntimeCall::Uniques(pallet_uniques::Call::clear_attribute { .. }) |
720					RuntimeCall::Uniques(pallet_uniques::Call::clear_collection_metadata { .. }) |
721					RuntimeCall::Uniques(pallet_uniques::Call::set_collection_max_supply { .. }) |
722					RuntimeCall::Utility { .. } |
723					RuntimeCall::Multisig { .. }
724			),
725			ProxyType::AssetManager => matches!(
726				c,
727				RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) |
728					RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) |
729					RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) |
730					RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) |
731					RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) |
732					RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) |
733					RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) |
734					RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) |
735					RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) |
736					RuntimeCall::Nfts(pallet_nfts::Call::force_mint { .. }) |
737					RuntimeCall::Nfts(pallet_nfts::Call::update_mint_settings { .. }) |
738					RuntimeCall::Nfts(pallet_nfts::Call::mint_pre_signed { .. }) |
739					RuntimeCall::Nfts(pallet_nfts::Call::set_attributes_pre_signed { .. }) |
740					RuntimeCall::Nfts(pallet_nfts::Call::lock_item_transfer { .. }) |
741					RuntimeCall::Nfts(pallet_nfts::Call::unlock_item_transfer { .. }) |
742					RuntimeCall::Nfts(pallet_nfts::Call::lock_item_properties { .. }) |
743					RuntimeCall::Nfts(pallet_nfts::Call::set_metadata { .. }) |
744					RuntimeCall::Nfts(pallet_nfts::Call::clear_metadata { .. }) |
745					RuntimeCall::Nfts(pallet_nfts::Call::set_collection_metadata { .. }) |
746					RuntimeCall::Nfts(pallet_nfts::Call::clear_collection_metadata { .. }) |
747					RuntimeCall::Uniques(pallet_uniques::Call::mint { .. }) |
748					RuntimeCall::Uniques(pallet_uniques::Call::burn { .. }) |
749					RuntimeCall::Uniques(pallet_uniques::Call::freeze { .. }) |
750					RuntimeCall::Uniques(pallet_uniques::Call::thaw { .. }) |
751					RuntimeCall::Uniques(pallet_uniques::Call::freeze_collection { .. }) |
752					RuntimeCall::Uniques(pallet_uniques::Call::thaw_collection { .. }) |
753					RuntimeCall::Utility { .. } |
754					RuntimeCall::Multisig { .. }
755			),
756			ProxyType::Collator => matches!(
757				c,
758				RuntimeCall::CollatorSelection { .. } |
759					RuntimeCall::Utility { .. } |
760					RuntimeCall::Multisig { .. }
761			),
762		}
763	}
764
765	fn is_superset(&self, o: &Self) -> bool {
766		match (self, o) {
767			(x, y) if x == y => true,
768			(ProxyType::Any, _) => true,
769			(_, ProxyType::Any) => false,
770			(ProxyType::Assets, ProxyType::AssetOwner) => true,
771			(ProxyType::Assets, ProxyType::AssetManager) => true,
772			(ProxyType::NonTransfer, ProxyType::Collator) => true,
773			_ => false,
774		}
775	}
776}
777
778impl pallet_proxy::Config for Runtime {
779	type RuntimeEvent = RuntimeEvent;
780	type RuntimeCall = RuntimeCall;
781	type Currency = Balances;
782	type ProxyType = ProxyType;
783	type ProxyDepositBase = ProxyDepositBase;
784	type ProxyDepositFactor = ProxyDepositFactor;
785	type MaxProxies = MaxProxies;
786	type WeightInfo = weights::pallet_proxy::WeightInfo<Runtime>;
787	type MaxPending = MaxPending;
788	type CallHasher = BlakeTwo256;
789	type AnnouncementDepositBase = AnnouncementDepositBase;
790	type AnnouncementDepositFactor = AnnouncementDepositFactor;
791	// TODO add migration.
792	type BlockNumberProvider = RelayChainBlockNumberProvider;
793}
794
795parameter_types! {
796	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
797	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
798}
799
800impl cumulus_pallet_parachain_system::Config for Runtime {
801	type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
802	type RuntimeEvent = RuntimeEvent;
803	type OnSystemEvent = ();
804	type SelfParaId = parachain_info::Pallet<Runtime>;
805	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
806	type ReservedDmpWeight = ReservedDmpWeight;
807	type OutboundXcmpMessageSource = XcmpQueue;
808	type XcmpMessageHandler = XcmpQueue;
809	type ReservedXcmpWeight = ReservedXcmpWeight;
810	type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
811	type ConsensusHook = ConsensusHook;
812	type RelayParentOffset = ConstU32<0>;
813}
814
815type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
816	Runtime,
817	RELAY_CHAIN_SLOT_DURATION_MILLIS,
818	BLOCK_PROCESSING_VELOCITY,
819	UNINCLUDED_SEGMENT_CAPACITY,
820>;
821
822impl parachain_info::Config for Runtime {}
823
824parameter_types! {
825	// TODO: note that this value is different from most system chains, and is changed here only
826	// until lazy era pruning is implemented. The actual weight of the era pruning is not huge due
827	// to the fact that deletion is not expensive in `state_version: 1`.
828	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(70) * RuntimeBlockWeights::get().max_block;
829}
830
831impl pallet_message_queue::Config for Runtime {
832	type RuntimeEvent = RuntimeEvent;
833	type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
834	#[cfg(feature = "runtime-benchmarks")]
835	type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
836		cumulus_primitives_core::AggregateMessageOrigin,
837	>;
838	#[cfg(not(feature = "runtime-benchmarks"))]
839	type MessageProcessor = xcm_builder::ProcessXcmMessage<
840		AggregateMessageOrigin,
841		xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
842		RuntimeCall,
843	>;
844	type Size = u32;
845	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
846	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
847	type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
848	type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
849	type MaxStale = sp_core::ConstU32<8>;
850	type ServiceWeight = MessageQueueServiceWeight;
851	type IdleMaxServiceWeight = MessageQueueServiceWeight;
852}
853
854impl cumulus_pallet_aura_ext::Config for Runtime {}
855
856parameter_types! {
857	/// The asset ID for the asset that we use to pay for message delivery fees.
858	pub FeeAssetId: AssetId = AssetId(xcm_config::WestendLocation::get());
859	/// The base fee for the message delivery fees.
860	pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
861}
862
863pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
864	FeeAssetId,
865	BaseDeliveryFee,
866	TransactionByteFee,
867	XcmpQueue,
868>;
869
870impl cumulus_pallet_xcmp_queue::Config for Runtime {
871	type RuntimeEvent = RuntimeEvent;
872	type ChannelInfo = ParachainSystem;
873	type VersionWrapper = PolkadotXcm;
874	// Enqueue XCMP messages from siblings for later processing.
875	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
876	type MaxInboundSuspended = ConstU32<1_000>;
877	type MaxActiveOutboundChannels = ConstU32<128>;
878	// Most on-chain HRMP channels are configured to use 102400 bytes of max message size, so we
879	// need to set the page size larger than that until we reduce the channel size on-chain.
880	type MaxPageSize = ConstU32<{ 103 * 1024 }>;
881	type ControllerOrigin = EnsureRoot<AccountId>;
882	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
883	type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
884	type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
885}
886
887impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime {
888	// This must be the same as the `ChannelInfo` from the `Config`:
889	type ChannelList = ParachainSystem;
890}
891
892parameter_types! {
893	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
894}
895
896parameter_types! {
897	pub const Period: u32 = 6 * HOURS;
898	pub const Offset: u32 = 0;
899}
900
901impl pallet_session::Config for Runtime {
902	type RuntimeEvent = RuntimeEvent;
903	type ValidatorId = <Self as frame_system::Config>::AccountId;
904	// we don't have stash and controller, thus we don't need the convert as well.
905	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
906	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
907	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
908	type SessionManager = CollatorSelection;
909	// Essentially just Aura, but let's be pedantic.
910	type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
911	type Keys = SessionKeys;
912	type DisablingStrategy = ();
913	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
914	type Currency = Balances;
915	type KeyDeposit = ();
916}
917
918impl pallet_aura::Config for Runtime {
919	type AuthorityId = AuraId;
920	type DisabledValidators = ();
921	type MaxAuthorities = ConstU32<100_000>;
922	type AllowMultipleBlocksPerSlot = ConstBool<true>;
923	type SlotDuration = ConstU64<SLOT_DURATION>;
924}
925
926parameter_types! {
927	pub const PotId: PalletId = PalletId(*b"PotStake");
928	pub const SessionLength: BlockNumber = 6 * HOURS;
929}
930
931pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
932
933impl pallet_collator_selection::Config for Runtime {
934	type RuntimeEvent = RuntimeEvent;
935	type Currency = Balances;
936	type UpdateOrigin = CollatorSelectionUpdateOrigin;
937	type PotId = PotId;
938	type MaxCandidates = ConstU32<100>;
939	type MinEligibleCollators = ConstU32<4>;
940	type MaxInvulnerables = ConstU32<20>;
941	// should be a multiple of session or things will get inconsistent
942	type KickThreshold = Period;
943	type ValidatorId = <Self as frame_system::Config>::AccountId;
944	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
945	type ValidatorRegistration = Session;
946	type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
947}
948
949parameter_types! {
950	pub StakingPot: AccountId = CollatorSelection::account_id();
951}
952
953impl pallet_asset_conversion_tx_payment::Config for Runtime {
954	type RuntimeEvent = RuntimeEvent;
955	type AssetId = xcm::v5::Location;
956	type OnChargeAssetTransaction = SwapAssetAdapter<
957		WestendLocation,
958		NativeAndNonPoolAssets,
959		AssetConversion,
960		ResolveAssetTo<StakingPot, NativeAndNonPoolAssets>,
961	>;
962	type WeightInfo = weights::pallet_asset_conversion_tx_payment::WeightInfo<Runtime>;
963	#[cfg(feature = "runtime-benchmarks")]
964	type BenchmarkHelper = AssetConversionTxHelper;
965}
966
967parameter_types! {
968	pub const UniquesCollectionDeposit: Balance = UNITS / 10; // 1 / 10 UNIT deposit to create a collection
969	pub const UniquesItemDeposit: Balance = UNITS / 1_000; // 1 / 1000 UNIT deposit to mint an item
970	pub const UniquesMetadataDepositBase: Balance = deposit(1, 129);
971	pub const UniquesAttributeDepositBase: Balance = deposit(1, 0);
972	pub const UniquesDepositPerByte: Balance = deposit(0, 1);
973}
974
975impl pallet_uniques::Config for Runtime {
976	type RuntimeEvent = RuntimeEvent;
977	type CollectionId = CollectionId;
978	type ItemId = ItemId;
979	type Currency = Balances;
980	type ForceOrigin = AssetsForceOrigin;
981	type CollectionDeposit = UniquesCollectionDeposit;
982	type ItemDeposit = UniquesItemDeposit;
983	type MetadataDepositBase = UniquesMetadataDepositBase;
984	type AttributeDepositBase = UniquesAttributeDepositBase;
985	type DepositPerByte = UniquesDepositPerByte;
986	type StringLimit = ConstU32<128>;
987	type KeyLimit = ConstU32<32>;
988	type ValueLimit = ConstU32<64>;
989	type WeightInfo = weights::pallet_uniques::WeightInfo<Runtime>;
990	#[cfg(feature = "runtime-benchmarks")]
991	type Helper = ();
992	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
993	type Locker = ();
994}
995
996parameter_types! {
997	pub const NftFractionalizationPalletId: PalletId = PalletId(*b"fraction");
998	pub NewAssetSymbol: BoundedVec<u8, AssetsStringLimit> = (*b"FRAC").to_vec().try_into().unwrap();
999	pub NewAssetName: BoundedVec<u8, AssetsStringLimit> = (*b"Frac").to_vec().try_into().unwrap();
1000}
1001
1002impl pallet_nft_fractionalization::Config for Runtime {
1003	type RuntimeEvent = RuntimeEvent;
1004	type Deposit = AssetDeposit;
1005	type Currency = Balances;
1006	type NewAssetSymbol = NewAssetSymbol;
1007	type NewAssetName = NewAssetName;
1008	type StringLimit = AssetsStringLimit;
1009	type NftCollectionId = <Self as pallet_nfts::Config>::CollectionId;
1010	type NftId = <Self as pallet_nfts::Config>::ItemId;
1011	type AssetBalance = <Self as pallet_balances::Config>::Balance;
1012	type AssetId = <Self as pallet_assets::Config<TrustBackedAssetsInstance>>::AssetId;
1013	type Assets = Assets;
1014	type Nfts = Nfts;
1015	type PalletId = NftFractionalizationPalletId;
1016	type WeightInfo = weights::pallet_nft_fractionalization::WeightInfo<Runtime>;
1017	type RuntimeHoldReason = RuntimeHoldReason;
1018	#[cfg(feature = "runtime-benchmarks")]
1019	type BenchmarkHelper = ();
1020}
1021
1022parameter_types! {
1023	pub NftsPalletFeatures: PalletFeatures = PalletFeatures::all_enabled();
1024	pub const NftsMaxDeadlineDuration: BlockNumber = 12 * 30 * DAYS;
1025	// re-use the Uniques deposits
1026	pub const NftsCollectionDeposit: Balance = UniquesCollectionDeposit::get();
1027	pub const NftsItemDeposit: Balance = UniquesItemDeposit::get();
1028	pub const NftsMetadataDepositBase: Balance = UniquesMetadataDepositBase::get();
1029	pub const NftsAttributeDepositBase: Balance = UniquesAttributeDepositBase::get();
1030	pub const NftsDepositPerByte: Balance = UniquesDepositPerByte::get();
1031}
1032
1033impl pallet_nfts::Config for Runtime {
1034	type RuntimeEvent = RuntimeEvent;
1035	type CollectionId = CollectionId;
1036	type ItemId = ItemId;
1037	type Currency = Balances;
1038	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
1039	type ForceOrigin = AssetsForceOrigin;
1040	type Locker = ();
1041	type CollectionDeposit = NftsCollectionDeposit;
1042	type ItemDeposit = NftsItemDeposit;
1043	type MetadataDepositBase = NftsMetadataDepositBase;
1044	type AttributeDepositBase = NftsAttributeDepositBase;
1045	type DepositPerByte = NftsDepositPerByte;
1046	type StringLimit = ConstU32<256>;
1047	type KeyLimit = ConstU32<64>;
1048	type ValueLimit = ConstU32<256>;
1049	type ApprovalsLimit = ConstU32<20>;
1050	type ItemAttributesApprovalsLimit = ConstU32<30>;
1051	type MaxTips = ConstU32<10>;
1052	type MaxDeadlineDuration = NftsMaxDeadlineDuration;
1053	type MaxAttributesPerCall = ConstU32<10>;
1054	type Features = NftsPalletFeatures;
1055	type OffchainSignature = Signature;
1056	type OffchainPublic = <Signature as Verify>::Signer;
1057	type WeightInfo = weights::pallet_nfts::WeightInfo<Runtime>;
1058	#[cfg(feature = "runtime-benchmarks")]
1059	type Helper = ();
1060	type BlockNumberProvider = System;
1061}
1062
1063/// XCM router instance to BridgeHub with bridging capabilities for `Rococo` global
1064/// consensus with dynamic fees and back-pressure.
1065pub type ToRococoXcmRouterInstance = pallet_xcm_bridge_hub_router::Instance1;
1066impl pallet_xcm_bridge_hub_router::Config<ToRococoXcmRouterInstance> for Runtime {
1067	type RuntimeEvent = RuntimeEvent;
1068	type WeightInfo = weights::pallet_xcm_bridge_hub_router::WeightInfo<Runtime>;
1069
1070	type UniversalLocation = xcm_config::UniversalLocation;
1071	type SiblingBridgeHubLocation = xcm_config::bridging::SiblingBridgeHub;
1072	type BridgedNetworkId = xcm_config::bridging::to_rococo::RococoNetwork;
1073	type Bridges = xcm_config::bridging::NetworkExportTable;
1074	type DestinationVersion = PolkadotXcm;
1075
1076	type BridgeHubOrigin = frame_support::traits::EitherOfDiverse<
1077		EnsureRoot<AccountId>,
1078		EnsureXcm<Equals<Self::SiblingBridgeHubLocation>>,
1079	>;
1080	type ToBridgeHubSender = XcmpQueue;
1081	type LocalXcmChannelManager =
1082		cumulus_pallet_xcmp_queue::bridging::InAndOutXcmpChannelStatusProvider<Runtime>;
1083
1084	type ByteFee = xcm_config::bridging::XcmBridgeHubRouterByteFee;
1085	type FeeAsset = xcm_config::bridging::XcmBridgeHubRouterFeeAssetId;
1086}
1087
1088parameter_types! {
1089	pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
1090}
1091
1092impl pallet_migrations::Config for Runtime {
1093	type RuntimeEvent = RuntimeEvent;
1094	#[cfg(not(feature = "runtime-benchmarks"))]
1095	type Migrations = ();
1096	// Benchmarks need mocked migrations to guarantee that they succeed.
1097	#[cfg(feature = "runtime-benchmarks")]
1098	type Migrations = pallet_migrations::mock_helpers::MockedMigrations;
1099	type CursorMaxLen = ConstU32<65_536>;
1100	type IdentifierMaxLen = ConstU32<256>;
1101	type MigrationStatusHandler = ();
1102	type FailedMigrationHandler = frame_support::migrations::FreezeChainOnFailedMigration;
1103	type MaxServiceWeight = MbmServiceWeight;
1104	type WeightInfo = weights::pallet_migrations::WeightInfo<Runtime>;
1105}
1106
1107impl pallet_sudo::Config for Runtime {
1108	type RuntimeCall = RuntimeCall;
1109	type RuntimeEvent = RuntimeEvent;
1110	type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
1111}
1112
1113impl pallet_staking_async_preset_store::Config for Runtime {}
1114
1115// Create the runtime by composing the FRAME pallets that were previously configured.
1116construct_runtime!(
1117	pub enum Runtime
1118	{
1119		// System support stuff.
1120		System: frame_system = 0,
1121		ParachainSystem: cumulus_pallet_parachain_system = 1,
1122		// RandomnessCollectiveFlip = 2 removed
1123		Timestamp: pallet_timestamp = 3,
1124		ParachainInfo: parachain_info = 4,
1125		WeightReclaim: cumulus_pallet_weight_reclaim = 5,
1126		MultiBlockMigrations: pallet_migrations = 6,
1127
1128		// Monetary stuff.
1129		Balances: pallet_balances = 10,
1130		TransactionPayment: pallet_transaction_payment = 11,
1131		// AssetTxPayment: pallet_asset_tx_payment = 12,
1132		AssetTxPayment: pallet_asset_conversion_tx_payment = 13,
1133
1134		// Collator support. the order of these 5 are important and shall not change.
1135		Authorship: pallet_authorship = 20,
1136		CollatorSelection: pallet_collator_selection = 21,
1137		Session: pallet_session = 22,
1138		Aura: pallet_aura = 23,
1139		AuraExt: cumulus_pallet_aura_ext = 24,
1140
1141		// XCM helpers.
1142		XcmpQueue: cumulus_pallet_xcmp_queue = 30,
1143		PolkadotXcm: pallet_xcm = 31,
1144		CumulusXcm: cumulus_pallet_xcm = 32,
1145		// Bridge utilities.
1146		ToRococoXcmRouter: pallet_xcm_bridge_hub_router::<Instance1> = 34,
1147		MessageQueue: pallet_message_queue = 35,
1148
1149		// Handy utilities.
1150		Utility: pallet_utility = 40,
1151		Multisig: pallet_multisig = 41,
1152		Proxy: pallet_proxy = 42,
1153
1154		// The main stage.
1155		Assets: pallet_assets::<Instance1> = 50,
1156		Uniques: pallet_uniques = 51,
1157		Nfts: pallet_nfts = 52,
1158		ForeignAssets: pallet_assets::<Instance2> = 53,
1159		NftFractionalization: pallet_nft_fractionalization = 54,
1160		PoolAssets: pallet_assets::<Instance3> = 55,
1161		AssetConversion: pallet_asset_conversion = 56,
1162
1163		AssetsFreezer: pallet_assets_freezer::<Instance1> = 57,
1164		ForeignAssetsFreezer: pallet_assets_freezer::<Instance2> = 58,
1165		PoolAssetsFreezer: pallet_assets_freezer::<Instance3> = 59,
1166
1167		AssetRewards: pallet_asset_rewards = 61,
1168
1169		StateTrieMigration: pallet_state_trie_migration = 70,
1170
1171		// Staking.
1172		Staking: pallet_staking_async = 80,
1173		NominationPools: pallet_nomination_pools = 81,
1174		FastUnstake: pallet_fast_unstake = 82,
1175		VoterList: pallet_bags_list::<Instance1> = 83,
1176		DelegatedStaking: pallet_delegated_staking = 84,
1177		StakingRcClient: pallet_staking_async_rc_client = 89,
1178
1179		// Election apparatus.
1180		MultiBlockElection: pallet_election_provider_multi_block = 85,
1181		MultiBlockElectionVerifier: pallet_election_provider_multi_block::verifier = 86,
1182		MultiBlockElectionUnsigned: pallet_election_provider_multi_block::unsigned = 87,
1183		MultiBlockElectionSigned: pallet_election_provider_multi_block::signed = 88,
1184
1185		// Governance.
1186		Preimage: pallet_preimage = 90,
1187		Scheduler: pallet_scheduler = 91,
1188		ConvictionVoting: pallet_conviction_voting = 92,
1189		Referenda: pallet_referenda = 93,
1190		Origins: pallet_custom_origins = 94,
1191		Whitelist: pallet_whitelist = 95,
1192		Treasury: pallet_treasury = 96,
1193		AssetRate: pallet_asset_rate = 97,
1194
1195		// Balances.
1196		Vesting: pallet_vesting = 100,
1197
1198		// AHN specific.
1199		Sudo: pallet_sudo = 110,
1200		PresetStore: pallet_staking_async_preset_store = 111,
1201
1202		// TODO: the pallet instance should be removed once all pools have migrated
1203		// to the new account IDs.
1204		AssetConversionMigration: pallet_asset_conversion_ops = 200,
1205	}
1206);
1207
1208/// The address format for describing accounts.
1209pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
1210/// Block type as expected by this runtime.
1211pub type Block = generic::Block<Header, UncheckedExtrinsic>;
1212/// A Block signed with a Justification
1213pub type SignedBlock = generic::SignedBlock<Block>;
1214/// BlockId type as expected by this runtime.
1215pub type BlockId = generic::BlockId<Block>;
1216/// The extension to the basic transaction logic.
1217pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
1218	Runtime,
1219	(
1220		frame_system::CheckNonZeroSender<Runtime>,
1221		frame_system::CheckSpecVersion<Runtime>,
1222		frame_system::CheckTxVersion<Runtime>,
1223		frame_system::CheckGenesis<Runtime>,
1224		frame_system::CheckEra<Runtime>,
1225		frame_system::CheckNonce<Runtime>,
1226		frame_system::CheckWeight<Runtime>,
1227		pallet_asset_conversion_tx_payment::ChargeAssetTxPayment<Runtime>,
1228		frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
1229	),
1230>;
1231
1232pub type UncheckedExtrinsic =
1233	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
1234
1235/// Migrations to apply on runtime upgrade.
1236pub type Migrations = (
1237	// permanent
1238	pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
1239);
1240
1241/// Executive: handles dispatch to the various modules.
1242pub type Executive = frame_executive::Executive<
1243	Runtime,
1244	Block,
1245	frame_system::ChainContext<Runtime>,
1246	Runtime,
1247	AllPalletsWithSystem,
1248>;
1249
1250#[cfg(feature = "runtime-benchmarks")]
1251pub struct AssetConversionTxHelper;
1252
1253#[cfg(feature = "runtime-benchmarks")]
1254impl
1255	pallet_asset_conversion_tx_payment::BenchmarkHelperTrait<
1256		AccountId,
1257		cumulus_primitives_core::Location,
1258		cumulus_primitives_core::Location,
1259	> for AssetConversionTxHelper
1260{
1261	fn create_asset_id_parameter(
1262		seed: u32,
1263	) -> (cumulus_primitives_core::Location, cumulus_primitives_core::Location) {
1264		// Use a different parachain' foreign assets pallet so that the asset is indeed foreign.
1265		let asset_id = cumulus_primitives_core::Location::new(
1266			1,
1267			[
1268				cumulus_primitives_core::Junction::Parachain(3000),
1269				cumulus_primitives_core::Junction::PalletInstance(53),
1270				cumulus_primitives_core::Junction::GeneralIndex(seed.into()),
1271			],
1272		);
1273		(asset_id.clone(), asset_id)
1274	}
1275
1276	fn setup_balances_and_pool(asset_id: cumulus_primitives_core::Location, account: AccountId) {
1277		use frame_support::{assert_ok, traits::fungibles::Mutate};
1278		assert_ok!(ForeignAssets::force_create(
1279			RuntimeOrigin::root(),
1280			asset_id.clone().into(),
1281			account.clone().into(), /* owner */
1282			true,                   /* is_sufficient */
1283			1,
1284		));
1285
1286		let lp_provider = account.clone();
1287		use frame_support::traits::Currency;
1288		let _ = Balances::deposit_creating(&lp_provider, u64::MAX.into());
1289		assert_ok!(ForeignAssets::mint_into(
1290			asset_id.clone().into(),
1291			&lp_provider,
1292			u64::MAX.into()
1293		));
1294
1295		let token_native = alloc::boxed::Box::new(cumulus_primitives_core::Location::new(
1296			1,
1297			cumulus_primitives_core::Junctions::Here,
1298		));
1299		let token_second = alloc::boxed::Box::new(asset_id);
1300
1301		assert_ok!(AssetConversion::create_pool(
1302			RuntimeOrigin::signed(lp_provider.clone()),
1303			token_native.clone(),
1304			token_second.clone()
1305		));
1306
1307		assert_ok!(AssetConversion::add_liquidity(
1308			RuntimeOrigin::signed(lp_provider.clone()),
1309			token_native,
1310			token_second,
1311			(u32::MAX / 2).into(), // 1 desired
1312			u32::MAX.into(),       // 2 desired
1313			1,                     // 1 min
1314			1,                     // 2 min
1315			lp_provider,
1316		));
1317	}
1318}
1319
1320#[cfg(feature = "runtime-benchmarks")]
1321mod benches {
1322	frame_benchmarking::define_benchmarks!(
1323		[frame_system, SystemBench::<Runtime>]
1324		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
1325		[pallet_asset_conversion_ops, AssetConversionMigration]
1326		[pallet_asset_rate, AssetRate]
1327		[pallet_assets, Local]
1328		[pallet_assets, Foreign]
1329		[pallet_assets, Pool]
1330		[pallet_asset_conversion, AssetConversion]
1331		[pallet_asset_rewards, AssetRewards]
1332		[pallet_asset_conversion_tx_payment, AssetTxPayment]
1333		[pallet_staking_async, Staking]
1334		[pallet_bags_list, VoterList]
1335		[pallet_balances, Balances]
1336		[pallet_conviction_voting, ConvictionVoting]
1337		[pallet_election_provider_multi_block, MultiBlockElection]
1338		[pallet_election_provider_multi_block_verifier, MultiBlockElectionVerifier]
1339		[pallet_election_provider_multi_block_unsigned, MultiBlockElectionUnsigned]
1340		[pallet_election_provider_multi_block_signed, MultiBlockElectionSigned]
1341		[pallet_fast_unstake, FastUnstake]
1342		[pallet_message_queue, MessageQueue]
1343		[pallet_migrations, MultiBlockMigrations]
1344		[pallet_multisig, Multisig]
1345		[pallet_nft_fractionalization, NftFractionalization]
1346		[pallet_nfts, Nfts]
1347		[pallet_proxy, Proxy]
1348		[pallet_session, SessionBench::<Runtime>]
1349		[pallet_sudo, Sudo]
1350		[pallet_uniques, Uniques]
1351		[pallet_utility, Utility]
1352		[pallet_timestamp, Timestamp]
1353		[pallet_transaction_payment, TransactionPayment]
1354		[pallet_collator_selection, CollatorSelection]
1355		[cumulus_pallet_parachain_system, ParachainSystem]
1356		[cumulus_pallet_xcmp_queue, XcmpQueue]
1357		[pallet_treasury, Treasury]
1358		[pallet_vesting, Vesting]
1359		[pallet_whitelist, Whitelist]
1360		[pallet_xcm_bridge_hub_router, ToRococo]
1361		[pallet_asset_conversion_ops, AssetConversionMigration]
1362		// XCM
1363		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
1364		// NOTE: Make sure you point to the individual modules below.
1365		[pallet_xcm_benchmarks::fungible, XcmBalances]
1366		[pallet_xcm_benchmarks::generic, XcmGeneric]
1367		[cumulus_pallet_weight_reclaim, WeightReclaim]
1368	);
1369}
1370
1371impl_runtime_apis! {
1372	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
1373		fn slot_duration() -> sp_consensus_aura::SlotDuration {
1374			sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
1375		}
1376
1377		fn authorities() -> Vec<AuraId> {
1378			pallet_aura::Authorities::<Runtime>::get().into_inner()
1379		}
1380	}
1381
1382	impl cumulus_primitives_core::RelayParentOffsetApi<Block> for Runtime {
1383		fn relay_parent_offset() -> u32 {
1384			0
1385		}
1386	}
1387
1388	impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
1389		fn can_build_upon(
1390			included_hash: <Block as BlockT>::Hash,
1391			slot: cumulus_primitives_aura::Slot,
1392		) -> bool {
1393			ConsensusHook::can_build_upon(included_hash, slot)
1394		}
1395	}
1396
1397	impl sp_api::Core<Block> for Runtime {
1398		fn version() -> RuntimeVersion {
1399			VERSION
1400		}
1401
1402		fn execute_block(block: Block) {
1403			Executive::execute_block(block)
1404		}
1405
1406		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
1407			Executive::initialize_block(header)
1408		}
1409	}
1410
1411	impl sp_api::Metadata<Block> for Runtime {
1412		fn metadata() -> OpaqueMetadata {
1413			OpaqueMetadata::new(Runtime::metadata().into())
1414		}
1415
1416		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1417			Runtime::metadata_at_version(version)
1418		}
1419
1420		fn metadata_versions() -> alloc::vec::Vec<u32> {
1421			Runtime::metadata_versions()
1422		}
1423	}
1424
1425	impl sp_block_builder::BlockBuilder<Block> for Runtime {
1426		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
1427			Executive::apply_extrinsic(extrinsic)
1428		}
1429
1430		fn finalize_block() -> <Block as BlockT>::Header {
1431			Executive::finalize_block()
1432		}
1433
1434		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
1435			data.create_extrinsics()
1436		}
1437
1438		fn check_inherents(
1439			block: Block,
1440			data: sp_inherents::InherentData,
1441		) -> sp_inherents::CheckInherentsResult {
1442			data.check_extrinsics(&block)
1443		}
1444	}
1445
1446	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1447		fn validate_transaction(
1448			source: TransactionSource,
1449			tx: <Block as BlockT>::Extrinsic,
1450			block_hash: <Block as BlockT>::Hash,
1451		) -> TransactionValidity {
1452			Executive::validate_transaction(source, tx, block_hash)
1453		}
1454	}
1455
1456	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1457		fn offchain_worker(header: &<Block as BlockT>::Header) {
1458			Executive::offchain_worker(header)
1459		}
1460	}
1461
1462	impl sp_session::SessionKeys<Block> for Runtime {
1463		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
1464			SessionKeys::generate(seed)
1465		}
1466
1467		fn decode_session_keys(
1468			encoded: Vec<u8>,
1469		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
1470			SessionKeys::decode_into_raw_public_keys(&encoded)
1471		}
1472	}
1473
1474	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
1475		fn account_nonce(account: AccountId) -> Nonce {
1476			System::account_nonce(account)
1477		}
1478	}
1479
1480	impl pallet_nfts_runtime_api::NftsApi<Block, AccountId, u32, u32> for Runtime {
1481		fn owner(collection: u32, item: u32) -> Option<AccountId> {
1482			<Nfts as Inspect<AccountId>>::owner(&collection, &item)
1483		}
1484
1485		fn collection_owner(collection: u32) -> Option<AccountId> {
1486			<Nfts as Inspect<AccountId>>::collection_owner(&collection)
1487		}
1488
1489		fn attribute(
1490			collection: u32,
1491			item: u32,
1492			key: Vec<u8>,
1493		) -> Option<Vec<u8>> {
1494			<Nfts as Inspect<AccountId>>::attribute(&collection, &item, &key)
1495		}
1496
1497		fn custom_attribute(
1498			account: AccountId,
1499			collection: u32,
1500			item: u32,
1501			key: Vec<u8>,
1502		) -> Option<Vec<u8>> {
1503			<Nfts as Inspect<AccountId>>::custom_attribute(
1504				&account,
1505				&collection,
1506				&item,
1507				&key,
1508			)
1509		}
1510
1511		fn system_attribute(
1512			collection: u32,
1513			item: Option<u32>,
1514			key: Vec<u8>,
1515		) -> Option<Vec<u8>> {
1516			<Nfts as Inspect<AccountId>>::system_attribute(&collection, item.as_ref(), &key)
1517		}
1518
1519		fn collection_attribute(collection: u32, key: Vec<u8>) -> Option<Vec<u8>> {
1520			<Nfts as Inspect<AccountId>>::collection_attribute(&collection, &key)
1521		}
1522	}
1523
1524	impl pallet_asset_conversion::AssetConversionApi<
1525		Block,
1526		Balance,
1527		xcm::v5::Location,
1528	> for Runtime
1529	{
1530		fn quote_price_exact_tokens_for_tokens(asset1: xcm::v5::Location, asset2: xcm::v5::Location, amount: Balance, include_fee: bool) -> Option<Balance> {
1531			AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee)
1532		}
1533
1534		fn quote_price_tokens_for_exact_tokens(asset1: xcm::v5::Location, asset2: xcm::v5::Location, amount: Balance, include_fee: bool) -> Option<Balance> {
1535			AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee)
1536		}
1537
1538		fn get_reserves(asset1: xcm::v5::Location, asset2: xcm::v5::Location) -> Option<(Balance, Balance)> {
1539			AssetConversion::get_reserves(asset1, asset2).ok()
1540		}
1541	}
1542
1543	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
1544		fn query_info(
1545			uxt: <Block as BlockT>::Extrinsic,
1546			len: u32,
1547		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
1548			TransactionPayment::query_info(uxt, len)
1549		}
1550		fn query_fee_details(
1551			uxt: <Block as BlockT>::Extrinsic,
1552			len: u32,
1553		) -> pallet_transaction_payment::FeeDetails<Balance> {
1554			TransactionPayment::query_fee_details(uxt, len)
1555		}
1556		fn query_weight_to_fee(weight: Weight) -> Balance {
1557			TransactionPayment::weight_to_fee(weight)
1558		}
1559		fn query_length_to_fee(length: u32) -> Balance {
1560			TransactionPayment::length_to_fee(length)
1561		}
1562	}
1563
1564	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
1565		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
1566			let native_token = xcm_config::WestendLocation::get();
1567			// We accept the native token to pay fees.
1568			let mut acceptable_assets = vec![AssetId(native_token.clone())];
1569			// We also accept all assets in a pool with the native token.
1570			acceptable_assets.extend(
1571				assets_common::PoolAdapter::<Runtime>::get_assets_in_pool_with(native_token)
1572				.map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?
1573			);
1574			PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
1575		}
1576
1577		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
1578			let native_asset = xcm_config::WestendLocation::get();
1579			let fee_in_native = WeightToFee::weight_to_fee(&weight);
1580			let latest_asset_id: Result<AssetId, ()> = asset.clone().try_into();
1581			match latest_asset_id {
1582				Ok(asset_id) if asset_id.0 == native_asset => {
1583					// for native asset
1584					Ok(fee_in_native)
1585				},
1586				Ok(asset_id) => {
1587					// Try to get current price of `asset_id` in `native_asset`.
1588					if let Ok(Some(swapped_in_native)) = assets_common::PoolAdapter::<Runtime>::quote_price_tokens_for_exact_tokens(
1589							asset_id.0.clone(),
1590							native_asset,
1591							fee_in_native,
1592							true, // We include the fee.
1593						) {
1594						Ok(swapped_in_native)
1595					} else {
1596						log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!");
1597						Err(XcmPaymentApiError::AssetNotFound)
1598					}
1599				},
1600				Err(_) => {
1601					log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!");
1602					Err(XcmPaymentApiError::VersionedConversionFailed)
1603				}
1604			}
1605		}
1606
1607		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
1608			PolkadotXcm::query_xcm_weight(message)
1609		}
1610
1611		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
1612			PolkadotXcm::query_delivery_fees(destination, message)
1613		}
1614	}
1615
1616	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
1617		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: xcm::prelude::XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1618			PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
1619		}
1620
1621		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1622			PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
1623		}
1624	}
1625
1626	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
1627		fn convert_location(location: VersionedLocation) -> Result<
1628			AccountId,
1629			xcm_runtime_apis::conversions::Error
1630		> {
1631			xcm_runtime_apis::conversions::LocationToAccountHelper::<
1632				AccountId,
1633				xcm_config::LocationToAccountId,
1634			>::convert_location(location)
1635		}
1636	}
1637
1638	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
1639		for Runtime
1640	{
1641		fn query_call_info(
1642			call: RuntimeCall,
1643			len: u32,
1644		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
1645			TransactionPayment::query_call_info(call, len)
1646		}
1647		fn query_call_fee_details(
1648			call: RuntimeCall,
1649			len: u32,
1650		) -> pallet_transaction_payment::FeeDetails<Balance> {
1651			TransactionPayment::query_call_fee_details(call, len)
1652		}
1653		fn query_weight_to_fee(weight: Weight) -> Balance {
1654			TransactionPayment::weight_to_fee(weight)
1655		}
1656		fn query_length_to_fee(length: u32) -> Balance {
1657			TransactionPayment::length_to_fee(length)
1658		}
1659	}
1660
1661	impl assets_common::runtime_api::FungiblesApi<
1662		Block,
1663		AccountId,
1664	> for Runtime
1665	{
1666		fn query_account_balances(account: AccountId) -> Result<xcm::VersionedAssets, assets_common::runtime_api::FungiblesAccessError> {
1667			use assets_common::fungible_conversion::{convert, convert_balance};
1668			Ok([
1669				// collect pallet_balance
1670				{
1671					let balance = Balances::free_balance(account.clone());
1672					if balance > 0 {
1673						vec![convert_balance::<WestendLocation, Balance>(balance)?]
1674					} else {
1675						vec![]
1676					}
1677				},
1678				// collect pallet_assets (TrustBackedAssets)
1679				convert::<_, _, _, _, TrustBackedAssetsConvertedConcreteId>(
1680					Assets::account_balances(account.clone())
1681						.iter()
1682						.filter(|(_, balance)| balance > &0)
1683				)?,
1684				// collect pallet_assets (ForeignAssets)
1685				convert::<_, _, _, _, ForeignAssetsConvertedConcreteId>(
1686					ForeignAssets::account_balances(account.clone())
1687						.iter()
1688						.filter(|(_, balance)| balance > &0)
1689				)?,
1690				// collect pallet_assets (PoolAssets)
1691				convert::<_, _, _, _, PoolAssetsConvertedConcreteId>(
1692					PoolAssets::account_balances(account)
1693						.iter()
1694						.filter(|(_, balance)| balance > &0)
1695				)?,
1696				// collect ... e.g. other tokens
1697			].concat().into())
1698		}
1699	}
1700
1701	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
1702		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
1703			ParachainSystem::collect_collation_info(header)
1704		}
1705	}
1706
1707	impl pallet_asset_rewards::AssetRewards<Block, Balance> for Runtime {
1708		fn pool_creation_cost() -> Balance {
1709			StakePoolCreationDeposit::get()
1710		}
1711	}
1712
1713	#[cfg(feature = "try-runtime")]
1714	impl frame_try_runtime::TryRuntime<Block> for Runtime {
1715		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1716			let weight = Executive::try_runtime_upgrade(checks).unwrap();
1717			(weight, RuntimeBlockWeights::get().max_block)
1718		}
1719
1720		fn execute_block(
1721			block: Block,
1722			state_root_check: bool,
1723			signature_check: bool,
1724			select: frame_try_runtime::TryStateSelect,
1725		) -> Weight {
1726			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
1727			// have a backtrace here.
1728			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1729		}
1730	}
1731
1732
1733	impl pallet_nomination_pools_runtime_api::NominationPoolsApi<
1734		Block,
1735		AccountId,
1736		Balance,
1737	> for Runtime {
1738		fn pending_rewards(member: AccountId) -> Balance {
1739			NominationPools::api_pending_rewards(member).unwrap_or_default()
1740		}
1741
1742		fn points_to_balance(pool_id: PoolId, points: Balance) -> Balance {
1743			NominationPools::api_points_to_balance(pool_id, points)
1744		}
1745
1746		fn balance_to_points(pool_id: PoolId, new_funds: Balance) -> Balance {
1747			NominationPools::api_balance_to_points(pool_id, new_funds)
1748		}
1749
1750		fn pool_pending_slash(pool_id: PoolId) -> Balance {
1751			NominationPools::api_pool_pending_slash(pool_id)
1752		}
1753
1754		fn member_pending_slash(member: AccountId) -> Balance {
1755			NominationPools::api_member_pending_slash(member)
1756		}
1757
1758		fn pool_needs_delegate_migration(pool_id: PoolId) -> bool {
1759			NominationPools::api_pool_needs_delegate_migration(pool_id)
1760		}
1761
1762		fn member_needs_delegate_migration(member: AccountId) -> bool {
1763			NominationPools::api_member_needs_delegate_migration(member)
1764		}
1765
1766		fn member_total_balance(member: AccountId) -> Balance {
1767			NominationPools::api_member_total_balance(member)
1768		}
1769
1770		fn pool_balance(pool_id: PoolId) -> Balance {
1771			NominationPools::api_pool_balance(pool_id)
1772		}
1773
1774		fn pool_accounts(pool_id: PoolId) -> (AccountId, AccountId) {
1775			NominationPools::api_pool_accounts(pool_id)
1776		}
1777	}
1778
1779	impl pallet_staking_async_runtime_api::StakingApi<Block, Balance, AccountId> for Runtime {
1780		fn nominations_quota(balance: Balance) -> u32 {
1781			Staking::api_nominations_quota(balance)
1782		}
1783
1784		fn eras_stakers_page_count(era: sp_staking::EraIndex, account: AccountId) -> sp_staking::Page {
1785			Staking::api_eras_stakers_page_count(era, account)
1786		}
1787
1788		fn pending_rewards(era: sp_staking::EraIndex, account: AccountId) -> bool {
1789			Staking::api_pending_rewards(era, account)
1790		}
1791	}
1792
1793	#[cfg(feature = "runtime-benchmarks")]
1794	impl frame_benchmarking::Benchmark<Block> for Runtime {
1795		fn benchmark_metadata(extra: bool) -> (
1796			Vec<frame_benchmarking::BenchmarkList>,
1797			Vec<frame_support::traits::StorageInfo>,
1798		) {
1799			use frame_benchmarking::BenchmarkList;
1800			use frame_support::traits::StorageInfoTrait;
1801			use frame_system_benchmarking::Pallet as SystemBench;
1802			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1803			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1804			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1805			use pallet_xcm_bridge_hub_router::benchmarking::Pallet as XcmBridgeHubRouterBench;
1806
1807			// This is defined once again in dispatch_benchmark, because list_benchmarks!
1808			// and add_benchmarks! are macros exported by define_benchmarks! macros and those types
1809			// are referenced in that call.
1810			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1811			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1812
1813			// Benchmark files generated for `Assets/ForeignAssets` instances are by default
1814			// `pallet_assets_assets.rs / pallet_assets_foreign_assets`, which is not really nice,
1815			// so with this redefinition we can change names to nicer:
1816			// `pallet_assets_local.rs / pallet_assets_foreign.rs`.
1817			type Local = pallet_assets::Pallet::<Runtime, TrustBackedAssetsInstance>;
1818			type Foreign = pallet_assets::Pallet::<Runtime, ForeignAssetsInstance>;
1819			type Pool = pallet_assets::Pallet::<Runtime, PoolAssetsInstance>;
1820
1821			type ToRococo = XcmBridgeHubRouterBench<Runtime, ToRococoXcmRouterInstance>;
1822
1823			let mut list = Vec::<BenchmarkList>::new();
1824			list_benchmarks!(list, extra);
1825
1826			let storage_info = AllPalletsWithSystem::storage_info();
1827			(list, storage_info)
1828		}
1829
1830		fn dispatch_benchmark(
1831			config: frame_benchmarking::BenchmarkConfig
1832		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1833			use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
1834			use sp_storage::TrackedStorageKey;
1835			use frame_system_benchmarking::Pallet as SystemBench;
1836			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1837			use xcm::prelude::WeightLimit;
1838
1839			// add a few custom keys to benchmarks.
1840			frame_benchmarking::benchmarking::add_to_whitelist(
1841				crate::staking::MaxElectingVoters::key().to_vec().into()
1842			);
1843			frame_benchmarking::benchmarking::add_to_whitelist(
1844				crate::staking::Pages::key().to_vec().into()
1845			);
1846			frame_benchmarking::benchmarking::add_to_whitelist(
1847				crate::staking::SignedPhase::key().to_vec().into()
1848			);
1849			frame_benchmarking::benchmarking::add_to_whitelist(
1850				crate::staking::UnsignedPhase::key().to_vec().into()
1851			);
1852			frame_benchmarking::benchmarking::add_to_whitelist(
1853				crate::staking::SignedValidationPhase::key().to_vec().into()
1854			);
1855
1856			impl frame_system_benchmarking::Config for Runtime {
1857				fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1858					ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1859					Ok(())
1860				}
1861
1862				fn verify_set_code() {
1863					System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1864				}
1865			}
1866
1867			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1868			impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1869
1870			parameter_types! {
1871				pub ExistentialDepositAsset: Option<Asset> = Some((
1872					WestendLocation::get(),
1873					ExistentialDeposit::get()
1874				).into());
1875				pub const RandomParaId: ParaId = ParaId::new(43211234);
1876			}
1877
1878			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1879			impl pallet_xcm::benchmarking::Config for Runtime {
1880				type DeliveryHelper = (
1881					cumulus_primitives_utility::ToParentDeliveryHelper<
1882						xcm_config::XcmConfig,
1883						ExistentialDepositAsset,
1884						xcm_config::PriceForParentDelivery,
1885					>,
1886					polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1887						xcm_config::XcmConfig,
1888						ExistentialDepositAsset,
1889						PriceForSiblingParachainDelivery,
1890						RandomParaId,
1891						ParachainSystem,
1892					>
1893				);
1894
1895				fn reachable_dest() -> Option<Location> {
1896					Some(Parent.into())
1897				}
1898
1899				fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1900					// Relay/native token can be teleported between AH and Relay.
1901					Some((
1902						Asset {
1903							fun: Fungible(ExistentialDeposit::get()),
1904							id: AssetId(Parent.into())
1905						},
1906						Parent.into(),
1907					))
1908				}
1909
1910				fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1911					Some((
1912						Asset {
1913							fun: Fungible(ExistentialDeposit::get()),
1914							id: AssetId(Parent.into())
1915						},
1916						// AH can reserve transfer native token to some random parachain.
1917						ParentThen(Parachain(RandomParaId::get().into()).into()).into(),
1918					))
1919				}
1920
1921				fn set_up_complex_asset_transfer(
1922				) -> Option<(XcmAssets, u32, Location, alloc::boxed::Box<dyn FnOnce()>)> {
1923					// Transfer to Relay some local AH asset (local-reserve-transfer) while paying
1924					// fees using teleported native token.
1925					// (We don't care that Relay doesn't accept incoming unknown AH local asset)
1926					let dest = Parent.into();
1927
1928					let fee_amount = EXISTENTIAL_DEPOSIT;
1929					let fee_asset: Asset = (Location::parent(), fee_amount).into();
1930
1931					let who = frame_benchmarking::whitelisted_caller();
1932					// Give some multiple of the existential deposit
1933					let balance = fee_amount + EXISTENTIAL_DEPOSIT * 1000;
1934					let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
1935						&who, balance,
1936					);
1937					// verify initial balance
1938					assert_eq!(Balances::free_balance(&who), balance);
1939
1940					// set up local asset
1941					let asset_amount = 10u128;
1942					let initial_asset_amount = asset_amount * 10;
1943					let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::<
1944						Runtime,
1945						pallet_assets::Instance1
1946					>(true, initial_asset_amount);
1947					let asset_location = Location::new(
1948						0,
1949						[PalletInstance(50), GeneralIndex(u32::from(asset_id).into())]
1950					);
1951					let transfer_asset: Asset = (asset_location, asset_amount).into();
1952
1953					let assets: XcmAssets = vec![fee_asset.clone(), transfer_asset].into();
1954					let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 };
1955
1956					// verify transferred successfully
1957					let verify = alloc::boxed::Box::new(move || {
1958						// verify native balance after transfer, decreased by transferred fee amount
1959						// (plus transport fees)
1960						assert!(Balances::free_balance(&who) <= balance - fee_amount);
1961						// verify asset balance decreased by exactly transferred amount
1962						assert_eq!(
1963							Assets::balance(asset_id.into(), &who),
1964							initial_asset_amount - asset_amount,
1965						);
1966					});
1967					Some((assets, fee_index as u32, dest, verify))
1968				}
1969
1970				fn get_asset() -> Asset {
1971					Asset {
1972						id: AssetId(Location::parent()),
1973						fun: Fungible(ExistentialDeposit::get()),
1974					}
1975				}
1976			}
1977
1978			use pallet_xcm_bridge_hub_router::benchmarking::{
1979				Pallet as XcmBridgeHubRouterBench,
1980				Config as XcmBridgeHubRouterConfig,
1981			};
1982
1983			impl XcmBridgeHubRouterConfig<ToRococoXcmRouterInstance> for Runtime {
1984				fn make_congested() {
1985					cumulus_pallet_xcmp_queue::bridging::suspend_channel_for_benchmarks::<Runtime>(
1986						xcm_config::bridging::SiblingBridgeHubParaId::get().into()
1987					);
1988				}
1989				fn ensure_bridged_target_destination() -> Result<Location, BenchmarkError> {
1990					ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
1991						xcm_config::bridging::SiblingBridgeHubParaId::get().into()
1992					);
1993					let bridged_asset_hub = xcm_config::bridging::to_rococo::AssetHubRococo::get();
1994					let _ = PolkadotXcm::force_xcm_version(
1995						RuntimeOrigin::root(),
1996						alloc::boxed::Box::new(bridged_asset_hub.clone()),
1997						XCM_VERSION,
1998					).map_err(|e| {
1999						log::error!(
2000							"Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}",
2001							RuntimeOrigin::root(),
2002							bridged_asset_hub,
2003							XCM_VERSION,
2004							e
2005						);
2006						BenchmarkError::Stop("XcmVersion was not stored!")
2007					})?;
2008					Ok(bridged_asset_hub)
2009				}
2010			}
2011
2012			use xcm_config::{MaxAssetsIntoHolding, WestendLocation};
2013			use pallet_xcm_benchmarks::asset_instance_from;
2014
2015			impl pallet_xcm_benchmarks::Config for Runtime {
2016				type XcmConfig = xcm_config::XcmConfig;
2017				type AccountIdConverter = xcm_config::LocationToAccountId;
2018				type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
2019					xcm_config::XcmConfig,
2020					ExistentialDepositAsset,
2021					xcm_config::PriceForParentDelivery,
2022				>;
2023				fn valid_destination() -> Result<Location, BenchmarkError> {
2024					Ok(WestendLocation::get())
2025				}
2026				fn worst_case_holding(depositable_count: u32) -> XcmAssets {
2027					// A mix of fungible, non-fungible, and concrete assets.
2028					let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count;
2029					let holding_fungibles = holding_non_fungibles - 2; // -2 for two `iter::once` bellow
2030					let fungibles_amount: u128 = 100;
2031					(0..holding_fungibles)
2032						.map(|i| {
2033							Asset {
2034								id: AssetId(GeneralIndex(i as u128).into()),
2035								fun: Fungible(fungibles_amount * (i + 1) as u128), // non-zero amount
2036							}
2037						})
2038						.chain(core::iter::once(Asset { id: AssetId(Here.into()), fun: Fungible(u128::MAX) }))
2039						.chain(core::iter::once(Asset { id: AssetId(WestendLocation::get()), fun: Fungible(1_000_000 * UNITS) }))
2040						.chain((0..holding_non_fungibles).map(|i| Asset {
2041							id: AssetId(GeneralIndex(i as u128).into()),
2042							fun: NonFungible(asset_instance_from(i)),
2043						}))
2044						.collect::<Vec<_>>()
2045						.into()
2046				}
2047			}
2048
2049			parameter_types! {
2050				pub const TrustedTeleporter: Option<(Location, Asset)> = Some((
2051					WestendLocation::get(),
2052					Asset { fun: Fungible(UNITS), id: AssetId(WestendLocation::get()) },
2053				));
2054				pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
2055				// AssetHubNextWestend trusts AssetHubRococo as reserve for ROCs
2056				pub TrustedReserve: Option<(Location, Asset)> = Some(
2057					(
2058						xcm_config::bridging::to_rococo::AssetHubRococo::get(),
2059						Asset::from((xcm_config::bridging::to_rococo::RocLocation::get(), 1000000000000 as u128))
2060					)
2061				);
2062			}
2063
2064			impl pallet_xcm_benchmarks::fungible::Config for Runtime {
2065				type TransactAsset = Balances;
2066
2067				type CheckedAccount = CheckedAccount;
2068				type TrustedTeleporter = TrustedTeleporter;
2069				type TrustedReserve = TrustedReserve;
2070
2071				fn get_asset() -> Asset {
2072					Asset {
2073						id: AssetId(WestendLocation::get()),
2074						fun: Fungible(UNITS),
2075					}
2076				}
2077			}
2078
2079			impl pallet_xcm_benchmarks::generic::Config for Runtime {
2080				type TransactAsset = Balances;
2081				type RuntimeCall = RuntimeCall;
2082
2083				fn worst_case_response() -> (u64, Response) {
2084					(0u64, Response::Version(Default::default()))
2085				}
2086
2087				fn worst_case_asset_exchange() -> Result<(XcmAssets, XcmAssets), BenchmarkError> {
2088					Err(BenchmarkError::Skip)
2089				}
2090
2091				fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
2092					xcm_config::bridging::BridgingBenchmarksHelper::prepare_universal_alias()
2093					.ok_or(BenchmarkError::Skip)
2094				}
2095
2096				fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
2097					Ok((WestendLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
2098				}
2099
2100				fn subscribe_origin() -> Result<Location, BenchmarkError> {
2101					Ok(WestendLocation::get())
2102				}
2103
2104				fn claimable_asset() -> Result<(Location, Location, XcmAssets), BenchmarkError> {
2105					let origin = WestendLocation::get();
2106					let assets: XcmAssets = (AssetId(WestendLocation::get()), 1_000 * UNITS).into();
2107					let ticket = Location { parents: 0, interior: Here };
2108					Ok((origin, ticket, assets))
2109				}
2110
2111				fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
2112					Ok((Asset {
2113						id: AssetId(WestendLocation::get()),
2114						fun: Fungible(1_000 * UNITS),
2115					}, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
2116				}
2117
2118				fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
2119					Err(BenchmarkError::Skip)
2120				}
2121
2122				fn export_message_origin_and_destination(
2123				) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
2124					Err(BenchmarkError::Skip)
2125				}
2126
2127				fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
2128					// Any location can alias to an internal location.
2129					// Here parachain 1001 aliases to an internal account.
2130					Ok((
2131						Location::new(1, [Parachain(1001)]),
2132						Location::new(1, [Parachain(1001), AccountId32 { id: [111u8; 32], network: None }]),
2133					))
2134				}
2135			}
2136
2137			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
2138			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
2139
2140			type Local = pallet_assets::Pallet::<Runtime, TrustBackedAssetsInstance>;
2141			type Foreign = pallet_assets::Pallet::<Runtime, ForeignAssetsInstance>;
2142			type Pool = pallet_assets::Pallet::<Runtime, PoolAssetsInstance>;
2143
2144			type ToRococo = XcmBridgeHubRouterBench<Runtime, ToRococoXcmRouterInstance>;
2145
2146			use frame_support::traits::WhitelistedStorageKeys;
2147			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
2148
2149			let mut batches = Vec::<BenchmarkBatch>::new();
2150			let params = (&config, &whitelist);
2151			add_benchmarks!(params, batches);
2152
2153			Ok(batches)
2154		}
2155	}
2156
2157	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
2158		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
2159			let res = build_state::<RuntimeGenesisConfig>(config);
2160			match PresetStore::preset().unwrap().as_str() {
2161				"real-s" => {
2162					log::info!(target: "runtime", "detected a real-s preset");
2163					// used for slashing, better make it faster.
2164					crate::staking::SignedPhase::set(&0);
2165					crate::staking::SignedValidationPhase::set(&0);
2166				},
2167				"real-m" => {
2168					log::info!(target: "runtime", "detected a real-m preset");
2169					crate::staking::SignedPhase::set(&0);
2170					crate::staking::SignedValidationPhase::set(&0);
2171				}
2172				"fake-dev" => {
2173					log::info!(target: "runtime", "detected a fake-dev preset");
2174					// noop, default values are for dev.
2175				},
2176				"fake-ksm" => {
2177					log::info!(target: "runtime", "detected fake-ksm preset");
2178					crate::staking::enable_ksm_preset(true);
2179				},
2180				"fake-dot" => {
2181					log::info!(target: "runtime", "detected fake-dot preset");
2182					crate::staking::enable_dot_preset(true);
2183				},
2184				_ => {
2185					panic!("Unrecognized preset to build");
2186				}
2187			}
2188
2189			res
2190		}
2191
2192		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
2193			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
2194		}
2195
2196		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
2197			genesis_config_presets::preset_names()
2198		}
2199	}
2200
2201	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
2202		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
2203			PolkadotXcm::is_trusted_reserve(asset, location)
2204		}
2205		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
2206			PolkadotXcm::is_trusted_teleporter(asset, location)
2207		}
2208	}
2209
2210	impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
2211		fn parachain_id() -> ParaId {
2212			ParachainInfo::parachain_id()
2213		}
2214	}
2215}
2216
2217cumulus_pallet_parachain_system::register_validate_block! {
2218	Runtime = Runtime,
2219	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
2220}
2221
2222parameter_types! {
2223	// The deposit configuration for the singed migration. Specially if you want to allow any signed account to do the migration (see `SignedFilter`, these deposits should be high)
2224	pub const MigrationSignedDepositPerItem: Balance = CENTS;
2225	pub const MigrationSignedDepositBase: Balance = 2_000 * CENTS;
2226	pub const MigrationMaxKeyLen: u32 = 512;
2227}
2228
2229impl pallet_state_trie_migration::Config for Runtime {
2230	type RuntimeEvent = RuntimeEvent;
2231	type Currency = Balances;
2232	type RuntimeHoldReason = RuntimeHoldReason;
2233	type SignedDepositPerItem = MigrationSignedDepositPerItem;
2234	type SignedDepositBase = MigrationSignedDepositBase;
2235	// An origin that can control the whole pallet: should be Root, or a part of your council.
2236	type ControlOrigin = frame_system::EnsureSignedBy<RootMigController, AccountId>;
2237	// specific account for the migration, can trigger the signed migrations.
2238	type SignedFilter = frame_system::EnsureSignedBy<MigController, AccountId>;
2239
2240	// Replace this with weight based on your runtime.
2241	type WeightInfo = pallet_state_trie_migration::weights::SubstrateWeight<Runtime>;
2242
2243	type MaxKeyLen = MigrationMaxKeyLen;
2244}
2245
2246frame_support::ord_parameter_types! {
2247	pub const MigController: AccountId = AccountId::from(hex_literal::hex!("8458ed39dc4b6f6c7255f7bc42be50c2967db126357c999d44e12ca7ac80dc52"));
2248	pub const RootMigController: AccountId = AccountId::from(hex_literal::hex!("8458ed39dc4b6f6c7255f7bc42be50c2967db126357c999d44e12ca7ac80dc52"));
2249}
2250
2251#[test]
2252fn ensure_key_ss58() {
2253	use frame_support::traits::SortedMembers;
2254	use sp_core::crypto::Ss58Codec;
2255	let acc =
2256		AccountId::from_ss58check("5F4EbSkZz18X36xhbsjvDNs6NuZ82HyYtq5UiJ1h9SBHJXZD").unwrap();
2257	assert_eq!(acc, MigController::sorted_members()[0]);
2258	let acc =
2259		AccountId::from_ss58check("5F4EbSkZz18X36xhbsjvDNs6NuZ82HyYtq5UiJ1h9SBHJXZD").unwrap();
2260	assert_eq!(acc, RootMigController::sorted_members()[0]);
2261}