referrerpolicy=no-referrer-when-downgrade

collectives_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//! # Collectives Parachain
17//!
18//! This parachain is for collectives that serve the Westend network.
19//! Each collective is defined by a specialized (possibly instanced) pallet.
20//!
21//! ### Governance
22//!
23//! As a system parachain, Collectives defers its governance (namely, its `Root` origin), to
24//! its Relay Chain parent, Westend.
25//!
26//! ### Collator Selection
27//!
28//! Collectives uses `pallet-collator-selection`, a simple first-come-first-served registration
29//! system where collators can reserve a small bond to join the block producer set. There is no
30//! slashing. Collective members are generally expected to run collators.
31
32#![cfg_attr(not(feature = "std"), no_std)]
33#![recursion_limit = "256"]
34
35// Make the WASM binary available.
36#[cfg(feature = "std")]
37include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
38
39pub mod ambassador;
40mod genesis_config_presets;
41pub mod impls;
42mod weights;
43pub mod xcm_config;
44// Fellowship configurations.
45pub mod fellowship;
46
47// Secretary Configuration
48pub mod secretary;
49
50extern crate alloc;
51
52pub use ambassador::pallet_ambassador_origins;
53
54use alloc::{vec, vec::Vec};
55use ambassador::AmbassadorCoreInstance;
56use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
57use fellowship::{pallet_fellowship_origins, Fellows, FellowshipCoreInstance};
58use impls::{AllianceProposalProvider, EqualOrGreatestRootCmp};
59use sp_api::impl_runtime_apis;
60use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
61use sp_runtime::{
62	generic, impl_opaque_keys,
63	traits::{AccountIdConversion, BlakeTwo256, Block as BlockT},
64	transaction_validity::{TransactionSource, TransactionValidity},
65	ApplyExtrinsicResult, Perbill,
66};
67
68#[cfg(feature = "std")]
69use sp_version::NativeVersion;
70use sp_version::RuntimeVersion;
71
72use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
73use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
74use frame_support::{
75	construct_runtime, derive_impl,
76	dispatch::DispatchClass,
77	genesis_builder_helper::{build_state, get_preset},
78	parameter_types,
79	traits::{
80		fungible::HoldConsideration, ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse,
81		InstanceFilter, LinearStoragePrice, TransformOrigin,
82	},
83	weights::{ConstantMultiplier, Weight},
84	PalletId,
85};
86use frame_system::{
87	limits::{BlockLength, BlockWeights},
88	EnsureRoot,
89};
90pub use parachains_common as common;
91use parachains_common::{
92	impls::{DealWithFees, ToParentTreasury},
93	message_queue::*,
94	AccountId, AuraId, Balance, BlockNumber, Hash, Header, Nonce, Signature,
95	AVERAGE_ON_INITIALIZE_RATIO, NORMAL_DISPATCH_RATIO,
96};
97use sp_runtime::RuntimeDebug;
98use testnet_parachains_constants::westend::{
99	account::*, consensus::*, currency::*, fee::WeightToFee, time::*,
100};
101use xcm_config::{
102	GovernanceLocation, LocationToAccountId, TreasurerBodyId, XcmOriginToTransactDispatchOrigin,
103};
104
105#[cfg(any(feature = "std", test))]
106pub use sp_runtime::BuildStorage;
107
108// Polkadot imports
109use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
110use polkadot_runtime_common::{
111	impls::VersionedLocatableAsset, BlockHashCount, SlowAdjustingFeeUpdate,
112};
113use xcm::{prelude::*, Version as XcmVersion};
114use xcm_runtime_apis::{
115	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
116	fees::Error as XcmPaymentApiError,
117};
118
119use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
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("collectives-westend"),
130	impl_name: alloc::borrow::Cow::Borrowed("collectives-westend"),
131	authoring_version: 1,
132	spec_version: 1_019_004,
133	impl_version: 0,
134	apis: RUNTIME_API_VERSIONS,
135	transaction_version: 6,
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
145/// Privileged origin that represents Root or more than two thirds of the Alliance.
146pub type RootOrAllianceTwoThirdsMajority = EitherOfDiverse<
147	EnsureRoot<AccountId>,
148	pallet_collective::EnsureProportionMoreThan<AccountId, AllianceCollective, 2, 3>,
149>;
150
151parameter_types! {
152	pub const Version: RuntimeVersion = VERSION;
153	pub RuntimeBlockLength: BlockLength =
154		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
155	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
156		.base_block(BlockExecutionWeight::get())
157		.for_class(DispatchClass::all(), |weights| {
158			weights.base_extrinsic = ExtrinsicBaseWeight::get();
159		})
160		.for_class(DispatchClass::Normal, |weights| {
161			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
162		})
163		.for_class(DispatchClass::Operational, |weights| {
164			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
165			// Operational transactions have some extra reserved space, so that they
166			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
167			weights.reserved = Some(
168				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
169			);
170		})
171		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
172		.build_or_panic();
173	pub const SS58Prefix: u8 = 42;
174}
175
176// Configure FRAME pallets to include in runtime.
177#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
178impl frame_system::Config for Runtime {
179	type BlockWeights = RuntimeBlockWeights;
180	type BlockLength = RuntimeBlockLength;
181	type AccountId = AccountId;
182	type RuntimeCall = RuntimeCall;
183	type Nonce = Nonce;
184	type Hash = Hash;
185	type Block = Block;
186	type BlockHashCount = BlockHashCount;
187	type DbWeight = RocksDbWeight;
188	type Version = Version;
189	type AccountData = pallet_balances::AccountData<Balance>;
190	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
191	type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
192	type SS58Prefix = SS58Prefix;
193	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
194	type MaxConsumers = frame_support::traits::ConstU32<16>;
195	type SingleBlockMigrations = Migrations;
196}
197
198impl cumulus_pallet_weight_reclaim::Config for Runtime {
199	type WeightInfo = weights::cumulus_pallet_weight_reclaim::WeightInfo<Runtime>;
200}
201
202impl pallet_timestamp::Config for Runtime {
203	/// A timestamp: milliseconds since the unix epoch.
204	type Moment = u64;
205	type OnTimestampSet = Aura;
206	type MinimumPeriod = ConstU64<0>;
207	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
208}
209
210impl pallet_authorship::Config for Runtime {
211	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
212	type EventHandler = (CollatorSelection,);
213}
214
215parameter_types! {
216	pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
217}
218
219impl pallet_balances::Config for Runtime {
220	type MaxLocks = ConstU32<50>;
221	/// The type for recording an account's balance.
222	type Balance = Balance;
223	/// The ubiquitous event type.
224	type RuntimeEvent = RuntimeEvent;
225	type DustRemoval = ();
226	type ExistentialDeposit = ExistentialDeposit;
227	type AccountStore = System;
228	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
229	type MaxReserves = ConstU32<50>;
230	type ReserveIdentifier = [u8; 8];
231	type RuntimeHoldReason = RuntimeHoldReason;
232	type RuntimeFreezeReason = RuntimeFreezeReason;
233	type FreezeIdentifier = ();
234	type MaxFreezes = ConstU32<0>;
235	type DoneSlashHandler = ();
236}
237
238parameter_types! {
239	/// Relay Chain `TransactionByteFee` / 10
240	pub const TransactionByteFee: Balance = MILLICENTS;
241}
242
243impl pallet_transaction_payment::Config for Runtime {
244	type RuntimeEvent = RuntimeEvent;
245	type OnChargeTransaction =
246		pallet_transaction_payment::FungibleAdapter<Balances, DealWithFees<Runtime>>;
247	type WeightToFee = WeightToFee;
248	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
249	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
250	type OperationalFeeMultiplier = ConstU8<5>;
251	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
252}
253
254parameter_types! {
255	// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
256	pub const DepositBase: Balance = deposit(1, 88);
257	// Additional storage item size of 32 bytes.
258	pub const DepositFactor: Balance = deposit(0, 32);
259}
260
261impl pallet_multisig::Config for Runtime {
262	type RuntimeEvent = RuntimeEvent;
263	type RuntimeCall = RuntimeCall;
264	type Currency = Balances;
265	type DepositBase = DepositBase;
266	type DepositFactor = DepositFactor;
267	type MaxSignatories = ConstU32<100>;
268	type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
269	type BlockNumberProvider = frame_system::Pallet<Runtime>;
270}
271
272impl pallet_utility::Config for Runtime {
273	type RuntimeEvent = RuntimeEvent;
274	type RuntimeCall = RuntimeCall;
275	type PalletsOrigin = OriginCaller;
276	type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
277}
278
279parameter_types! {
280	// One storage item; key size 32, value size 8; .
281	pub const ProxyDepositBase: Balance = deposit(1, 40);
282	// Additional storage item size of 33 bytes.
283	pub const ProxyDepositFactor: Balance = deposit(0, 33);
284	// One storage item; key size 32, value size 16
285	pub const AnnouncementDepositBase: Balance = deposit(1, 48);
286	pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
287}
288
289/// The type used to represent the kinds of proxying allowed.
290#[derive(
291	Copy,
292	Clone,
293	Eq,
294	PartialEq,
295	Ord,
296	PartialOrd,
297	Encode,
298	Decode,
299	DecodeWithMemTracking,
300	RuntimeDebug,
301	MaxEncodedLen,
302	scale_info::TypeInfo,
303)]
304pub enum ProxyType {
305	/// Fully permissioned proxy. Can execute any call on behalf of _proxied_.
306	Any,
307	/// Can execute any call that does not transfer funds.
308	NonTransfer,
309	/// Proxy with the ability to reject time-delay proxy announcements.
310	CancelProxy,
311	/// Collator selection proxy. Can execute calls related to collator selection mechanism.
312	Collator,
313	/// Alliance proxy. Allows calls related to the Alliance.
314	Alliance,
315	/// Fellowship proxy. Allows calls related to the Fellowship.
316	Fellowship,
317	/// Ambassador proxy. Allows calls related to the Ambassador Program.
318	Ambassador,
319	/// Secretary proxy. Allows calls related to the Secretary collective
320	Secretary,
321}
322impl Default for ProxyType {
323	fn default() -> Self {
324		Self::Any
325	}
326}
327impl InstanceFilter<RuntimeCall> for ProxyType {
328	fn filter(&self, c: &RuntimeCall) -> bool {
329		match self {
330			ProxyType::Any => true,
331			ProxyType::NonTransfer => !matches!(c, RuntimeCall::Balances { .. }),
332			ProxyType::CancelProxy => matches!(
333				c,
334				RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) |
335					RuntimeCall::Utility { .. } |
336					RuntimeCall::Multisig { .. }
337			),
338			ProxyType::Collator => matches!(
339				c,
340				RuntimeCall::CollatorSelection { .. } |
341					RuntimeCall::Utility { .. } |
342					RuntimeCall::Multisig { .. }
343			),
344			ProxyType::Alliance => matches!(
345				c,
346				RuntimeCall::AllianceMotion { .. } |
347					RuntimeCall::Alliance { .. } |
348					RuntimeCall::Utility { .. } |
349					RuntimeCall::Multisig { .. }
350			),
351			ProxyType::Fellowship => matches!(
352				c,
353				RuntimeCall::FellowshipCollective { .. } |
354					RuntimeCall::FellowshipReferenda { .. } |
355					RuntimeCall::FellowshipCore { .. } |
356					RuntimeCall::FellowshipSalary { .. } |
357					RuntimeCall::FellowshipTreasury { .. } |
358					RuntimeCall::Utility { .. } |
359					RuntimeCall::Multisig { .. }
360			),
361			ProxyType::Ambassador => matches!(
362				c,
363				RuntimeCall::AmbassadorCollective { .. } |
364					RuntimeCall::AmbassadorReferenda { .. } |
365					RuntimeCall::AmbassadorContent { .. } |
366					RuntimeCall::AmbassadorCore { .. } |
367					RuntimeCall::AmbassadorSalary { .. } |
368					RuntimeCall::Utility { .. } |
369					RuntimeCall::Multisig { .. }
370			),
371			ProxyType::Secretary => matches!(
372				c,
373				RuntimeCall::SecretaryCollective { .. } |
374					RuntimeCall::SecretarySalary { .. } |
375					RuntimeCall::Utility { .. } |
376					RuntimeCall::Multisig { .. }
377			),
378		}
379	}
380	fn is_superset(&self, o: &Self) -> bool {
381		match (self, o) {
382			(x, y) if x == y => true,
383			(ProxyType::Any, _) => true,
384			(_, ProxyType::Any) => false,
385			(ProxyType::NonTransfer, _) => true,
386			_ => false,
387		}
388	}
389}
390
391impl pallet_proxy::Config for Runtime {
392	type RuntimeEvent = RuntimeEvent;
393	type RuntimeCall = RuntimeCall;
394	type Currency = Balances;
395	type ProxyType = ProxyType;
396	type ProxyDepositBase = ProxyDepositBase;
397	type ProxyDepositFactor = ProxyDepositFactor;
398	type MaxProxies = ConstU32<32>;
399	type WeightInfo = weights::pallet_proxy::WeightInfo<Runtime>;
400	type MaxPending = ConstU32<32>;
401	type CallHasher = BlakeTwo256;
402	type AnnouncementDepositBase = AnnouncementDepositBase;
403	type AnnouncementDepositFactor = AnnouncementDepositFactor;
404	type BlockNumberProvider = frame_system::Pallet<Runtime>;
405}
406
407parameter_types! {
408	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
409	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
410}
411
412impl cumulus_pallet_parachain_system::Config for Runtime {
413	type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
414	type RuntimeEvent = RuntimeEvent;
415	type OnSystemEvent = ();
416	type SelfParaId = parachain_info::Pallet<Runtime>;
417	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
418	type ReservedDmpWeight = ReservedDmpWeight;
419	type OutboundXcmpMessageSource = XcmpQueue;
420	type XcmpMessageHandler = XcmpQueue;
421	type ReservedXcmpWeight = ReservedXcmpWeight;
422	type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
423	type ConsensusHook = ConsensusHook;
424	type RelayParentOffset = ConstU32<0>;
425}
426
427type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
428	Runtime,
429	RELAY_CHAIN_SLOT_DURATION_MILLIS,
430	BLOCK_PROCESSING_VELOCITY,
431	UNINCLUDED_SEGMENT_CAPACITY,
432>;
433
434impl parachain_info::Config for Runtime {}
435
436parameter_types! {
437	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block;
438}
439
440impl pallet_message_queue::Config for Runtime {
441	type RuntimeEvent = RuntimeEvent;
442	type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
443	#[cfg(feature = "runtime-benchmarks")]
444	type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
445		cumulus_primitives_core::AggregateMessageOrigin,
446	>;
447	#[cfg(not(feature = "runtime-benchmarks"))]
448	type MessageProcessor = xcm_builder::ProcessXcmMessage<
449		AggregateMessageOrigin,
450		xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
451		RuntimeCall,
452	>;
453	type Size = u32;
454	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
455	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
456	type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
457	type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
458	type MaxStale = sp_core::ConstU32<8>;
459	type ServiceWeight = MessageQueueServiceWeight;
460	type IdleMaxServiceWeight = MessageQueueServiceWeight;
461}
462
463impl cumulus_pallet_aura_ext::Config for Runtime {}
464
465parameter_types! {
466	/// The asset ID for the asset that we use to pay for message delivery fees.
467	pub FeeAssetId: AssetId = AssetId(xcm_config::WndLocation::get());
468	/// The base fee for the message delivery fees.
469	pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
470}
471
472pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
473	FeeAssetId,
474	BaseDeliveryFee,
475	TransactionByteFee,
476	XcmpQueue,
477>;
478
479impl cumulus_pallet_xcmp_queue::Config for Runtime {
480	type RuntimeEvent = RuntimeEvent;
481	type ChannelInfo = ParachainSystem;
482	type VersionWrapper = PolkadotXcm;
483	// Enqueue XCMP messages from siblings for later processing.
484	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
485	type MaxInboundSuspended = ConstU32<1_000>;
486	type MaxActiveOutboundChannels = ConstU32<128>;
487	// Most on-chain HRMP channels are configured to use 102400 bytes of max message size, so we
488	// need to set the page size larger than that until we reduce the channel size on-chain.
489	type MaxPageSize = ConstU32<{ 103 * 1024 }>;
490	type ControllerOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Fellows>;
491	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
492	type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
493	type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
494}
495
496impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime {
497	// This must be the same as the `ChannelInfo` from the `Config`:
498	type ChannelList = ParachainSystem;
499}
500
501parameter_types! {
502	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
503}
504
505pub const PERIOD: u32 = 6 * HOURS;
506pub const OFFSET: u32 = 0;
507
508impl pallet_session::Config for Runtime {
509	type RuntimeEvent = RuntimeEvent;
510	type ValidatorId = <Self as frame_system::Config>::AccountId;
511	// we don't have stash and controller, thus we don't need the convert as well.
512	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
513	type ShouldEndSession = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
514	type NextSessionRotation = pallet_session::PeriodicSessions<ConstU32<PERIOD>, ConstU32<OFFSET>>;
515	type SessionManager = CollatorSelection;
516	// Essentially just Aura, but let's be pedantic.
517	type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
518	type Keys = SessionKeys;
519	type DisablingStrategy = ();
520	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
521	type Currency = Balances;
522	type KeyDeposit = ();
523}
524
525impl pallet_aura::Config for Runtime {
526	type AuthorityId = AuraId;
527	type DisabledValidators = ();
528	type MaxAuthorities = ConstU32<100_000>;
529	type AllowMultipleBlocksPerSlot = ConstBool<true>;
530	type SlotDuration = ConstU64<SLOT_DURATION>;
531}
532
533parameter_types! {
534	pub const PotId: PalletId = PalletId(*b"PotStake");
535	pub const SessionLength: BlockNumber = 6 * HOURS;
536	// `StakingAdmin` pluralistic body.
537	pub const StakingAdminBodyId: BodyId = BodyId::Defense;
538}
539
540/// We allow root and the `StakingAdmin` to execute privileged collator selection operations.
541pub type CollatorSelectionUpdateOrigin = EitherOfDiverse<
542	EnsureRoot<AccountId>,
543	EnsureXcm<IsVoiceOfBody<GovernanceLocation, StakingAdminBodyId>>,
544>;
545
546impl pallet_collator_selection::Config for Runtime {
547	type RuntimeEvent = RuntimeEvent;
548	type Currency = Balances;
549	type UpdateOrigin = CollatorSelectionUpdateOrigin;
550	type PotId = PotId;
551	type MaxCandidates = ConstU32<100>;
552	type MinEligibleCollators = ConstU32<4>;
553	type MaxInvulnerables = ConstU32<20>;
554	// should be a multiple of session or things will get inconsistent
555	type KickThreshold = ConstU32<PERIOD>;
556	type ValidatorId = <Self as frame_system::Config>::AccountId;
557	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
558	type ValidatorRegistration = Session;
559	type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
560}
561
562pub const ALLIANCE_MOTION_DURATION: BlockNumber = 5 * DAYS;
563
564parameter_types! {
565	pub const AllianceMotionDuration: BlockNumber = ALLIANCE_MOTION_DURATION;
566	pub MaxProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block;
567}
568pub const ALLIANCE_MAX_PROPOSALS: u32 = 100;
569pub const ALLIANCE_MAX_MEMBERS: u32 = 100;
570
571type AllianceCollective = pallet_collective::Instance1;
572impl pallet_collective::Config<AllianceCollective> for Runtime {
573	type RuntimeOrigin = RuntimeOrigin;
574	type Proposal = RuntimeCall;
575	type RuntimeEvent = RuntimeEvent;
576	type MotionDuration = AllianceMotionDuration;
577	type MaxProposals = ConstU32<ALLIANCE_MAX_PROPOSALS>;
578	type MaxMembers = ConstU32<ALLIANCE_MAX_MEMBERS>;
579	type DefaultVote = pallet_collective::MoreThanMajorityThenPrimeDefaultVote;
580	type SetMembersOrigin = EnsureRoot<AccountId>;
581	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
582	type MaxProposalWeight = MaxProposalWeight;
583	type DisapproveOrigin = EnsureRoot<Self::AccountId>;
584	type KillOrigin = EnsureRoot<Self::AccountId>;
585	type Consideration = ();
586}
587
588pub const MAX_FELLOWS: u32 = ALLIANCE_MAX_MEMBERS;
589pub const MAX_ALLIES: u32 = 100;
590
591parameter_types! {
592	pub const AllyDeposit: Balance = 1_000 * UNITS; // 1,000 WND bond to join as an Ally
593	pub WestendTreasuryAccount: AccountId = WESTEND_TREASURY_PALLET_ID.into_account_truncating();
594	// The number of blocks a member must wait between giving a retirement notice and retiring.
595	// Supposed to be greater than time required to `kick_member` with alliance motion.
596	pub const AllianceRetirementPeriod: BlockNumber = (90 * DAYS) + ALLIANCE_MOTION_DURATION;
597}
598
599impl pallet_alliance::Config for Runtime {
600	type RuntimeEvent = RuntimeEvent;
601	type Proposal = RuntimeCall;
602	type AdminOrigin = RootOrAllianceTwoThirdsMajority;
603	type MembershipManager = RootOrAllianceTwoThirdsMajority;
604	type AnnouncementOrigin = RootOrAllianceTwoThirdsMajority;
605	type Currency = Balances;
606	type Slashed = ToParentTreasury<WestendTreasuryAccount, LocationToAccountId, Runtime>;
607	type InitializeMembers = AllianceMotion;
608	type MembershipChanged = AllianceMotion;
609	type RetirementPeriod = AllianceRetirementPeriod;
610	type IdentityVerifier = (); // Don't block accounts on identity criteria
611	type ProposalProvider = AllianceProposalProvider<Runtime, AllianceCollective>;
612	type MaxProposals = ConstU32<ALLIANCE_MAX_MEMBERS>;
613	type MaxFellows = ConstU32<MAX_FELLOWS>;
614	type MaxAllies = ConstU32<MAX_ALLIES>;
615	type MaxUnscrupulousItems = ConstU32<100>;
616	type MaxWebsiteUrlLength = ConstU32<255>;
617	type MaxAnnouncementsCount = ConstU32<100>;
618	type MaxMembersCount = ConstU32<ALLIANCE_MAX_MEMBERS>;
619	type AllyDeposit = AllyDeposit;
620	type WeightInfo = weights::pallet_alliance::WeightInfo<Runtime>;
621}
622
623parameter_types! {
624	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
625}
626
627#[cfg(not(feature = "runtime-benchmarks"))]
628parameter_types! {
629	pub const MaxScheduledPerBlock: u32 = 50;
630}
631
632#[cfg(feature = "runtime-benchmarks")]
633parameter_types! {
634	pub const MaxScheduledPerBlock: u32 = 200;
635}
636
637impl pallet_scheduler::Config for Runtime {
638	type RuntimeOrigin = RuntimeOrigin;
639	type RuntimeEvent = RuntimeEvent;
640	type PalletsOrigin = OriginCaller;
641	type RuntimeCall = RuntimeCall;
642	type MaximumWeight = MaximumSchedulerWeight;
643	type ScheduleOrigin = EnsureRoot<AccountId>;
644	type MaxScheduledPerBlock = MaxScheduledPerBlock;
645	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
646	type OriginPrivilegeCmp = EqualOrGreatestRootCmp;
647	type Preimages = Preimage;
648	type BlockNumberProvider = frame_system::Pallet<Runtime>;
649}
650
651parameter_types! {
652	pub const PreimageBaseDeposit: Balance = deposit(2, 64);
653	pub const PreimageByteDeposit: Balance = deposit(0, 1);
654	pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
655}
656
657impl pallet_preimage::Config for Runtime {
658	type WeightInfo = weights::pallet_preimage::WeightInfo<Runtime>;
659	type RuntimeEvent = RuntimeEvent;
660	type Currency = Balances;
661	type ManagerOrigin = EnsureRoot<AccountId>;
662	type Consideration = HoldConsideration<
663		AccountId,
664		Balances,
665		PreimageHoldReason,
666		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
667	>;
668}
669
670impl pallet_asset_rate::Config for Runtime {
671	type WeightInfo = weights::pallet_asset_rate::WeightInfo<Runtime>;
672	type RuntimeEvent = RuntimeEvent;
673	type CreateOrigin = EitherOfDiverse<
674		EnsureRoot<AccountId>,
675		EitherOfDiverse<EnsureXcm<IsVoiceOfBody<GovernanceLocation, TreasurerBodyId>>, Fellows>,
676	>;
677	type RemoveOrigin = Self::CreateOrigin;
678	type UpdateOrigin = Self::CreateOrigin;
679	type Currency = Balances;
680	type AssetKind = VersionedLocatableAsset;
681	#[cfg(feature = "runtime-benchmarks")]
682	type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::AssetRateArguments;
683}
684
685// Create the runtime by composing the FRAME pallets that were previously configured.
686construct_runtime!(
687	pub enum Runtime
688	{
689		// System support stuff.
690		System: frame_system = 0,
691		ParachainSystem: cumulus_pallet_parachain_system = 1,
692		Timestamp: pallet_timestamp = 2,
693		ParachainInfo: parachain_info = 3,
694		WeightReclaim: cumulus_pallet_weight_reclaim = 4,
695
696		// Monetary stuff.
697		Balances: pallet_balances = 10,
698		TransactionPayment: pallet_transaction_payment = 11,
699
700		// Collator support. the order of these 5 are important and shall not change.
701		Authorship: pallet_authorship = 20,
702		CollatorSelection: pallet_collator_selection = 21,
703		Session: pallet_session = 22,
704		Aura: pallet_aura = 23,
705		AuraExt: cumulus_pallet_aura_ext = 24,
706
707		// XCM helpers.
708		XcmpQueue: cumulus_pallet_xcmp_queue = 30,
709		PolkadotXcm: pallet_xcm = 31,
710		CumulusXcm: cumulus_pallet_xcm = 32,
711		MessageQueue: pallet_message_queue = 34,
712
713		// Handy utilities.
714		Utility: pallet_utility = 40,
715		Multisig: pallet_multisig = 41,
716		Proxy: pallet_proxy = 42,
717		Preimage: pallet_preimage = 43,
718		Scheduler: pallet_scheduler = 44,
719		AssetRate: pallet_asset_rate = 45,
720
721		// The main stage.
722
723		// The Alliance.
724		Alliance: pallet_alliance = 50,
725		AllianceMotion: pallet_collective::<Instance1> = 51,
726
727		// The Fellowship.
728		// pub type FellowshipCollectiveInstance = pallet_ranked_collective::Instance1;
729		FellowshipCollective: pallet_ranked_collective::<Instance1> = 60,
730		// pub type FellowshipReferendaInstance = pallet_referenda::Instance1;
731		FellowshipReferenda: pallet_referenda::<Instance1> = 61,
732		FellowshipOrigins: pallet_fellowship_origins = 62,
733		// pub type FellowshipCoreInstance = pallet_core_fellowship::Instance1;
734		FellowshipCore: pallet_core_fellowship::<Instance1> = 63,
735		// pub type FellowshipSalaryInstance = pallet_salary::Instance1;
736		FellowshipSalary: pallet_salary::<Instance1> = 64,
737		// pub type FellowshipTreasuryInstance = pallet_treasury::Instance1;
738		FellowshipTreasury: pallet_treasury::<Instance1> = 65,
739
740		// Ambassador Program.
741		AmbassadorCollective: pallet_ranked_collective::<Instance2> = 70,
742		AmbassadorReferenda: pallet_referenda::<Instance2> = 71,
743		AmbassadorOrigins: pallet_ambassador_origins = 72,
744		AmbassadorCore: pallet_core_fellowship::<Instance2> = 73,
745		AmbassadorSalary: pallet_salary::<Instance2> = 74,
746		AmbassadorContent: pallet_collective_content::<Instance1> = 75,
747
748		StateTrieMigration: pallet_state_trie_migration = 80,
749
750		// The Secretary Collective
751		// pub type SecretaryCollectiveInstance = pallet_ranked_collective::instance3;
752		SecretaryCollective: pallet_ranked_collective::<Instance3> = 90,
753		// pub type SecretarySalaryInstance = pallet_salary::Instance3;
754		SecretarySalary: pallet_salary::<Instance3> = 91,
755	}
756);
757
758/// The address format for describing accounts.
759pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
760/// Block type as expected by this runtime.
761pub type Block = generic::Block<Header, UncheckedExtrinsic>;
762/// A Block signed with a Justification
763pub type SignedBlock = generic::SignedBlock<Block>;
764/// BlockId type as expected by this runtime.
765pub type BlockId = generic::BlockId<Block>;
766/// The extension to the basic transaction logic.
767pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
768	Runtime,
769	(
770		frame_system::AuthorizeCall<Runtime>,
771		frame_system::CheckNonZeroSender<Runtime>,
772		frame_system::CheckSpecVersion<Runtime>,
773		frame_system::CheckTxVersion<Runtime>,
774		frame_system::CheckGenesis<Runtime>,
775		frame_system::CheckEra<Runtime>,
776		frame_system::CheckNonce<Runtime>,
777		frame_system::CheckWeight<Runtime>,
778	),
779>;
780
781/// Unchecked extrinsic type as expected by this runtime.
782pub type UncheckedExtrinsic =
783	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
784/// All migrations executed on runtime upgrade as a nested tuple of types implementing
785/// `OnRuntimeUpgrade`. Included migrations must be idempotent.
786type Migrations = (
787	// unreleased
788	pallet_collator_selection::migration::v2::MigrationToV2<Runtime>,
789	// unreleased
790	cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4<Runtime>,
791	cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5<Runtime>,
792	// permanent
793	pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
794	// unreleased
795	pallet_core_fellowship::migration::MigrateV0ToV1<Runtime, FellowshipCoreInstance>,
796	// unreleased
797	pallet_core_fellowship::migration::MigrateV0ToV1<Runtime, AmbassadorCoreInstance>,
798	cumulus_pallet_aura_ext::migration::MigrateV0ToV1<Runtime>,
799	pallet_session::migrations::v1::MigrateV0ToV1<
800		Runtime,
801		pallet_session::migrations::v1::InitOffenceSeverity<Runtime>,
802	>,
803);
804
805/// Executive: handles dispatch to the various modules.
806pub type Executive = frame_executive::Executive<
807	Runtime,
808	Block,
809	frame_system::ChainContext<Runtime>,
810	Runtime,
811	AllPalletsWithSystem,
812>;
813
814#[cfg(feature = "runtime-benchmarks")]
815mod benches {
816	frame_benchmarking::define_benchmarks!(
817		[frame_system, SystemBench::<Runtime>]
818		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
819		[pallet_balances, Balances]
820		[pallet_message_queue, MessageQueue]
821		[pallet_multisig, Multisig]
822		[pallet_proxy, Proxy]
823		[pallet_session, SessionBench::<Runtime>]
824		[pallet_utility, Utility]
825		[pallet_timestamp, Timestamp]
826		[pallet_transaction_payment, TransactionPayment]
827		[pallet_collator_selection, CollatorSelection]
828		[cumulus_pallet_parachain_system, ParachainSystem]
829		[cumulus_pallet_xcmp_queue, XcmpQueue]
830		[pallet_alliance, Alliance]
831		[pallet_collective, AllianceMotion]
832		[pallet_preimage, Preimage]
833		[pallet_scheduler, Scheduler]
834		[pallet_referenda, FellowshipReferenda]
835		[pallet_ranked_collective, FellowshipCollective]
836		[pallet_core_fellowship, FellowshipCore]
837		[pallet_salary, FellowshipSalary]
838		[pallet_treasury, FellowshipTreasury]
839		[pallet_referenda, AmbassadorReferenda]
840		[pallet_ranked_collective, AmbassadorCollective]
841		[pallet_collective_content, AmbassadorContent]
842		[pallet_core_fellowship, AmbassadorCore]
843		[pallet_salary, AmbassadorSalary]
844		[pallet_ranked_collective, SecretaryCollective]
845		[pallet_salary, SecretarySalary]
846		[pallet_asset_rate, AssetRate]
847		[cumulus_pallet_weight_reclaim, WeightReclaim]
848		// XCM
849		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
850		// NOTE: Make sure you point to the individual modules below.
851		[pallet_xcm_benchmarks::fungible, XcmBalances]
852		[pallet_xcm_benchmarks::generic, XcmGeneric]
853	);
854}
855
856impl_runtime_apis! {
857	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
858		fn slot_duration() -> sp_consensus_aura::SlotDuration {
859			sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
860		}
861
862		fn authorities() -> Vec<AuraId> {
863			pallet_aura::Authorities::<Runtime>::get().into_inner()
864		}
865	}
866
867	impl cumulus_primitives_core::RelayParentOffsetApi<Block> for Runtime {
868		fn relay_parent_offset() -> u32 {
869			0
870		}
871	}
872
873	impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
874		fn can_build_upon(
875			included_hash: <Block as BlockT>::Hash,
876			slot: cumulus_primitives_aura::Slot,
877		) -> bool {
878			ConsensusHook::can_build_upon(included_hash, slot)
879		}
880	}
881
882	impl sp_api::Core<Block> for Runtime {
883		fn version() -> RuntimeVersion {
884			VERSION
885		}
886
887		fn execute_block(block: Block) {
888			Executive::execute_block(block)
889		}
890
891		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
892			Executive::initialize_block(header)
893		}
894	}
895
896	impl sp_api::Metadata<Block> for Runtime {
897		fn metadata() -> OpaqueMetadata {
898			OpaqueMetadata::new(Runtime::metadata().into())
899		}
900
901		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
902			Runtime::metadata_at_version(version)
903		}
904
905		fn metadata_versions() -> alloc::vec::Vec<u32> {
906			Runtime::metadata_versions()
907		}
908	}
909
910	impl sp_block_builder::BlockBuilder<Block> for Runtime {
911		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
912			Executive::apply_extrinsic(extrinsic)
913		}
914
915		fn finalize_block() -> <Block as BlockT>::Header {
916			Executive::finalize_block()
917		}
918
919		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
920			data.create_extrinsics()
921		}
922
923		fn check_inherents(
924			block: Block,
925			data: sp_inherents::InherentData,
926		) -> sp_inherents::CheckInherentsResult {
927			data.check_extrinsics(&block)
928		}
929	}
930
931	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
932		fn validate_transaction(
933			source: TransactionSource,
934			tx: <Block as BlockT>::Extrinsic,
935			block_hash: <Block as BlockT>::Hash,
936		) -> TransactionValidity {
937			Executive::validate_transaction(source, tx, block_hash)
938		}
939	}
940
941	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
942		fn offchain_worker(header: &<Block as BlockT>::Header) {
943			Executive::offchain_worker(header)
944		}
945	}
946
947	impl sp_session::SessionKeys<Block> for Runtime {
948		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
949			SessionKeys::generate(seed)
950		}
951
952		fn decode_session_keys(
953			encoded: Vec<u8>,
954		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
955			SessionKeys::decode_into_raw_public_keys(&encoded)
956		}
957	}
958
959	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
960		fn account_nonce(account: AccountId) -> Nonce {
961			System::account_nonce(account)
962		}
963	}
964
965	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
966		fn query_info(
967			uxt: <Block as BlockT>::Extrinsic,
968			len: u32,
969		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
970			TransactionPayment::query_info(uxt, len)
971		}
972		fn query_fee_details(
973			uxt: <Block as BlockT>::Extrinsic,
974			len: u32,
975		) -> pallet_transaction_payment::FeeDetails<Balance> {
976			TransactionPayment::query_fee_details(uxt, len)
977		}
978		fn query_weight_to_fee(weight: Weight) -> Balance {
979			TransactionPayment::weight_to_fee(weight)
980		}
981		fn query_length_to_fee(length: u32) -> Balance {
982			TransactionPayment::length_to_fee(length)
983		}
984	}
985
986	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
987		for Runtime
988	{
989		fn query_call_info(
990			call: RuntimeCall,
991			len: u32,
992		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
993			TransactionPayment::query_call_info(call, len)
994		}
995		fn query_call_fee_details(
996			call: RuntimeCall,
997			len: u32,
998		) -> pallet_transaction_payment::FeeDetails<Balance> {
999			TransactionPayment::query_call_fee_details(call, len)
1000		}
1001		fn query_weight_to_fee(weight: Weight) -> Balance {
1002			TransactionPayment::weight_to_fee(weight)
1003		}
1004		fn query_length_to_fee(length: u32) -> Balance {
1005			TransactionPayment::length_to_fee(length)
1006		}
1007	}
1008
1009	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
1010		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
1011			let acceptable_assets = vec![AssetId(xcm_config::WndLocation::get())];
1012			PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
1013		}
1014
1015		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
1016			use crate::xcm_config::XcmConfig;
1017
1018			type Trader = <XcmConfig as xcm_executor::Config>::Trader;
1019
1020			PolkadotXcm::query_weight_to_asset_fee::<Trader>(weight, asset)
1021		}
1022
1023		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
1024			PolkadotXcm::query_xcm_weight(message)
1025		}
1026
1027		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
1028			PolkadotXcm::query_delivery_fees(destination, message)
1029		}
1030	}
1031
1032	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
1033		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1034			PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
1035		}
1036
1037		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1038			PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
1039		}
1040	}
1041
1042	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
1043		fn convert_location(location: VersionedLocation) -> Result<
1044			AccountId,
1045			xcm_runtime_apis::conversions::Error
1046		> {
1047			xcm_runtime_apis::conversions::LocationToAccountHelper::<
1048				AccountId,
1049				LocationToAccountId,
1050			>::convert_location(location)
1051		}
1052	}
1053
1054	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
1055		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1056			PolkadotXcm::is_trusted_reserve(asset, location)
1057		}
1058		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1059			PolkadotXcm::is_trusted_teleporter(asset, location)
1060		}
1061	}
1062
1063	impl xcm_runtime_apis::authorized_aliases::AuthorizedAliasersApi<Block> for Runtime {
1064		fn authorized_aliasers(target: VersionedLocation) -> Result<
1065			Vec<xcm_runtime_apis::authorized_aliases::OriginAliaser>,
1066			xcm_runtime_apis::authorized_aliases::Error
1067		> {
1068			PolkadotXcm::authorized_aliasers(target)
1069		}
1070		fn is_authorized_alias(origin: VersionedLocation, target: VersionedLocation) -> Result<
1071			bool,
1072			xcm_runtime_apis::authorized_aliases::Error
1073		> {
1074			PolkadotXcm::is_authorized_alias(origin, target)
1075		}
1076	}
1077
1078	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
1079		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
1080			ParachainSystem::collect_collation_info(header)
1081		}
1082	}
1083
1084	#[cfg(feature = "try-runtime")]
1085	impl frame_try_runtime::TryRuntime<Block> for Runtime {
1086		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1087			let weight = Executive::try_runtime_upgrade(checks).unwrap();
1088			(weight, RuntimeBlockWeights::get().max_block)
1089		}
1090
1091		fn execute_block(
1092			block: Block,
1093			state_root_check: bool,
1094			signature_check: bool,
1095			select: frame_try_runtime::TryStateSelect,
1096		) -> Weight {
1097			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
1098			// have a backtrace here.
1099			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1100		}
1101	}
1102
1103	#[cfg(feature = "runtime-benchmarks")]
1104	impl frame_benchmarking::Benchmark<Block> for Runtime {
1105		fn benchmark_metadata(extra: bool) -> (
1106			Vec<frame_benchmarking::BenchmarkList>,
1107			Vec<frame_support::traits::StorageInfo>,
1108		) {
1109			use frame_benchmarking::BenchmarkList;
1110			use frame_support::traits::StorageInfoTrait;
1111			use frame_system_benchmarking::Pallet as SystemBench;
1112			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1113			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1114			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1115
1116			// This is defined once again in dispatch_benchmark, because list_benchmarks!
1117			// and add_benchmarks! are macros exported by define_benchmarks! macros and those types
1118			// are referenced in that call.
1119			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1120			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1121
1122			let mut list = Vec::<BenchmarkList>::new();
1123			list_benchmarks!(list, extra);
1124
1125			let storage_info = AllPalletsWithSystem::storage_info();
1126			(list, storage_info)
1127		}
1128
1129		#[allow(non_local_definitions)]
1130		fn dispatch_benchmark(
1131			config: frame_benchmarking::BenchmarkConfig
1132		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1133			use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
1134			use sp_storage::TrackedStorageKey;
1135
1136			use frame_system_benchmarking::Pallet as SystemBench;
1137			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1138			impl frame_system_benchmarking::Config for Runtime {
1139				fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
1140					ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
1141					Ok(())
1142				}
1143
1144				fn verify_set_code() {
1145					System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
1146				}
1147			}
1148
1149			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1150			impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1151			use xcm_config::WndLocation;
1152			use testnet_parachains_constants::westend::locations::{AssetHubParaId, AssetHubLocation};
1153
1154			parameter_types! {
1155				pub ExistentialDepositAsset: Option<Asset> = Some((
1156					WndLocation::get(),
1157					ExistentialDeposit::get()
1158				).into());
1159			}
1160
1161			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
1162			impl pallet_xcm::benchmarking::Config for Runtime {
1163				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1164						xcm_config::XcmConfig,
1165						ExistentialDepositAsset,
1166						PriceForSiblingParachainDelivery,
1167						AssetHubParaId,
1168						ParachainSystem,
1169					>;
1170
1171				fn reachable_dest() -> Option<Location> {
1172					Some(AssetHubLocation::get())
1173				}
1174
1175				fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
1176					// Relay/native token can be teleported between Collectives and Relay.
1177					Some((
1178						Asset {
1179							fun: Fungible(ExistentialDeposit::get()),
1180							id: AssetId(WndLocation::get())
1181						}.into(),
1182						AssetHubLocation::get(),
1183					))
1184				}
1185
1186				fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
1187					// Reserve transfers are disabled on Collectives.
1188					None
1189				}
1190
1191				fn set_up_complex_asset_transfer(
1192				) -> Option<(Assets, u32, Location, alloc::boxed::Box<dyn FnOnce()>)> {
1193					// Collectives only supports teleports to system parachain.
1194					// Relay/native token can be teleported between Collectives and Relay.
1195					let native_location = WndLocation::get();
1196					let dest = AssetHubLocation::get();
1197					pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
1198						native_location,
1199						dest
1200					)
1201				}
1202
1203				fn get_asset() -> Asset {
1204					Asset {
1205						id: AssetId(WndLocation::get()),
1206						fun: Fungible(ExistentialDeposit::get()),
1207					}
1208				}
1209			}
1210
1211			impl pallet_xcm_benchmarks::Config for Runtime {
1212				type XcmConfig = xcm_config::XcmConfig;
1213				type AccountIdConverter = xcm_config::LocationToAccountId;
1214				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
1215						xcm_config::XcmConfig,
1216						ExistentialDepositAsset,
1217						PriceForSiblingParachainDelivery,
1218						AssetHubParaId,
1219						ParachainSystem
1220					>;
1221				fn valid_destination() -> Result<Location, BenchmarkError> {
1222					Ok(AssetHubLocation::get())
1223				}
1224				fn worst_case_holding(_depositable_count: u32) -> Assets {
1225					// just concrete assets according to relay chain.
1226					let assets: Vec<Asset> = vec![
1227						Asset {
1228							id: AssetId(WndLocation::get()),
1229							fun: Fungible(1_000_000 * UNITS),
1230						}
1231					];
1232					assets.into()
1233				}
1234			}
1235
1236			parameter_types! {
1237				pub TrustedTeleporter: Option<(Location, Asset)> = Some((
1238					AssetHubLocation::get(),
1239					Asset { fun: Fungible(UNITS), id: AssetId(WndLocation::get()) },
1240				));
1241				pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
1242				pub const TrustedReserve: Option<(Location, Asset)> = None;
1243			}
1244
1245			impl pallet_xcm_benchmarks::fungible::Config for Runtime {
1246				type TransactAsset = Balances;
1247
1248				type CheckedAccount = CheckedAccount;
1249				type TrustedTeleporter = TrustedTeleporter;
1250				type TrustedReserve = TrustedReserve;
1251
1252				fn get_asset() -> Asset {
1253					Asset {
1254						id: AssetId(WndLocation::get()),
1255						fun: Fungible(UNITS),
1256					}
1257				}
1258			}
1259
1260			impl pallet_xcm_benchmarks::generic::Config for Runtime {
1261				type TransactAsset = Balances;
1262				type RuntimeCall = RuntimeCall;
1263
1264				fn worst_case_response() -> (u64, Response) {
1265					(0u64, Response::Version(Default::default()))
1266				}
1267
1268				fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
1269					Err(BenchmarkError::Skip)
1270				}
1271
1272				fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
1273					Err(BenchmarkError::Skip)
1274				}
1275
1276				fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
1277					Ok((AssetHubLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
1278				}
1279
1280				fn subscribe_origin() -> Result<Location, BenchmarkError> {
1281					Ok(AssetHubLocation::get())
1282				}
1283
1284				fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
1285					let origin = AssetHubLocation::get();
1286					let assets: Assets = (AssetId(WndLocation::get()), 1_000 * UNITS).into();
1287					let ticket = Location { parents: 0, interior: Here };
1288					Ok((origin, ticket, assets))
1289				}
1290
1291				fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
1292					Ok((Asset {
1293						id: AssetId(WndLocation::get()),
1294						fun: Fungible(1_000_000 * UNITS),
1295					}, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
1296				}
1297
1298				fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
1299					Err(BenchmarkError::Skip)
1300				}
1301
1302				fn export_message_origin_and_destination(
1303				) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
1304					Err(BenchmarkError::Skip)
1305				}
1306
1307				fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
1308					// Any location can alias to an internal location.
1309					// Here parachain 1000 aliases to an internal account.
1310					let origin = Location::new(1, [Parachain(1000)]);
1311					let target = Location::new(1, [Parachain(1000), AccountId32 { id: [128u8; 32], network: None }]);
1312					Ok((origin, target))
1313				}
1314			}
1315
1316			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
1317			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
1318
1319			use frame_support::traits::WhitelistedStorageKeys;
1320			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1321
1322			let mut batches = Vec::<BenchmarkBatch>::new();
1323			let params = (&config, &whitelist);
1324			add_benchmarks!(params, batches);
1325
1326			Ok(batches)
1327		}
1328	}
1329
1330	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1331		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1332			build_state::<RuntimeGenesisConfig>(config)
1333		}
1334
1335		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1336			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1337		}
1338
1339		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1340			genesis_config_presets::preset_names()
1341		}
1342	}
1343
1344	impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
1345		fn parachain_id() -> ParaId {
1346			ParachainInfo::parachain_id()
1347		}
1348	}
1349}
1350
1351cumulus_pallet_parachain_system::register_validate_block! {
1352	Runtime = Runtime,
1353	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
1354}
1355
1356parameter_types! {
1357	// 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)
1358	pub const MigrationSignedDepositPerItem: Balance = CENTS;
1359	pub const MigrationSignedDepositBase: Balance = 2_000 * CENTS;
1360	pub const MigrationMaxKeyLen: u32 = 512;
1361}
1362
1363impl pallet_state_trie_migration::Config for Runtime {
1364	type RuntimeEvent = RuntimeEvent;
1365	type Currency = Balances;
1366	type RuntimeHoldReason = RuntimeHoldReason;
1367	type SignedDepositPerItem = MigrationSignedDepositPerItem;
1368	type SignedDepositBase = MigrationSignedDepositBase;
1369	// An origin that can control the whole pallet: should be Root, or a part of your council.
1370	type ControlOrigin = frame_system::EnsureSignedBy<RootMigController, AccountId>;
1371	// specific account for the migration, can trigger the signed migrations.
1372	type SignedFilter = frame_system::EnsureSignedBy<MigController, AccountId>;
1373
1374	// Replace this with weight based on your runtime.
1375	type WeightInfo = pallet_state_trie_migration::weights::SubstrateWeight<Runtime>;
1376
1377	type MaxKeyLen = MigrationMaxKeyLen;
1378}
1379
1380frame_support::ord_parameter_types! {
1381	pub const MigController: AccountId = AccountId::from(hex_literal::hex!("8458ed39dc4b6f6c7255f7bc42be50c2967db126357c999d44e12ca7ac80dc52"));
1382	pub const RootMigController: AccountId = AccountId::from(hex_literal::hex!("8458ed39dc4b6f6c7255f7bc42be50c2967db126357c999d44e12ca7ac80dc52"));
1383}
1384
1385#[test]
1386fn ensure_key_ss58() {
1387	use frame_support::traits::SortedMembers;
1388	use sp_core::crypto::Ss58Codec;
1389	let acc =
1390		AccountId::from_ss58check("5F4EbSkZz18X36xhbsjvDNs6NuZ82HyYtq5UiJ1h9SBHJXZD").unwrap();
1391	assert_eq!(acc, MigController::sorted_members()[0]);
1392	let acc =
1393		AccountId::from_ss58check("5F4EbSkZz18X36xhbsjvDNs6NuZ82HyYtq5UiJ1h9SBHJXZD").unwrap();
1394	assert_eq!(acc, RootMigController::sorted_members()[0]);
1395}