Skip to main content

coretime_westend_runtime/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#![cfg_attr(not(feature = "std"), no_std)]
17// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
18#![recursion_limit = "256"]
19
20// Make the WASM binary available.
21#[cfg(feature = "std")]
22include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
23
24/// Provides the `WASM_BINARY` build with `fast-runtime` feature enabled.
25///
26/// This is for example useful for local test chains.
27#[cfg(feature = "std")]
28pub mod fast_runtime_binary {
29	include!(concat!(env!("OUT_DIR"), "/fast_runtime_binary.rs"));
30}
31
32mod coretime;
33mod genesis_config_presets;
34mod weights;
35pub mod xcm_config;
36
37extern crate alloc;
38
39use alloc::{vec, vec::Vec};
40use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
41use cumulus_pallet_parachain_system::{RelayNumberMonotonicallyIncreases, RelaychainDataProvider};
42use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
43use frame_support::{
44	construct_runtime, derive_impl,
45	dispatch::DispatchClass,
46	genesis_builder_helper::{build_state, get_preset},
47	parameter_types,
48	traits::{
49		ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, InstanceFilter, TransformOrigin,
50	},
51	weights::{ConstantMultiplier, Weight},
52	PalletId,
53};
54use frame_system::{
55	limits::{BlockLength, BlockWeights},
56	EnsureRoot,
57};
58use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
59use parachains_common::{
60	impls::DealWithFees,
61	message_queue::{NarrowOriginToSibling, ParaIdToSibling},
62	AccountId, AuraId, Balance, BlockNumber, Hash, Header, Nonce, Signature,
63	AVERAGE_ON_INITIALIZE_RATIO, NORMAL_DISPATCH_RATIO,
64};
65use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
66use sp_api::impl_runtime_apis;
67use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
68#[cfg(any(feature = "std", test))]
69pub use sp_runtime::BuildStorage;
70use sp_runtime::{
71	generic, impl_opaque_keys,
72	traits::{BlakeTwo256, Block as BlockT, BlockNumberProvider},
73	transaction_validity::{TransactionSource, TransactionValidity},
74	ApplyExtrinsicResult, Debug, DispatchError, MultiAddress, MultiSignature, MultiSigner, Perbill,
75	Percent,
76};
77use sp_session::OpaqueGeneratedSessionKeys;
78#[cfg(feature = "std")]
79use sp_version::NativeVersion;
80use sp_version::RuntimeVersion;
81use testnet_parachains_constants::westend::{
82	accumulate_forward::*, consensus::*, currency::*, dap::*, fee::WeightToFee, time::*,
83};
84use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
85use xcm::{prelude::*, Version as XcmVersion};
86use xcm_config::{
87	FellowshipLocation, GovernanceLocation, TokenRelayLocation, XcmConfig,
88	XcmOriginToTransactDispatchOrigin,
89};
90use xcm_runtime_apis::{
91	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
92	fees::Error as XcmPaymentApiError,
93};
94
95/// The address format for describing accounts.
96pub type Address = MultiAddress<AccountId, ()>;
97
98/// Block type as expected by this runtime.
99pub type Block = generic::Block<Header, UncheckedExtrinsic>;
100
101/// A Block signed with a Justification
102pub type SignedBlock = generic::SignedBlock<Block>;
103
104/// BlockId type as expected by this runtime.
105pub type BlockId = generic::BlockId<Block>;
106
107/// The TransactionExtension to the basic transaction logic.
108pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
109	Runtime,
110	(
111		frame_system::AuthorizeCall<Runtime>,
112		frame_system::CheckNonZeroSender<Runtime>,
113		frame_system::CheckSpecVersion<Runtime>,
114		frame_system::CheckTxVersion<Runtime>,
115		frame_system::CheckGenesis<Runtime>,
116		frame_system::CheckEra<Runtime>,
117		frame_system::CheckNonce<Runtime>,
118		frame_system::CheckWeight<Runtime>,
119		pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
120		frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
121	),
122>;
123
124/// Unchecked extrinsic type as expected by this runtime.
125pub type UncheckedExtrinsic =
126	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
127
128/// Migrations to apply on runtime upgrade.
129pub type Migrations = (
130	pallet_collator_selection::migration::v2::MigrationToV2<Runtime>,
131	cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4<Runtime>,
132	cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5<Runtime>,
133	cumulus_pallet_xcmp_queue::migration::v6::MigrateV5ToV6<Runtime>,
134	pallet_broker::migration::MigrateV0ToV1<Runtime>,
135	pallet_broker::migration::MigrateV1ToV2<Runtime>,
136	pallet_broker::migration::MigrateV2ToV3<Runtime>,
137	pallet_broker::migration::MigrateV3ToV4<Runtime, BrokerMigrationV4BlockConversion>,
138	pallet_session::migrations::v1::MigrateV0ToV1<
139		Runtime,
140		pallet_session::migrations::v1::InitOffenceSeverity<Runtime>,
141	>,
142	// #11705: drain residual relay-treasury XCM payouts into accumulation account.
143	// Idempotent. No further activity on the legacy `py/trsry` account is expected.
144	// Safe to remove once confirmed.
145	pallet_accumulate_and_forward::migrations::DrainLegacyTreasuryToAccumulationAccount<Runtime>,
146	// permanent
147	pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
148	cumulus_pallet_aura_ext::migration::MigrateV0ToV1<Runtime>,
149	cumulus_pallet_parachain_system::migration::Migration<Runtime>,
150);
151
152/// Executive: handles dispatch to the various modules.
153pub type Executive = frame_executive::Executive<
154	Runtime,
155	Block,
156	frame_system::ChainContext<Runtime>,
157	Runtime,
158	AllPalletsWithSystem,
159>;
160
161impl_opaque_keys! {
162	pub struct SessionKeys {
163		pub aura: Aura,
164	}
165}
166
167#[sp_version::runtime_version]
168pub const VERSION: RuntimeVersion = RuntimeVersion {
169	spec_name: alloc::borrow::Cow::Borrowed("coretime-westend"),
170	impl_name: alloc::borrow::Cow::Borrowed("coretime-westend"),
171	authoring_version: 1,
172	spec_version: 1_022_003,
173	impl_version: 0,
174	apis: RUNTIME_API_VERSIONS,
175	transaction_version: 2,
176	system_version: 1,
177};
178
179/// The version information used to identify this runtime when compiled natively.
180#[cfg(feature = "std")]
181pub fn native_version() -> NativeVersion {
182	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
183}
184
185parameter_types! {
186	pub const Version: RuntimeVersion = VERSION;
187	pub RuntimeBlockLength: BlockLength = BlockLength::builder()
188		.max_length(5 * 1024 * 1024)
189		.modify_max_length_for_class(DispatchClass::Normal, |m| {
190			*m = NORMAL_DISPATCH_RATIO * *m
191		})
192		.build();
193	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
194		.base_block(BlockExecutionWeight::get())
195		.for_class(DispatchClass::all(), |weights| {
196			weights.base_extrinsic = ExtrinsicBaseWeight::get();
197		})
198		.for_class(DispatchClass::Normal, |weights| {
199			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
200		})
201		.for_class(DispatchClass::Operational, |weights| {
202			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
203			// Operational transactions have some extra reserved space, so that they
204			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
205			weights.reserved = Some(
206				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
207			);
208		})
209		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
210		.build_or_panic();
211	pub const SS58Prefix: u8 = 42;
212}
213
214// Configure FRAME pallets to include in runtime.
215#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
216impl frame_system::Config for Runtime {
217	/// The identifier used to distinguish between accounts.
218	type AccountId = AccountId;
219	/// The nonce type for storing how many extrinsics an account has signed.
220	type Nonce = Nonce;
221	/// The type for hashing blocks and tries.
222	type Hash = Hash;
223	/// The block type.
224	type Block = Block;
225	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
226	type BlockHashCount = BlockHashCount;
227	/// Runtime version.
228	type Version = Version;
229	/// The data to be stored in an account.
230	type AccountData = pallet_balances::AccountData<Balance>;
231	/// The weight of database operations that the runtime can invoke.
232	type DbWeight = RocksDbWeight;
233	/// Weight information for the extrinsics of this pallet.
234	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
235	/// Weight information for the extensions of this pallet.
236	type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
237	/// Block & extrinsics weights: base values and limits.
238	type BlockWeights = RuntimeBlockWeights;
239	/// The maximum length of a block (in bytes).
240	type BlockLength = RuntimeBlockLength;
241	type SS58Prefix = SS58Prefix;
242	/// The action to take on a Runtime Upgrade
243	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
244	type MaxConsumers = ConstU32<16>;
245	type SingleBlockMigrations = Migrations;
246}
247
248impl cumulus_pallet_weight_reclaim::Config for Runtime {
249	type WeightInfo = weights::cumulus_pallet_weight_reclaim::WeightInfo<Runtime>;
250}
251
252impl pallet_timestamp::Config for Runtime {
253	/// A timestamp: milliseconds since the unix epoch.
254	type Moment = u64;
255	type OnTimestampSet = Aura;
256	type MinimumPeriod = ConstU64<0>;
257	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
258}
259
260impl pallet_authorship::Config for Runtime {
261	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
262	type EventHandler = (CollatorSelection,);
263}
264
265parameter_types! {
266	pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
267}
268
269impl pallet_balances::Config for Runtime {
270	type Balance = Balance;
271	type DustRemoval = AccumulateForward;
272	type RuntimeEvent = RuntimeEvent;
273	type ExistentialDeposit = ExistentialDeposit;
274	type AccountStore = System;
275	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
276	type MaxLocks = ConstU32<50>;
277	type MaxReserves = ConstU32<50>;
278	type ReserveIdentifier = [u8; 8];
279	type RuntimeHoldReason = RuntimeHoldReason;
280	type RuntimeFreezeReason = RuntimeFreezeReason;
281	type FreezeIdentifier = ();
282	type MaxFreezes = ConstU32<0>;
283	type DoneSlashHandler = ();
284}
285
286parameter_types! {
287	/// Relay Chain `TransactionByteFee` / 10
288	pub const TransactionByteFee: Balance = MILLICENTS;
289	/// Percentage of fees to send to the accumulation account.
290	pub const AccumulateForwardFeePercent: Percent = Percent::from_percent(100);
291}
292
293pub type DealWithFeesAccumulate = pallet_accumulate_and_forward::DealWithFeesSplit<
294	Runtime,
295	AccumulateForwardFeePercent,
296	DealWithFees<Runtime>,
297>;
298
299impl pallet_transaction_payment::Config for Runtime {
300	type RuntimeEvent = RuntimeEvent;
301	type OnChargeTransaction =
302		pallet_transaction_payment::FungibleAdapter<Balances, DealWithFeesAccumulate>;
303	type OperationalFeeMultiplier = ConstU8<5>;
304	type WeightToFee = WeightToFee;
305	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
306	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
307	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
308}
309
310parameter_types! {
311	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
312	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
313	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
314}
315
316impl cumulus_pallet_parachain_system::Config for Runtime {
317	type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
318	type RuntimeEvent = RuntimeEvent;
319	type OnSystemEvent = ();
320	type SelfParaId = parachain_info::Pallet<Runtime>;
321	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
322	type OutboundXcmpMessageSource = XcmpQueue;
323	type ReservedDmpWeight = ReservedDmpWeight;
324	type XcmpMessageHandler = XcmpQueue;
325	type ReservedXcmpWeight = ReservedXcmpWeight;
326	type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
327	type ConsensusHook = ConsensusHook;
328	type RelayParentOffset = ConstU32<0>;
329}
330
331type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
332	Runtime,
333	RELAY_CHAIN_SLOT_DURATION_MILLIS,
334	BLOCK_PROCESSING_VELOCITY,
335	UNINCLUDED_SEGMENT_CAPACITY,
336>;
337
338parameter_types! {
339	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block;
340}
341
342impl pallet_message_queue::Config for Runtime {
343	type RuntimeEvent = RuntimeEvent;
344	type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
345	#[cfg(feature = "runtime-benchmarks")]
346	type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
347		cumulus_primitives_core::AggregateMessageOrigin,
348	>;
349	#[cfg(not(feature = "runtime-benchmarks"))]
350	type MessageProcessor = xcm_builder::ProcessXcmMessage<
351		AggregateMessageOrigin,
352		xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
353		RuntimeCall,
354	>;
355	type Size = u32;
356	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
357	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
358	type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
359	type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
360	type MaxStale = sp_core::ConstU32<8>;
361	type ServiceWeight = MessageQueueServiceWeight;
362	type IdleMaxServiceWeight = MessageQueueServiceWeight;
363}
364
365impl parachain_info::Config for Runtime {}
366
367impl cumulus_pallet_aura_ext::Config for Runtime {}
368
369parameter_types! {
370	/// Fellows pluralistic body.
371	pub const FellowsBodyId: BodyId = BodyId::Technical;
372}
373
374/// Privileged origin that represents Root or Fellows pluralistic body.
375pub type RootOrFellows = EitherOfDiverse<
376	EnsureRoot<AccountId>,
377	EnsureXcm<IsVoiceOfBody<FellowshipLocation, FellowsBodyId>>,
378>;
379
380parameter_types! {
381	/// The asset ID for the asset that we use to pay for message delivery fees.
382	pub FeeAssetId: AssetId = AssetId(TokenRelayLocation::get());
383	/// The base fee for the message delivery fees.
384	pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
385}
386
387pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
388	FeeAssetId,
389	BaseDeliveryFee,
390	TransactionByteFee,
391	XcmpQueue,
392>;
393
394impl cumulus_pallet_xcmp_queue::Config for Runtime {
395	type RuntimeEvent = RuntimeEvent;
396	type ChannelInfo = ParachainSystem;
397	type VersionWrapper = PolkadotXcm;
398	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
399	type MaxInboundSuspended = ConstU32<1_000>;
400	type MaxActiveOutboundChannels = ConstU32<128>;
401	// Most on-chain HRMP channels are configured to use 102400 bytes of max message size, so we
402	// need to set the page size larger than that until we reduce the channel size on-chain.
403	type MaxPageSize = ConstU32<{ 103 * 1024 }>;
404	type ControllerOrigin = RootOrFellows;
405	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
406	type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
407	type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
408}
409
410impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime {
411	// This must be the same as the `ChannelInfo` from the `Config`:
412	type ChannelList = ParachainSystem;
413}
414
415pub const PERIOD: u32 = 6 * HOURS;
416pub const OFFSET: u32 = 0;
417
418impl pallet_session::Config for Runtime {
419	type RuntimeEvent = RuntimeEvent;
420	type ValidatorId = <Self as frame_system::Config>::AccountId;
421	// we don't have stash and controller, thus we don't need the convert as well.
422	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
423	type ShouldEndSession = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
424	type NextSessionRotation = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
425	type SessionManager = CollatorSelection;
426	// Essentially just Aura, but let's be pedantic.
427	type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
428	type Keys = SessionKeys;
429	type DisablingStrategy = ();
430	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
431	type Currency = Balances;
432	type KeyDeposit = ();
433}
434
435impl pallet_aura::Config for Runtime {
436	type AuthorityId = AuraId;
437	type DisabledValidators = ();
438	type MaxAuthorities = ConstU32<100_000>;
439	type AllowMultipleBlocksPerSlot = ConstBool<true>;
440	type SlotDuration = ConstU64<SLOT_DURATION>;
441}
442
443parameter_types! {
444	pub const PotId: PalletId = PalletId(*b"PotStake");
445	pub const SessionLength: BlockNumber = 6 * HOURS;
446	/// StakingAdmin pluralistic body.
447	pub const StakingAdminBodyId: BodyId = BodyId::Defense;
448}
449
450/// We allow Root and the `StakingAdmin` to execute privileged collator selection operations.
451pub type CollatorSelectionUpdateOrigin = EitherOfDiverse<
452	EnsureRoot<AccountId>,
453	EnsureXcm<IsVoiceOfBody<GovernanceLocation, StakingAdminBodyId>>,
454>;
455
456impl pallet_collator_selection::Config for Runtime {
457	type RuntimeEvent = RuntimeEvent;
458	type Currency = Balances;
459	type UpdateOrigin = CollatorSelectionUpdateOrigin;
460	type PotId = PotId;
461	type MaxCandidates = ConstU32<100>;
462	type MinEligibleCollators = ConstU32<4>;
463	type MaxInvulnerables = ConstU32<20>;
464	// should be a multiple of session or things will get inconsistent
465	type KickThreshold = ConstU32<PERIOD>;
466	type ValidatorId = <Self as frame_system::Config>::AccountId;
467	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
468	type ValidatorRegistration = Session;
469	type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
470}
471
472parameter_types! {
473	/// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
474	pub const DepositBase: Balance = deposit(1, 88);
475	/// Additional storage item size of 32 bytes.
476	pub const DepositFactor: Balance = deposit(0, 32);
477}
478
479impl pallet_multisig::Config for Runtime {
480	type RuntimeEvent = RuntimeEvent;
481	type RuntimeCall = RuntimeCall;
482	type Currency = Balances;
483	type DepositBase = DepositBase;
484	type DepositFactor = DepositFactor;
485	type MaxSignatories = ConstU32<100>;
486	type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
487	type BlockNumberProvider = frame_system::Pallet<Runtime>;
488}
489
490/// The type used to represent the kinds of proxying allowed.
491#[derive(
492	Copy,
493	Clone,
494	Eq,
495	PartialEq,
496	Ord,
497	PartialOrd,
498	Encode,
499	Decode,
500	DecodeWithMemTracking,
501	Debug,
502	MaxEncodedLen,
503	scale_info::TypeInfo,
504)]
505pub enum ProxyType {
506	/// Fully permissioned proxy. Can execute any call on behalf of _proxied_.
507	Any,
508	/// Can execute any call that does not transfer funds or assets.
509	NonTransfer,
510	/// Proxy with the ability to reject time-delay proxy announcements.
511	CancelProxy,
512	/// Proxy for all Broker pallet calls.
513	Broker,
514	/// Proxy for renewing coretime.
515	CoretimeRenewer,
516	/// Proxy able to purchase on-demand coretime credits.
517	OnDemandPurchaser,
518	/// Collator selection proxy. Can execute calls related to collator selection mechanism.
519	Collator,
520}
521impl Default for ProxyType {
522	fn default() -> Self {
523		Self::Any
524	}
525}
526
527impl InstanceFilter<RuntimeCall> for ProxyType {
528	fn filter(&self, c: &RuntimeCall) -> bool {
529		match self {
530			ProxyType::Any => true,
531			ProxyType::NonTransfer => !matches!(
532				c,
533				RuntimeCall::Balances { .. } |
534				// `purchase`, `renew`, `transfer` and `purchase_credit` are pretty self explanatory.
535				RuntimeCall::Broker(pallet_broker::Call::purchase { .. }) |
536				RuntimeCall::Broker(pallet_broker::Call::renew { .. }) |
537				RuntimeCall::Broker(pallet_broker::Call::transfer { .. }) |
538				RuntimeCall::Broker(pallet_broker::Call::purchase_credit { .. }) |
539				// `pool` doesn't transfer, but it defines the account to be paid for contributions
540				RuntimeCall::Broker(pallet_broker::Call::pool { .. }) |
541				// `assign` is essentially a transfer of a region NFT
542				RuntimeCall::Broker(pallet_broker::Call::assign { .. })
543			),
544			ProxyType::CancelProxy => matches!(
545				c,
546				RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) |
547					RuntimeCall::Utility { .. } |
548					RuntimeCall::Multisig { .. }
549			),
550			ProxyType::Broker => {
551				matches!(
552					c,
553					RuntimeCall::Broker { .. } |
554						RuntimeCall::Utility { .. } |
555						RuntimeCall::Multisig { .. }
556				)
557			},
558			ProxyType::CoretimeRenewer => {
559				matches!(
560					c,
561					RuntimeCall::Broker(pallet_broker::Call::renew { .. }) |
562						RuntimeCall::Utility { .. } |
563						RuntimeCall::Multisig { .. }
564				)
565			},
566			ProxyType::OnDemandPurchaser => {
567				matches!(
568					c,
569					RuntimeCall::Broker(pallet_broker::Call::purchase_credit { .. }) |
570						RuntimeCall::Utility { .. } |
571						RuntimeCall::Multisig { .. }
572				)
573			},
574			ProxyType::Collator => matches!(
575				c,
576				RuntimeCall::CollatorSelection { .. } |
577					RuntimeCall::Utility { .. } |
578					RuntimeCall::Multisig { .. }
579			),
580		}
581	}
582
583	fn is_superset(&self, o: &Self) -> bool {
584		match (self, o) {
585			(x, y) if x == y => true,
586			(ProxyType::Any, _) => true,
587			(_, ProxyType::Any) => false,
588			(ProxyType::Broker, ProxyType::CoretimeRenewer) => true,
589			(ProxyType::Broker, ProxyType::OnDemandPurchaser) => true,
590			(ProxyType::NonTransfer, ProxyType::Collator) => true,
591			_ => false,
592		}
593	}
594}
595
596parameter_types! {
597	// One storage item; key size 32, value size 8; .
598	pub const ProxyDepositBase: Balance = deposit(1, 40);
599	// Additional storage item size of 33 bytes.
600	pub const ProxyDepositFactor: Balance = deposit(0, 33);
601	pub const MaxProxies: u16 = 32;
602	// One storage item; key size 32, value size 16
603	pub const AnnouncementDepositBase: Balance = deposit(1, 48);
604	pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
605	pub const MaxPending: u16 = 32;
606}
607
608impl pallet_proxy::Config for Runtime {
609	type RuntimeEvent = RuntimeEvent;
610	type RuntimeCall = RuntimeCall;
611	type Currency = Balances;
612	type ProxyType = ProxyType;
613	type ProxyDepositBase = ProxyDepositBase;
614	type ProxyDepositFactor = ProxyDepositFactor;
615	type MaxProxies = MaxProxies;
616	type WeightInfo = weights::pallet_proxy::WeightInfo<Runtime>;
617	type MaxPending = MaxPending;
618	type CallHasher = BlakeTwo256;
619	type AnnouncementDepositBase = AnnouncementDepositBase;
620	type AnnouncementDepositFactor = AnnouncementDepositFactor;
621	type BlockNumberProvider = frame_system::Pallet<Runtime>;
622}
623
624impl pallet_utility::Config for Runtime {
625	type RuntimeEvent = RuntimeEvent;
626	type RuntimeCall = RuntimeCall;
627	type PalletsOrigin = OriginCaller;
628	type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
629}
630
631impl pallet_sudo::Config for Runtime {
632	type RuntimeCall = RuntimeCall;
633	type RuntimeEvent = RuntimeEvent;
634	type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
635}
636
637impl pallet_accumulate_and_forward::Config for Runtime {
638	type Currency = Balances;
639	type PalletId = AccumulateForwardPalletId;
640	type Forwarder = xcm_builder::TeleportForwarderForAccountId32<
641		xcm_config::XcmConfig,
642		testnet_parachains_constants::westend::locations::AssetHubLocation,
643		xcm_config::TokenRelayLocation,
644		DapStagingLocation,
645	>;
646	type TransferPeriod = ForwardPeriod;
647	type MinTransferAmount = MinForwardAmount;
648	type BlockNumberProvider = RelaychainDataProvider<Runtime>;
649	type WeightInfo = weights::pallet_accumulate_and_forward::WeightInfo<Runtime>;
650}
651
652pub struct BrokerMigrationV4BlockConversion;
653
654impl pallet_broker::migration::v4::BlockToRelayHeightConversion<Runtime>
655	for BrokerMigrationV4BlockConversion
656{
657	fn convert_block_number_to_relay_height(input_block_number: u32) -> u32 {
658		let relay_height = pallet_broker::RCBlockNumberProviderOf::<
659			<Runtime as pallet_broker::Config>::Coretime,
660		>::current_block_number();
661		let parachain_block_number = frame_system::Pallet::<Runtime>::block_number();
662		let offset = relay_height - parachain_block_number * 2;
663		offset + input_block_number * 2
664	}
665
666	fn convert_block_length_to_relay_length(input_block_length: u32) -> u32 {
667		input_block_length * 2
668	}
669}
670
671pub type MetaTxExtension = (
672	pallet_verify_signature::VerifySignature<Runtime>,
673	pallet_meta_tx::MetaTxMarker<Runtime>,
674	frame_system::CheckNonZeroSender<Runtime>,
675	frame_system::CheckSpecVersion<Runtime>,
676	frame_system::CheckTxVersion<Runtime>,
677	frame_system::CheckGenesis<Runtime>,
678	frame_system::CheckEra<Runtime>,
679	frame_system::CheckNonce<Runtime>,
680	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
681);
682
683impl pallet_meta_tx::Config for Runtime {
684	type WeightInfo = weights::pallet_meta_tx::WeightInfo<Runtime>;
685	type RuntimeEvent = RuntimeEvent;
686	#[cfg(not(feature = "runtime-benchmarks"))]
687	type Extension = MetaTxExtension;
688	#[cfg(feature = "runtime-benchmarks")]
689	type Extension = pallet_meta_tx::WeightlessExtension<Runtime>;
690}
691
692impl pallet_verify_signature::Config for Runtime {
693	type Signature = MultiSignature;
694	type AccountIdentifier = MultiSigner;
695	type WeightInfo = weights::pallet_verify_signature::WeightInfo<Runtime>;
696	#[cfg(feature = "runtime-benchmarks")]
697	type BenchmarkHelper = ();
698}
699
700// Create the runtime by composing the FRAME pallets that were previously configured.
701construct_runtime!(
702	pub enum Runtime
703	{
704		// System support stuff.
705		System: frame_system = 0,
706		ParachainSystem: cumulus_pallet_parachain_system = 1,
707		Timestamp: pallet_timestamp = 3,
708		ParachainInfo: parachain_info = 4,
709		WeightReclaim: cumulus_pallet_weight_reclaim = 5,
710
711		// Monetary stuff.
712		Balances: pallet_balances = 10,
713		TransactionPayment: pallet_transaction_payment = 11,
714		AccumulateForward: pallet_accumulate_and_forward = 12,
715
716		// Collator support. The order of these 5 are important and shall not change.
717		Authorship: pallet_authorship = 20,
718		CollatorSelection: pallet_collator_selection = 21,
719		Session: pallet_session = 22,
720		Aura: pallet_aura = 23,
721		AuraExt: cumulus_pallet_aura_ext = 24,
722
723		// XCM & related
724		XcmpQueue: cumulus_pallet_xcmp_queue = 30,
725		PolkadotXcm: pallet_xcm = 31,
726		CumulusXcm: cumulus_pallet_xcm = 32,
727		MessageQueue: pallet_message_queue = 34,
728
729		// Handy utilities.
730		Utility: pallet_utility = 40,
731		Multisig: pallet_multisig = 41,
732		Proxy: pallet_proxy = 42,
733		MetaTx: pallet_meta_tx = 43,
734		VerifySignature: pallet_verify_signature = 44,
735
736		// The main stage.
737		Broker: pallet_broker = 50,
738
739		// Sudo
740		Sudo: pallet_sudo = 100,
741	}
742);
743
744#[cfg(feature = "runtime-benchmarks")]
745mod benches {
746	frame_benchmarking::define_benchmarks!(
747		[frame_system, SystemBench::<Runtime>]
748		[cumulus_pallet_parachain_system, ParachainSystem]
749		[pallet_timestamp, Timestamp]
750		[pallet_balances, Balances]
751		[pallet_broker, Broker]
752		[pallet_collator_selection, CollatorSelection]
753		[pallet_session, SessionBench::<Runtime>]
754		[cumulus_pallet_xcmp_queue, XcmpQueue]
755		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
756		[pallet_message_queue, MessageQueue]
757		[pallet_multisig, Multisig]
758		[pallet_proxy, Proxy]
759		[pallet_utility, Utility]
760		[pallet_meta_tx, MetaTx]
761		[pallet_verify_signature, VerifySignature]
762		// NOTE: Make sure you point to the individual modules below.
763		[pallet_xcm_benchmarks::fungible, XcmBalances]
764		[pallet_xcm_benchmarks::generic, XcmGeneric]
765		[cumulus_pallet_weight_reclaim, WeightReclaim]
766		[pallet_accumulate_and_forward, AccumulateForward]
767	);
768}
769
770impl_runtime_apis! {
771	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
772		fn slot_duration() -> sp_consensus_aura::SlotDuration {
773			sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
774		}
775
776		fn authorities() -> Vec<AuraId> {
777			pallet_aura::Authorities::<Runtime>::get().into_inner()
778		}
779	}
780
781	impl cumulus_primitives_core::RelayParentOffsetApi<Block> for Runtime {
782		fn relay_parent_offset() -> u32 {
783			0
784		}
785	}
786
787	impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
788		fn can_build_upon(
789			included_hash: <Block as BlockT>::Hash,
790			slot: cumulus_primitives_aura::Slot,
791		) -> bool {
792			ConsensusHook::can_build_upon(included_hash, slot)
793		}
794	}
795
796	impl sp_api::Core<Block> for Runtime {
797		fn version() -> RuntimeVersion {
798			VERSION
799		}
800
801		fn execute_block(block: <Block as BlockT>::LazyBlock) {
802			Executive::execute_block(block)
803		}
804
805		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
806			Executive::initialize_block(header)
807		}
808	}
809
810	impl sp_api::Metadata<Block> for Runtime {
811		fn metadata() -> OpaqueMetadata {
812			OpaqueMetadata::new(Runtime::metadata().into())
813		}
814
815		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
816			Runtime::metadata_at_version(version)
817		}
818
819		fn metadata_versions() -> alloc::vec::Vec<u32> {
820			Runtime::metadata_versions()
821		}
822	}
823
824	impl sp_block_builder::BlockBuilder<Block> for Runtime {
825		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
826			Executive::apply_extrinsic(extrinsic)
827		}
828
829		fn finalize_block() -> <Block as BlockT>::Header {
830			Executive::finalize_block()
831		}
832
833		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
834			data.create_extrinsics()
835		}
836
837		fn check_inherents(
838			block: <Block as BlockT>::LazyBlock,
839			data: sp_inherents::InherentData,
840		) -> sp_inherents::CheckInherentsResult {
841			data.check_extrinsics(&block)
842		}
843	}
844
845	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
846		fn validate_transaction(
847			source: TransactionSource,
848			tx: <Block as BlockT>::Extrinsic,
849			block_hash: <Block as BlockT>::Hash,
850		) -> TransactionValidity {
851			Executive::validate_transaction(source, tx, block_hash)
852		}
853	}
854
855	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
856		fn offchain_worker(header: &<Block as BlockT>::Header) {
857			Executive::offchain_worker(header)
858		}
859	}
860
861	impl sp_session::SessionKeys<Block> for Runtime {
862		fn generate_session_keys(owner: Vec<u8>, seed: Option<Vec<u8>>) -> OpaqueGeneratedSessionKeys {
863			SessionKeys::generate(&owner, seed).into()
864		}
865
866		fn decode_session_keys(
867			encoded: Vec<u8>,
868		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
869			SessionKeys::decode_into_raw_public_keys(&encoded)
870		}
871	}
872
873	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
874		fn account_nonce(account: AccountId) -> Nonce {
875			System::account_nonce(account)
876		}
877	}
878
879	impl pallet_broker::runtime_api::BrokerApi<Block, Balance> for Runtime {
880		fn sale_price() -> Result<Balance, DispatchError> {
881			Broker::current_price()
882		}
883	}
884
885	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
886		fn query_info(
887			uxt: <Block as BlockT>::Extrinsic,
888			len: u32,
889		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
890			TransactionPayment::query_info(uxt, len)
891		}
892		fn query_fee_details(
893			uxt: <Block as BlockT>::Extrinsic,
894			len: u32,
895		) -> pallet_transaction_payment::FeeDetails<Balance> {
896			TransactionPayment::query_fee_details(uxt, len)
897		}
898		fn query_weight_to_fee(weight: Weight) -> Balance {
899			TransactionPayment::weight_to_fee(weight)
900		}
901		fn query_length_to_fee(length: u32) -> Balance {
902			TransactionPayment::length_to_fee(length)
903		}
904	}
905
906	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
907		for Runtime
908	{
909		fn query_call_info(
910			call: RuntimeCall,
911			len: u32,
912		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
913			TransactionPayment::query_call_info(call, len)
914		}
915		fn query_call_fee_details(
916			call: RuntimeCall,
917			len: u32,
918		) -> pallet_transaction_payment::FeeDetails<Balance> {
919			TransactionPayment::query_call_fee_details(call, len)
920		}
921		fn query_weight_to_fee(weight: Weight) -> Balance {
922			TransactionPayment::weight_to_fee(weight)
923		}
924		fn query_length_to_fee(length: u32) -> Balance {
925			TransactionPayment::length_to_fee(length)
926		}
927	}
928
929	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
930		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
931			let acceptable_assets = vec![AssetId(xcm_config::TokenRelayLocation::get())];
932			PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
933		}
934
935		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
936			type Trader = <XcmConfig as xcm_executor::Config>::Trader;
937			PolkadotXcm::query_weight_to_asset_fee::<Trader>(weight, asset)
938		}
939
940		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
941			PolkadotXcm::query_xcm_weight(message)
942		}
943
944		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>, asset_id: VersionedAssetId) -> Result<VersionedAssets, XcmPaymentApiError> {
945			type AssetExchanger = <XcmConfig as xcm_executor::Config>::AssetExchanger;
946			PolkadotXcm::query_delivery_fees::<AssetExchanger>(destination, message, asset_id)
947		}
948	}
949
950	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
951		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
952			PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
953		}
954
955		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
956			PolkadotXcm::dry_run_xcm::<xcm_config::XcmRouter>(origin_location, xcm)
957		}
958	}
959
960	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
961		fn convert_location(location: VersionedLocation) -> Result<
962			AccountId,
963			xcm_runtime_apis::conversions::Error
964		> {
965			xcm_runtime_apis::conversions::LocationToAccountHelper::<
966				AccountId,
967				xcm_config::LocationToAccountId,
968			>::convert_location(location)
969		}
970	}
971
972	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
973		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
974			PolkadotXcm::is_trusted_reserve(asset, location)
975		}
976		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
977			PolkadotXcm::is_trusted_teleporter(asset, location)
978		}
979	}
980
981	impl xcm_runtime_apis::authorized_aliases::AuthorizedAliasersApi<Block> for Runtime {
982		fn authorized_aliasers(target: VersionedLocation) -> Result<
983			Vec<xcm_runtime_apis::authorized_aliases::OriginAliaser>,
984			xcm_runtime_apis::authorized_aliases::Error
985		> {
986			PolkadotXcm::authorized_aliasers(target)
987		}
988		fn is_authorized_alias(origin: VersionedLocation, target: VersionedLocation) -> Result<
989			bool,
990			xcm_runtime_apis::authorized_aliases::Error
991		> {
992			PolkadotXcm::is_authorized_alias(origin, target)
993		}
994	}
995
996	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
997		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
998			ParachainSystem::collect_collation_info(header)
999		}
1000	}
1001
1002	#[cfg(feature = "try-runtime")]
1003	impl frame_try_runtime::TryRuntime<Block> for Runtime {
1004		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1005			let weight = Executive::try_runtime_upgrade(checks).unwrap();
1006			(weight, RuntimeBlockWeights::get().max_block)
1007		}
1008
1009		fn execute_block(
1010			block: <Block as BlockT>::LazyBlock,
1011			state_root_check: bool,
1012			signature_check: bool,
1013			select: frame_try_runtime::TryStateSelect,
1014		) -> Weight {
1015			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
1016			// have a backtrace here.
1017			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1018		}
1019	}
1020
1021	#[cfg(feature = "runtime-benchmarks")]
1022	impl frame_benchmarking::Benchmark<Block> for Runtime {
1023		fn benchmark_metadata(extra: bool) -> (
1024			Vec<frame_benchmarking::BenchmarkList>,
1025			Vec<frame_support::traits::StorageInfo>,
1026		) {
1027			use frame_benchmarking::BenchmarkList;
1028			use frame_support::traits::StorageInfoTrait;
1029			use frame_system_benchmarking::Pallet as SystemBench;
1030			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1031			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1032
1033			// This is defined once again in dispatch_benchmark, because list_benchmarks!
1034			// and add_benchmarks! are macros exported by define_benchmarks! macros and those types
1035			// are referenced in that call.
1036			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1037			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1038
1039			let mut list = Vec::<BenchmarkList>::new();
1040			list_benchmarks!(list, extra);
1041
1042			let storage_info = AllPalletsWithSystem::storage_info();
1043			(list, storage_info)
1044		}
1045
1046		#[allow(non_local_definitions)]
1047		fn dispatch_benchmark(
1048			config: frame_benchmarking::BenchmarkConfig
1049		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1050			use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
1051			use sp_storage::TrackedStorageKey;
1052			use codec::Encode;
1053
1054			use frame_system_benchmarking::Pallet as SystemBench;
1055			impl frame_system_benchmarking::Config for Runtime {
1056				fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1057					ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1058					Ok(())
1059				}
1060
1061				fn verify_set_code() {
1062					System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1063				}
1064			}
1065
1066			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1067			impl cumulus_pallet_session_benchmarking::Config for Runtime {
1068				fn generate_session_keys_and_proof(owner: Self::AccountId) -> (Self::Keys, Vec<u8>) {
1069					let keys = SessionKeys::generate(&owner.encode(), None);
1070					(keys.keys, keys.proof.encode())
1071				}
1072			}
1073
1074			use xcm::latest::prelude::*;
1075			use xcm_config::TokenRelayLocation;
1076			use testnet_parachains_constants::westend::locations::{AssetHubParaId, AssetHubLocation};
1077
1078			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1079			impl pallet_xcm::benchmarking::Config for Runtime {
1080				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1081						xcm_config::XcmConfig,
1082						ExistentialDepositAsset,
1083						PriceForSiblingParachainDelivery,
1084						AssetHubParaId,
1085						ParachainSystem,
1086					>;
1087
1088				fn reachable_dest() -> Option<Location> {
1089					Some(AssetHubLocation::get())
1090				}
1091
1092				fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1093					// Relay/native token can be teleported between AH and Relay.
1094					Some((
1095						Asset {
1096							fun: Fungible(ExistentialDeposit::get()),
1097							id: AssetId(TokenRelayLocation::get())
1098						},
1099						AssetHubLocation::get(),
1100					))
1101				}
1102
1103				fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1104					// Coretime chain can reserve transfer regions to some random parachain.
1105
1106					// Properties of a mock region:
1107					let core = 0;
1108					let begin = 0;
1109					let end = 42;
1110
1111					let region_id = pallet_broker::Pallet::<Runtime>::issue(core, begin, pallet_broker::CoreMask::complete(), end, None, None);
1112					Some((
1113						Asset {
1114							fun: NonFungible(Index(region_id.into())),
1115							id: AssetId(xcm_config::BrokerPalletLocation::get())
1116						},
1117						AssetHubLocation::get(),
1118					))
1119				}
1120
1121				fn set_up_complex_asset_transfer() -> Option<(Assets, u32, Location, alloc::boxed::Box<dyn FnOnce()>)> {
1122					let native_location = Parent.into();
1123					let dest = AssetHubLocation::get();
1124
1125					pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1126						native_location,
1127						dest,
1128					)
1129				}
1130
1131				fn get_asset() -> Asset {
1132					Asset {
1133						id: AssetId(TokenRelayLocation::get()),
1134						fun: Fungible(ExistentialDeposit::get()),
1135					}
1136				}
1137			}
1138
1139			parameter_types! {
1140				pub ExistentialDepositAsset: Option<Asset> = Some((
1141					TokenRelayLocation::get(),
1142					ExistentialDeposit::get()
1143				).into());
1144			}
1145
1146			impl pallet_xcm_benchmarks::Config for Runtime {
1147				type XcmConfig = xcm_config::XcmConfig;
1148
1149				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1150						xcm_config::XcmConfig,
1151						ExistentialDepositAsset,
1152						PriceForSiblingParachainDelivery,
1153						AssetHubParaId,
1154						ParachainSystem,
1155					>;
1156
1157				type AccountIdConverter = xcm_config::LocationToAccountId;
1158				fn valid_destination() -> Result<Location, BenchmarkError> {
1159					Ok(AssetHubLocation::get())
1160				}
1161				fn worst_case_holding(_depositable_count: u32) -> xcm_executor::AssetsInHolding {
1162					use pallet_xcm_benchmarks::MockCredit;
1163					// just concrete assets according to relay chain.
1164					let mut holding = xcm_executor::AssetsInHolding::new();
1165					holding.fungible.insert(
1166						AssetId(TokenRelayLocation::get()),
1167						alloc::boxed::Box::new(MockCredit(1_000_000 * UNITS)),
1168					);
1169					holding
1170				}
1171			}
1172
1173			parameter_types! {
1174				pub TrustedTeleporter: Option<(Location, Asset)> = Some((
1175					AssetHubLocation::get(),
1176					Asset { fun: Fungible(UNITS), id: AssetId(TokenRelayLocation::get()) },
1177				));
1178				pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1179				pub const TrustedReserve: Option<(Location, Asset)> = None;
1180			}
1181
1182			impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1183				type TransactAsset = Balances;
1184
1185				type CheckedAccount = CheckedAccount;
1186				type TrustedTeleporter = TrustedTeleporter;
1187				type TrustedReserve = TrustedReserve;
1188
1189				fn get_asset() -> Asset {
1190					Asset {
1191						id: AssetId(TokenRelayLocation::get()),
1192						fun: Fungible(UNITS),
1193					}
1194				}
1195			}
1196
1197			impl pallet_xcm_benchmarks::generic::Config for Runtime {
1198				type RuntimeCall = RuntimeCall;
1199				type TransactAsset = Balances;
1200
1201				fn worst_case_response() -> (u64, Response) {
1202					(0u64, Response::Version(Default::default()))
1203				}
1204
1205				fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
1206					Err(BenchmarkError::Skip)
1207				}
1208
1209				fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
1210					Err(BenchmarkError::Skip)
1211				}
1212
1213				fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
1214					Ok((AssetHubLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1215				}
1216
1217				fn subscribe_origin() -> Result<Location, BenchmarkError> {
1218					Ok(AssetHubLocation::get())
1219				}
1220
1221				fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1222					let origin = AssetHubLocation::get();
1223					let assets: Assets = (AssetId(TokenRelayLocation::get()), 1_000 * UNITS).into();
1224					let ticket = Location { parents: 0, interior: Here };
1225					Ok((origin, ticket, assets))
1226				}
1227
1228				fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
1229					Ok((Asset {
1230						id: AssetId(TokenRelayLocation::get()),
1231						fun: Fungible(1_000_000 * UNITS),
1232					}, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
1233				}
1234
1235				fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
1236					Err(BenchmarkError::Skip)
1237				}
1238
1239				fn export_message_origin_and_destination(
1240				) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
1241					Err(BenchmarkError::Skip)
1242				}
1243
1244				fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
1245					let origin = Location::new(1, [Parachain(1000)]);
1246					let target = Location::new(1, [Parachain(1000), AccountId32 { id: [128u8; 32], network: None }]);
1247					Ok((origin, target))
1248				}
1249			}
1250
1251			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1252			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1253
1254			use frame_support::traits::WhitelistedStorageKeys;
1255			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1256
1257			let mut batches = Vec::<BenchmarkBatch>::new();
1258			let params = (&config, &whitelist);
1259			add_benchmarks!(params, batches);
1260
1261			Ok(batches)
1262		}
1263	}
1264
1265	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1266		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1267			build_state::<RuntimeGenesisConfig>(config)
1268		}
1269
1270		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1271			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1272		}
1273
1274		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1275			genesis_config_presets::preset_names()
1276		}
1277	}
1278
1279	impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
1280		fn parachain_id() -> ParaId {
1281			ParachainInfo::parachain_id()
1282		}
1283	}
1284
1285	impl cumulus_primitives_core::TargetBlockRate<Block> for Runtime {
1286		fn target_block_rate() -> u32 {
1287			BLOCK_PROCESSING_VELOCITY
1288		}
1289	}
1290}
1291
1292cumulus_pallet_parachain_system::register_validate_block! {
1293	Runtime = Runtime,
1294	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
1295}