referrerpolicy=no-referrer-when-downgrade

kitchensink_runtime/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! The Substrate runtime. This can be compiled with `#[no_std]`, ready for Wasm.
19
20#![cfg_attr(not(feature = "std"), no_std)]
21// `construct_runtime!` does a lot of recursion and requires us to increase the limits.
22#![recursion_limit = "1024"]
23
24extern crate alloc;
25
26#[cfg(feature = "runtime-benchmarks")]
27use pallet_asset_rate::AssetKindFactory;
28#[cfg(feature = "runtime-benchmarks")]
29use pallet_multi_asset_bounties::ArgumentsFactory as PalletMultiAssetBountiesArgumentsFactory;
30#[cfg(feature = "runtime-benchmarks")]
31use pallet_treasury::ArgumentsFactory as PalletTreasuryArgumentsFactory;
32#[cfg(feature = "runtime-benchmarks")]
33use polkadot_sdk::sp_core::crypto::FromEntropy;
34
35use polkadot_sdk::*;
36
37use alloc::{vec, vec::Vec};
38use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
39use frame_election_provider_support::{
40	bounds::{ElectionBounds, ElectionBoundsBuilder},
41	onchain, BalancingConfig, ElectionDataProvider, SequentialPhragmen, VoteWeight,
42};
43use frame_support::{
44	derive_impl,
45	dispatch::DispatchClass,
46	dynamic_params::{dynamic_pallet_params, dynamic_params},
47	genesis_builder_helper::{build_state, get_preset},
48	instances::{Instance1, Instance2},
49	ord_parameter_types,
50	pallet_prelude::Get,
51	parameter_types,
52	traits::{
53		fungible::{
54			Balanced, Credit, HoldConsideration, ItemOf, NativeFromLeft, NativeOrWithId, UnionOf,
55		},
56		tokens::{
57			imbalance::{ResolveAssetTo, ResolveTo},
58			nonfungibles_v2::Inspect,
59			pay::PayAssetFromAccount,
60			GetSalary, PayFromAccount, PayWithFungibles,
61		},
62		AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU16, ConstU32, ConstU64,
63		ConstantStoragePrice, Contains, Currency, EitherOfDiverse, EnsureOriginWithArg,
64		EqualPrivilegeOnly, InsideBoth, InstanceFilter, KeyOwnerProofSystem, LinearStoragePrice,
65		LockIdentifier, Nothing, OnUnbalanced, WithdrawReasons,
66	},
67	weights::{
68		constants::{
69			BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND,
70		},
71		ConstantMultiplier, Weight,
72	},
73	BoundedVec, PalletId,
74};
75use frame_system::{
76	limits::{BlockLength, BlockWeights},
77	EnsureAuthorized, EnsureRoot, EnsureRootWithSuccess, EnsureSigned, EnsureSignedBy,
78	EnsureWithSuccess,
79};
80use hrmp_primitives::{MessageToPara, MessageToRelay};
81pub use node_primitives::{AccountId, Signature};
82use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Moment, Nonce};
83use pallet_asset_conversion::{AccountIdConverter, Ascending, Chain, WithFirstAsset};
84use pallet_asset_conversion_tx_payment::SwapAssetAdapter;
85use pallet_assets_precompiles::{InlineIdConfig, ERC20};
86use pallet_broker::{CoreAssignment, CoreIndex, CoretimeInterface, PartsOf57600, TaskId};
87use pallet_election_provider_multi_phase::{GeometricDepositBase, SolutionAccuracyOf};
88use pallet_identity::legacy::IdentityInfo;
89use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
90use pallet_nfts::PalletFeatures;
91use pallet_nis::WithMaximumOf;
92use pallet_nomination_pools::PoolId;
93use pallet_revive::evm::runtime::EthExtra;
94use pallet_session::historical as pallet_session_historical;
95use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
96pub use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment};
97use pallet_tx_pause::RuntimeCallNameOf;
98use pallet_vesting_precompiles::Vesting as VestingPrecompile;
99use polkadot_primitives::Id as ParaId;
100use polkadot_runtime_parachains::{
101	hrmp::deposits::{DepositAction, DepositChangeRequest, DepositError, OnDepositSet},
102	origin as parachains_origin,
103};
104use sp_api::impl_runtime_apis;
105use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
106use sp_consensus_beefy::{
107	ecdsa_crypto::{AuthorityId as BeefyId, Signature as BeefySignature},
108	mmr::MmrLeafVersion,
109};
110use sp_consensus_grandpa::AuthorityId as GrandpaId;
111use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
112use sp_inherents::{CheckInherentsResult, InherentData};
113use sp_runtime::{
114	curve::PiecewiseLinear,
115	generic, impl_opaque_keys, str_array as s,
116	traits::{
117		self, AccountIdConversion, BlakeTwo256, Block as BlockT, Bounded, ConvertInto,
118		MaybeConvert, NumberFor, OpaqueKeys, SaturatedConversion, StaticLookup,
119	},
120	transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
121	ApplyExtrinsicResult, Debug, FixedPointNumber, FixedU128, MultiSignature, MultiSigner, Perbill,
122	Percent, Permill, Perquintill,
123};
124use sp_std::{borrow::Cow, prelude::*};
125use sp_version::RuntimeVersion;
126use static_assertions::const_assert;
127
128#[cfg(any(feature = "std", test))]
129pub use frame_system::Call as SystemCall;
130#[cfg(any(feature = "std", test))]
131pub use pallet_balances::Call as BalancesCall;
132#[cfg(any(feature = "std", test))]
133pub use pallet_sudo::Call as SudoCall;
134#[cfg(any(feature = "std", test))]
135pub use sp_runtime::BuildStorage;
136
137pub use pallet_staking::StakerStatus;
138
139/// Implementations of some helper traits passed into runtime modules as associated types.
140pub mod impls;
141#[cfg(not(feature = "runtime-benchmarks"))]
142use impls::AllianceIdentityVerifier;
143use impls::AllianceProposalProvider;
144
145/// Constant values used within the runtime.
146pub mod constants;
147use constants::{currency::*, time::*};
148use sp_runtime::generic::Era;
149
150/// Generated voter bag information.
151mod voter_bags;
152
153/// Runtime API definition for assets.
154pub mod assets_api;
155
156/// Genesis presets used by this runtime.
157pub mod genesis_config_presets;
158
159// Make the WASM binary available.
160#[cfg(feature = "std")]
161include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
162
163/// Max size for serialized extrinsic params for this testing runtime.
164/// This is a quite arbitrary but empirically battle tested value.
165#[cfg(test)]
166pub const CALL_PARAMS_MAX_SIZE: usize = 512;
167
168/// Wasm binary unwrapped. If built with `SKIP_WASM_BUILD`, the function panics.
169#[cfg(feature = "std")]
170pub fn wasm_binary_unwrap() -> &'static [u8] {
171	WASM_BINARY.expect(
172		"Development wasm binary is not available. This means the client is built with \
173		 `SKIP_WASM_BUILD` flag and it is only usable for production chains. Please rebuild with \
174		 the flag disabled.",
175	)
176}
177
178/// Runtime version.
179#[sp_version::runtime_version]
180pub const VERSION: RuntimeVersion = RuntimeVersion {
181	spec_name: alloc::borrow::Cow::Borrowed("node"),
182	impl_name: alloc::borrow::Cow::Borrowed("substrate-node"),
183	authoring_version: 10,
184	// Per convention: if the runtime behavior changes, increment spec_version
185	// and set impl_version to 0. If only runtime
186	// implementation changes and behavior does not, then leave spec_version as
187	// is and increment impl_version.
188	spec_version: 271,
189	impl_version: 0,
190	apis: RUNTIME_API_VERSIONS,
191	transaction_version: 2,
192	system_version: 1,
193};
194
195/// The BABE epoch configuration at genesis.
196pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration =
197	sp_consensus_babe::BabeEpochConfiguration {
198		c: PRIMARY_PROBABILITY,
199		allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots,
200	};
201
202type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
203
204/// We assume that ~10% of the block weight is consumed by `on_initialize` handlers.
205/// This is used to limit the maximal weight of a single extrinsic.
206const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
207/// We allow `Normal` extrinsics to fill up the block up to 95%, the rest can be used
208/// by  Operational  extrinsics.
209const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(95);
210/// We allow for 2 seconds of compute with a 6 second average block time, with maximum proof size.
211const MAXIMUM_BLOCK_WEIGHT: Weight =
212	Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);
213
214parameter_types! {
215	pub const BlockHashCount: BlockNumber = 2400;
216	pub const Version: RuntimeVersion = VERSION;
217	pub RuntimeBlockLength: BlockLength = BlockLength::builder()
218		.max_length(15 * 1024 * 1024)
219		.modify_max_length_for_class(DispatchClass::Normal, |m| {
220			*m = NORMAL_DISPATCH_RATIO * *m
221		})
222		.build();
223	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
224		.base_block(BlockExecutionWeight::get())
225		.for_class(DispatchClass::all(), |weights| {
226			weights.base_extrinsic = ExtrinsicBaseWeight::get();
227		})
228		.for_class(DispatchClass::Normal, |weights| {
229			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
230		})
231		.for_class(DispatchClass::Operational, |weights| {
232			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
233			// Operational transactions have some extra reserved space, so that they
234			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
235			weights.reserved = Some(
236				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
237			);
238		})
239		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
240		.build_or_panic();
241	pub MaxCollectivesProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block;
242}
243
244const_assert!(NORMAL_DISPATCH_RATIO.deconstruct() >= AVERAGE_ON_INITIALIZE_RATIO.deconstruct());
245
246/// Calls that can bypass the safe-mode pallet.
247pub struct SafeModeWhitelistedCalls;
248impl Contains<RuntimeCall> for SafeModeWhitelistedCalls {
249	fn contains(call: &RuntimeCall) -> bool {
250		match call {
251			RuntimeCall::System(_) | RuntimeCall::SafeMode(_) | RuntimeCall::TxPause(_) => true,
252			_ => false,
253		}
254	}
255}
256
257/// Calls that cannot be paused by the tx-pause pallet.
258pub struct TxPauseWhitelistedCalls;
259/// Whitelist `Balances::transfer_keep_alive`, all others are pauseable.
260impl Contains<RuntimeCallNameOf<Runtime>> for TxPauseWhitelistedCalls {
261	fn contains(full_name: &RuntimeCallNameOf<Runtime>) -> bool {
262		match (full_name.0.as_slice(), full_name.1.as_slice()) {
263			(b"Balances", b"transfer_keep_alive") => true,
264			_ => false,
265		}
266	}
267}
268
269#[cfg(feature = "runtime-benchmarks")]
270pub struct AssetRateArguments;
271#[cfg(feature = "runtime-benchmarks")]
272impl AssetKindFactory<NativeOrWithId<u32>> for AssetRateArguments {
273	fn create_asset_kind(seed: u32) -> NativeOrWithId<u32> {
274		if !seed.is_multiple_of(2) {
275			NativeOrWithId::Native
276		} else {
277			NativeOrWithId::WithId(seed / 2)
278		}
279	}
280}
281
282#[cfg(feature = "runtime-benchmarks")]
283pub struct PalletTreasuryArguments;
284#[cfg(feature = "runtime-benchmarks")]
285impl PalletTreasuryArgumentsFactory<NativeOrWithId<u32>, AccountId> for PalletTreasuryArguments {
286	fn create_asset_kind(seed: u32) -> NativeOrWithId<u32> {
287		if !seed.is_multiple_of(2) {
288			NativeOrWithId::Native
289		} else {
290			NativeOrWithId::WithId(seed / 2)
291		}
292	}
293
294	fn create_beneficiary(seed: [u8; 32]) -> AccountId {
295		AccountId::from_entropy(&mut seed.as_slice()).unwrap()
296	}
297}
298
299#[cfg(feature = "runtime-benchmarks")]
300pub struct PalletMultiAssetBountiesArguments;
301#[cfg(feature = "runtime-benchmarks")]
302impl PalletMultiAssetBountiesArgumentsFactory<NativeOrWithId<u32>, AccountId, u128>
303	for PalletMultiAssetBountiesArguments
304{
305	fn create_asset_kind(seed: u32) -> NativeOrWithId<u32> {
306		if !seed.is_multiple_of(2) {
307			NativeOrWithId::Native
308		} else {
309			NativeOrWithId::WithId(seed / 2)
310		}
311	}
312
313	fn create_beneficiary(seed: [u8; 32]) -> AccountId {
314		AccountId::from_entropy(&mut seed.as_slice()).unwrap()
315	}
316}
317
318impl pallet_tx_pause::Config for Runtime {
319	type RuntimeEvent = RuntimeEvent;
320	type RuntimeCall = RuntimeCall;
321	type PauseOrigin = EnsureRoot<AccountId>;
322	type UnpauseOrigin = EnsureRoot<AccountId>;
323	type WhitelistedCalls = TxPauseWhitelistedCalls;
324	type MaxNameLen = ConstU32<256>;
325	type WeightInfo = pallet_tx_pause::weights::SubstrateWeight<Runtime>;
326}
327
328parameter_types! {
329	pub const EnterDuration: BlockNumber = 4 * HOURS;
330	pub const EnterDepositAmount: Balance = 2_000_000 * DOLLARS;
331	pub const ExtendDuration: BlockNumber = 2 * HOURS;
332	pub const ExtendDepositAmount: Balance = 1_000_000 * DOLLARS;
333	pub const ReleaseDelay: u32 = 2 * DAYS;
334}
335
336impl pallet_safe_mode::Config for Runtime {
337	type RuntimeEvent = RuntimeEvent;
338	type Currency = Balances;
339	type RuntimeHoldReason = RuntimeHoldReason;
340	type WhitelistedCalls = SafeModeWhitelistedCalls;
341	type EnterDuration = EnterDuration;
342	type EnterDepositAmount = EnterDepositAmount;
343	type ExtendDuration = ExtendDuration;
344	type ExtendDepositAmount = ExtendDepositAmount;
345	type ForceEnterOrigin = EnsureRootWithSuccess<AccountId, ConstU32<9>>;
346	type ForceExtendOrigin = EnsureRootWithSuccess<AccountId, ConstU32<11>>;
347	type ForceExitOrigin = EnsureRoot<AccountId>;
348	type ForceDepositOrigin = EnsureRoot<AccountId>;
349	type ReleaseDelay = ReleaseDelay;
350	type Notify = ();
351	type WeightInfo = pallet_safe_mode::weights::SubstrateWeight<Runtime>;
352}
353
354#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
355impl frame_system::Config for Runtime {
356	type BaseCallFilter = InsideBoth<SafeMode, TxPause>;
357	type BlockWeights = RuntimeBlockWeights;
358	type BlockLength = RuntimeBlockLength;
359	type DbWeight = RocksDbWeight;
360	type Nonce = Nonce;
361	type Hash = Hash;
362	type AccountId = AccountId;
363	type Lookup = Indices;
364	type Block = Block;
365	type BlockHashCount = BlockHashCount;
366	type Version = Version;
367	type AccountData = pallet_balances::AccountData<Balance>;
368	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
369	type SS58Prefix = ConstU16<42>;
370	type MaxConsumers = ConstU32<16>;
371	type MultiBlockMigrator = MultiBlockMigrations;
372	type SingleBlockMigrations = Migrations;
373}
374
375impl pallet_insecure_randomness_collective_flip::Config for Runtime {}
376
377impl pallet_example_tasks::Config for Runtime {
378	type RuntimeTask = RuntimeTask;
379	type WeightInfo = pallet_example_tasks::weights::SubstrateWeight<Runtime>;
380}
381
382impl pallet_example_mbm::Config for Runtime {}
383
384impl pallet_utility::Config for Runtime {
385	type RuntimeEvent = RuntimeEvent;
386	type RuntimeCall = RuntimeCall;
387	type PalletsOrigin = OriginCaller;
388	type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
389}
390
391parameter_types! {
392	// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
393	pub const DepositBase: Balance = deposit(1, 88);
394	// Additional storage item size of 32 bytes.
395	pub const DepositFactor: Balance = deposit(0, 32);
396}
397
398impl pallet_multisig::Config for Runtime {
399	type RuntimeEvent = RuntimeEvent;
400	type RuntimeCall = RuntimeCall;
401	type Currency = Balances;
402	type DepositBase = DepositBase;
403	type DepositFactor = DepositFactor;
404	type MaxSignatories = ConstU32<100>;
405	type WeightInfo = pallet_multisig::weights::SubstrateWeight<Runtime>;
406	type BlockNumberProvider = frame_system::Pallet<Runtime>;
407}
408
409parameter_types! {
410	// One storage item; key size 32, value size 8; .
411	pub const ProxyDepositBase: Balance = deposit(1, 8);
412	// Additional storage item size of 33 bytes.
413	pub const ProxyDepositFactor: Balance = deposit(0, 33);
414	pub const AnnouncementDepositBase: Balance = deposit(1, 8);
415	pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
416}
417
418/// The type used to represent the kinds of proxying allowed.
419#[derive(
420	Copy,
421	Clone,
422	Eq,
423	PartialEq,
424	Ord,
425	PartialOrd,
426	Encode,
427	Decode,
428	DecodeWithMemTracking,
429	Debug,
430	MaxEncodedLen,
431	scale_info::TypeInfo,
432)]
433pub enum ProxyType {
434	Any,
435	NonTransfer,
436	Governance,
437	Staking,
438}
439impl Default for ProxyType {
440	fn default() -> Self {
441		Self::Any
442	}
443}
444impl InstanceFilter<RuntimeCall> for ProxyType {
445	fn filter(&self, c: &RuntimeCall) -> bool {
446		match self {
447			ProxyType::Any => true,
448			ProxyType::NonTransfer => !matches!(
449				c,
450				RuntimeCall::Balances(..) |
451					RuntimeCall::Assets(..) |
452					RuntimeCall::Uniques(..) |
453					RuntimeCall::Nfts(..) |
454					RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) |
455					RuntimeCall::Indices(pallet_indices::Call::transfer { .. })
456			),
457			ProxyType::Governance => matches!(
458				c,
459				RuntimeCall::Democracy(..) |
460					RuntimeCall::Council(..) |
461					RuntimeCall::Society(..) |
462					RuntimeCall::TechnicalCommittee(..) |
463					RuntimeCall::Elections(..) |
464					RuntimeCall::Treasury(..)
465			),
466			ProxyType::Staking => {
467				matches!(c, RuntimeCall::Staking(..) | RuntimeCall::FastUnstake(..))
468			},
469		}
470	}
471	fn is_superset(&self, o: &Self) -> bool {
472		match (self, o) {
473			(x, y) if x == y => true,
474			(ProxyType::Any, _) => true,
475			(_, ProxyType::Any) => false,
476			(ProxyType::NonTransfer, _) => true,
477			_ => false,
478		}
479	}
480}
481
482impl pallet_proxy::Config for Runtime {
483	type RuntimeEvent = RuntimeEvent;
484	type RuntimeCall = RuntimeCall;
485	type Currency = Balances;
486	type ProxyType = ProxyType;
487	type ProxyDepositBase = ProxyDepositBase;
488	type ProxyDepositFactor = ProxyDepositFactor;
489	type MaxProxies = ConstU32<32>;
490	type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
491	type MaxPending = ConstU32<32>;
492	type CallHasher = BlakeTwo256;
493	type AnnouncementDepositBase = AnnouncementDepositBase;
494	type AnnouncementDepositFactor = AnnouncementDepositFactor;
495	type BlockNumberProvider = frame_system::Pallet<Runtime>;
496}
497
498parameter_types! {
499	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
500		RuntimeBlockWeights::get().max_block;
501}
502
503impl pallet_scheduler::Config for Runtime {
504	type RuntimeEvent = RuntimeEvent;
505	type RuntimeOrigin = RuntimeOrigin;
506	type PalletsOrigin = OriginCaller;
507	type RuntimeCall = RuntimeCall;
508	type MaximumWeight = MaximumSchedulerWeight;
509	type ScheduleOrigin = EnsureRoot<AccountId>;
510	#[cfg(feature = "runtime-benchmarks")]
511	type MaxScheduledPerBlock = ConstU32<512>;
512	#[cfg(not(feature = "runtime-benchmarks"))]
513	type MaxScheduledPerBlock = ConstU32<50>;
514	type WeightInfo = pallet_scheduler::weights::SubstrateWeight<Runtime>;
515	type OriginPrivilegeCmp = EqualPrivilegeOnly;
516	type Preimages = Preimage;
517	type BlockNumberProvider = frame_system::Pallet<Runtime>;
518}
519
520impl pallet_glutton::Config for Runtime {
521	type RuntimeEvent = RuntimeEvent;
522	type AdminOrigin = EnsureRoot<AccountId>;
523	type WeightInfo = pallet_glutton::weights::SubstrateWeight<Runtime>;
524}
525
526parameter_types! {
527	pub const PreimageHoldReason: RuntimeHoldReason =
528		RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
529}
530
531impl pallet_preimage::Config for Runtime {
532	type WeightInfo = pallet_preimage::weights::SubstrateWeight<Runtime>;
533	type RuntimeEvent = RuntimeEvent;
534	type Currency = Balances;
535	type ManagerOrigin = EnsureRoot<AccountId>;
536	type Consideration = HoldConsideration<
537		AccountId,
538		Balances,
539		PreimageHoldReason,
540		LinearStoragePrice<
541			dynamic_params::storage::BaseDeposit,
542			dynamic_params::storage::ByteDeposit,
543			Balance,
544		>,
545	>;
546}
547
548parameter_types! {
549	// NOTE: Currently it is not possible to change the epoch duration after the chain has started.
550	//       Attempting to do so will brick block production.
551	pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS;
552	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
553	pub const ReportLongevity: u64 =
554		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
555}
556
557impl pallet_babe::Config for Runtime {
558	type EpochDuration = EpochDuration;
559	type ExpectedBlockTime = ExpectedBlockTime;
560	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
561	type DisabledValidators = Session;
562	type WeightInfo = ();
563	type MaxAuthorities = MaxAuthorities;
564	type MaxNominators = MaxNominators;
565	type KeyOwnerProof = sp_session::MembershipProof;
566	type EquivocationReportSystem =
567		pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
568}
569
570parameter_types! {
571	pub const IndexDeposit: Balance = 1 * DOLLARS;
572}
573
574impl pallet_indices::Config for Runtime {
575	type AccountIndex = AccountIndex;
576	type Currency = Balances;
577	type Deposit = IndexDeposit;
578	type RuntimeEvent = RuntimeEvent;
579	type WeightInfo = pallet_indices::weights::SubstrateWeight<Runtime>;
580}
581
582parameter_types! {
583	pub const ExistentialDeposit: Balance = 1 * DOLLARS;
584	// For weight estimation, we assume that the most locks on an individual account will be 50.
585	// This number may need to be adjusted in the future if this assumption no longer holds true.
586	pub const MaxLocks: u32 = 50;
587	pub const MaxReserves: u32 = 50;
588}
589
590impl pallet_balances::Config for Runtime {
591	type RuntimeHoldReason = RuntimeHoldReason;
592	type RuntimeFreezeReason = RuntimeFreezeReason;
593	type MaxLocks = MaxLocks;
594	type MaxReserves = MaxReserves;
595	type ReserveIdentifier = [u8; 8];
596	type Balance = Balance;
597	type DustRemoval = ();
598	type RuntimeEvent = RuntimeEvent;
599	type ExistentialDeposit = ExistentialDeposit;
600	type AccountStore = frame_system::Pallet<Runtime>;
601	type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
602	type DoneSlashHandler = ();
603}
604
605parameter_types! {
606	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
607	pub const OperationalFeeMultiplier: u8 = 5;
608	pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25);
609	pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(1, 100_000);
610	pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10u128);
611	pub MaximumMultiplier: Multiplier = Bounded::max_value();
612}
613
614impl pallet_transaction_payment::Config for Runtime {
615	type RuntimeEvent = RuntimeEvent;
616	type OnChargeTransaction = FungibleAdapter<Balances, ResolveTo<TreasuryAccount, Balances>>;
617	type OperationalFeeMultiplier = OperationalFeeMultiplier;
618	type WeightToFee = pallet_revive::evm::fees::BlockRatioFee<1, 1, Self, Balance>;
619	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
620	type FeeMultiplierUpdate = TargetedFeeAdjustment<
621		Self,
622		TargetBlockFullness,
623		AdjustmentVariable,
624		MinimumMultiplier,
625		MaximumMultiplier,
626	>;
627	type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Runtime>;
628}
629
630pub type AssetsFreezerInstance = pallet_assets_freezer::Instance1;
631impl pallet_assets_freezer::Config<AssetsFreezerInstance> for Runtime {
632	type RuntimeFreezeReason = RuntimeFreezeReason;
633	type RuntimeEvent = RuntimeEvent;
634}
635
636impl pallet_asset_conversion_tx_payment::Config for Runtime {
637	type RuntimeEvent = RuntimeEvent;
638	type AssetId = NativeOrWithId<u32>;
639	type OnChargeAssetTransaction = SwapAssetAdapter<
640		Native,
641		NativeAndAssets,
642		AssetConversion,
643		ResolveAssetTo<TreasuryAccount, NativeAndAssets>,
644	>;
645	type WeightInfo = pallet_asset_conversion_tx_payment::weights::SubstrateWeight<Runtime>;
646	#[cfg(feature = "runtime-benchmarks")]
647	type BenchmarkHelper = AssetConversionTxHelper;
648}
649
650impl pallet_skip_feeless_payment::Config for Runtime {
651	type RuntimeEvent = RuntimeEvent;
652}
653
654parameter_types! {
655	pub const MinimumPeriod: Moment = SLOT_DURATION / 2;
656}
657
658impl pallet_timestamp::Config for Runtime {
659	type Moment = Moment;
660	type OnTimestampSet = Babe;
661	type MinimumPeriod = MinimumPeriod;
662	type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
663}
664
665impl pallet_authorship::Config for Runtime {
666	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
667	type EventHandler = (Staking, ImOnline);
668}
669
670impl_opaque_keys! {
671	pub struct SessionKeys {
672		pub grandpa: Grandpa,
673		pub babe: Babe,
674		pub im_online: ImOnline,
675		pub authority_discovery: AuthorityDiscovery,
676		pub mixnet: Mixnet,
677		pub beefy: Beefy,
678	}
679}
680
681impl pallet_session::Config for Runtime {
682	type RuntimeEvent = RuntimeEvent;
683	type ValidatorId = <Self as frame_system::Config>::AccountId;
684	type ValidatorIdOf = sp_runtime::traits::ConvertInto;
685	type ShouldEndSession = Babe;
686	type NextSessionRotation = Babe;
687	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
688	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
689	type Keys = SessionKeys;
690	type DisablingStrategy = pallet_session::disabling::UpToLimitWithReEnablingDisablingStrategy;
691	type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
692	type Currency = Balances;
693	type KeyDeposit = ();
694}
695
696impl pallet_session::historical::Config for Runtime {
697	type RuntimeEvent = RuntimeEvent;
698	type FullIdentification = ();
699	type FullIdentificationOf = pallet_staking::UnitIdentificationOf<Self>;
700}
701
702pallet_staking_reward_curve::build! {
703	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
704		min_inflation: 0_025_000,
705		max_inflation: 0_100_000,
706		ideal_stake: 0_500_000,
707		falloff: 0_050_000,
708		max_piece_count: 40,
709		test_precision: 0_005_000,
710	);
711}
712
713parameter_types! {
714	pub const SessionsPerEra: sp_staking::SessionIndex = 6;
715	pub const BondingDuration: sp_staking::EraIndex = 24 * 28;
716	pub const SlashDeferDuration: sp_staking::EraIndex = 24 * 7; // 1/4 the bonding duration.
717	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
718	pub const MaxNominators: u32 = 64;
719	pub const MaxControllersInDeprecationBatch: u32 = 5900;
720	pub OffchainRepeat: BlockNumber = 5;
721	pub HistoryDepth: u32 = 84;
722}
723
724/// Upper limit on the number of NPOS nominations.
725const MAX_QUOTA_NOMINATIONS: u32 = 16;
726
727pub struct StakingBenchmarkingConfig;
728impl pallet_staking::BenchmarkingConfig for StakingBenchmarkingConfig {
729	type MaxNominators = ConstU32<5000>;
730	type MaxValidators = ConstU32<1000>;
731}
732
733impl pallet_staking::Config for Runtime {
734	type OldCurrency = Balances;
735	type Currency = Balances;
736	type CurrencyBalance = Balance;
737	type UnixTime = Timestamp;
738	type CurrencyToVote = sp_staking::currency_to_vote::U128CurrencyToVote;
739	type RewardRemainder = ResolveTo<TreasuryAccount, Balances>;
740	type RuntimeEvent = RuntimeEvent;
741	type RuntimeHoldReason = RuntimeHoldReason;
742	type Slash = ResolveTo<TreasuryAccount, Balances>; // send the slashed funds to the treasury.
743	type Reward = (); // rewards are minted from the void
744	type SessionsPerEra = SessionsPerEra;
745	type BondingDuration = BondingDuration;
746	type SlashDeferDuration = SlashDeferDuration;
747	/// A super-majority of the council can cancel the slash.
748	type AdminOrigin = EitherOfDiverse<
749		EnsureRoot<AccountId>,
750		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 3, 4>,
751	>;
752	type SessionInterface = Self;
753	type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
754	type NextNewSession = Session;
755	type MaxExposurePageSize = ConstU32<256>;
756	type ElectionProvider = ElectionProviderMultiPhase;
757	type GenesisElectionProvider = onchain::OnChainExecution<OnChainSeqPhragmen>;
758	type VoterList = VoterList;
759	type NominationsQuota = pallet_staking::FixedNominationsQuota<MAX_QUOTA_NOMINATIONS>;
760	// This a placeholder, to be introduced in the next PR as an instance of bags-list
761	type TargetList = pallet_staking::UseValidatorsMap<Self>;
762	type MaxUnlockingChunks = ConstU32<32>;
763	type MaxControllersInDeprecationBatch = MaxControllersInDeprecationBatch;
764	type HistoryDepth = HistoryDepth;
765	type EventListeners = (NominationPools, DelegatedStaking);
766	type WeightInfo = pallet_staking::weights::SubstrateWeight<Runtime>;
767	type BenchmarkingConfig = StakingBenchmarkingConfig;
768	type Filter = Nothing;
769	type MaxValidatorSet = ConstU32<1000>;
770}
771
772parameter_types! {
773	pub const DapPalletId: PalletId = pallet_dap::DAP_PALLET_ID;
774	pub const DapIssuanceCadence: u64 = 0; // drip every block
775	pub const DapMaxElapsedPerDrip: u64 = 600_000;
776}
777
778impl pallet_dap::Config for Runtime {
779	type Currency = Balances;
780	type PalletId = DapPalletId;
781	type IssuanceCurve = ();
782	type BudgetRecipients = (pallet_dap::Pallet<Runtime>,);
783	type Time = Timestamp;
784	type IssuanceCadence = DapIssuanceCadence;
785	type MaxElapsedPerDrip = DapMaxElapsedPerDrip;
786	type BudgetOrigin = EnsureRoot<AccountId>;
787	type WeightInfo = ();
788}
789
790impl pallet_fast_unstake::Config for Runtime {
791	type RuntimeEvent = RuntimeEvent;
792	type ControlOrigin = frame_system::EnsureRoot<AccountId>;
793	type BatchSize = ConstU32<64>;
794	type Deposit = ConstU128<{ DOLLARS }>;
795	type Currency = Balances;
796	type Staking = Staking;
797	type MaxErasToCheckPerBlock = ConstU32<1>;
798	type WeightInfo = ();
799}
800parameter_types! {
801	// phase durations. 1/4 of the last session for each.
802	pub const SignedPhase: u32 = EPOCH_DURATION_IN_BLOCKS / 4;
803	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_BLOCKS / 4;
804
805	// signed config
806	pub const SignedRewardBase: Balance = 1 * DOLLARS;
807	pub const SignedFixedDeposit: Balance = 1 * DOLLARS;
808	pub const SignedDepositIncreaseFactor: Percent = Percent::from_percent(10);
809	pub const SignedDepositByte: Balance = 1 * CENTS;
810
811	// miner configs
812	pub const MultiPhaseUnsignedPriority: TransactionPriority = StakingUnsignedPriority::get() - 1u64;
813	pub MinerMaxWeight: Weight = RuntimeBlockWeights::get()
814		.get(DispatchClass::Normal)
815		.max_extrinsic.expect("Normal extrinsics have a weight limit configured; qed")
816		.saturating_sub(BlockExecutionWeight::get());
817	// Solution can occupy 90% of normal block size
818	pub MinerMaxLength: u32 = Perbill::from_rational(9u32, 10) *
819		*RuntimeBlockLength::get()
820		.max
821		.get(DispatchClass::Normal);
822}
823
824frame_election_provider_support::generate_solution_type!(
825	#[compact]
826	pub struct NposSolution16::<
827		VoterIndex = u32,
828		TargetIndex = u16,
829		Accuracy = sp_runtime::PerU16,
830		MaxVoters = MaxElectingVotersSolution,
831	>(16)
832);
833
834parameter_types! {
835	// Note: the EPM in this runtime runs the election on-chain. The election bounds must be
836	// carefully set so that an election round fits in one block.
837	pub ElectionBoundsMultiPhase: ElectionBounds = ElectionBoundsBuilder::default()
838		.voters_count(10_000.into()).targets_count(1_500.into()).build();
839	pub ElectionBoundsOnChain: ElectionBounds = ElectionBoundsBuilder::default()
840		.voters_count(5_000.into()).targets_count(1_250.into()).build();
841
842	pub MaxNominations: u32 = <NposSolution16 as frame_election_provider_support::NposSolution>::LIMIT as u32;
843	pub MaxElectingVotersSolution: u32 = 40_000;
844	// The maximum winners that can be elected by the Election pallet which is equivalent to the
845	// maximum active validators the staking pallet can have.
846	pub MaxActiveValidators: u32 = 1000;
847}
848
849/// The numbers configured here could always be more than the the maximum limits of staking pallet
850/// to ensure election snapshot will not run out of memory. For now, we set them to smaller values
851/// since the staking is bounded and the weight pipeline takes hours for this single pallet.
852pub struct ElectionProviderBenchmarkConfig;
853impl pallet_election_provider_multi_phase::BenchmarkingConfig for ElectionProviderBenchmarkConfig {
854	const VOTERS: [u32; 2] = [1000, 2000];
855	const TARGETS: [u32; 2] = [500, 1000];
856	const ACTIVE_VOTERS: [u32; 2] = [500, 800];
857	const DESIRED_TARGETS: [u32; 2] = [200, 400];
858	const SNAPSHOT_MAXIMUM_VOTERS: u32 = 1000;
859	const MINER_MAXIMUM_VOTERS: u32 = 1000;
860	const MAXIMUM_TARGETS: u32 = 300;
861}
862
863/// Maximum number of iterations for balancing that will be executed in the embedded OCW
864/// miner of election provider multi phase.
865pub const MINER_MAX_ITERATIONS: u32 = 10;
866
867/// A source of random balance for NposSolver, which is meant to be run by the OCW election miner.
868pub struct OffchainRandomBalancing;
869impl Get<Option<BalancingConfig>> for OffchainRandomBalancing {
870	fn get() -> Option<BalancingConfig> {
871		use sp_runtime::traits::TrailingZeroInput;
872		let iterations = match MINER_MAX_ITERATIONS {
873			0 => 0,
874			max => {
875				let seed = sp_io::offchain::random_seed();
876				let random = <u32>::decode(&mut TrailingZeroInput::new(&seed))
877					.expect("input is padded with zeroes; qed") %
878					max.saturating_add(1);
879				random as usize
880			},
881		};
882
883		let config = BalancingConfig { iterations, tolerance: 0 };
884		Some(config)
885	}
886}
887
888pub struct OnChainSeqPhragmen;
889impl onchain::Config for OnChainSeqPhragmen {
890	type Sort = ConstBool<true>;
891	type System = Runtime;
892	type Solver = SequentialPhragmen<AccountId, SolutionAccuracyOf<Runtime>>;
893	type DataProvider = Staking;
894	type WeightInfo = frame_election_provider_support::weights::SubstrateWeight<Runtime>;
895	type Bounds = ElectionBoundsOnChain;
896	type MaxBackersPerWinner = MaxElectingVotersSolution;
897	type MaxWinnersPerPage = MaxActiveValidators;
898}
899
900impl pallet_election_provider_multi_phase::MinerConfig for Runtime {
901	type AccountId = AccountId;
902	type MaxLength = MinerMaxLength;
903	type MaxWeight = MinerMaxWeight;
904	type Solution = NposSolution16;
905	type MaxVotesPerVoter =
906	<<Self as pallet_election_provider_multi_phase::Config>::DataProvider as ElectionDataProvider>::MaxVotesPerVoter;
907	type MaxWinners = MaxActiveValidators;
908	type MaxBackersPerWinner = MaxElectingVotersSolution;
909
910	// The unsigned submissions have to respect the weight of the submit_unsigned call, thus their
911	// weight estimate function is wired to this call's weight.
912	fn solution_weight(v: u32, t: u32, a: u32, d: u32) -> Weight {
913		<
914			<Self as pallet_election_provider_multi_phase::Config>::WeightInfo
915			as
916			pallet_election_provider_multi_phase::WeightInfo
917		>::submit_unsigned(v, t, a, d)
918	}
919}
920
921impl pallet_election_provider_multi_phase::Config for Runtime {
922	type RuntimeEvent = RuntimeEvent;
923	type Currency = Balances;
924	type EstimateCallFee = TransactionPayment;
925	type SignedPhase = SignedPhase;
926	type UnsignedPhase = UnsignedPhase;
927	type BetterSignedThreshold = ();
928	type OffchainRepeat = OffchainRepeat;
929	type MinerTxPriority = MultiPhaseUnsignedPriority;
930	type MinerConfig = Self;
931	type SignedMaxSubmissions = ConstU32<10>;
932	type SignedRewardBase = SignedRewardBase;
933	type SignedDepositBase =
934		GeometricDepositBase<Balance, SignedFixedDeposit, SignedDepositIncreaseFactor>;
935	type SignedDepositByte = SignedDepositByte;
936	type SignedMaxRefunds = ConstU32<3>;
937	type SignedDepositWeight = ();
938	type SignedMaxWeight = MinerMaxWeight;
939	type SlashHandler = (); // burn slashes
940	type RewardHandler = (); // rewards are minted from the void
941	type DataProvider = Staking;
942	type Fallback = onchain::OnChainExecution<OnChainSeqPhragmen>;
943	type GovernanceFallback = onchain::OnChainExecution<OnChainSeqPhragmen>;
944	type Solver = SequentialPhragmen<AccountId, SolutionAccuracyOf<Self>, OffchainRandomBalancing>;
945	type ForceOrigin = EnsureRootOrHalfCouncil;
946	type MaxWinners = MaxActiveValidators;
947	type ElectionBounds = ElectionBoundsMultiPhase;
948	type BenchmarkingConfig = ElectionProviderBenchmarkConfig;
949	type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight<Self>;
950	type MaxBackersPerWinner = MaxElectingVotersSolution;
951}
952
953parameter_types! {
954	pub const BagThresholds: &'static [u64] = &voter_bags::THRESHOLDS;
955	pub const AutoRebagNumber: u32 = 10;
956}
957
958type VoterBagsListInstance = pallet_bags_list::Instance1;
959impl pallet_bags_list::Config<VoterBagsListInstance> for Runtime {
960	type RuntimeEvent = RuntimeEvent;
961	type WeightInfo = pallet_bags_list::weights::SubstrateWeight<Runtime>;
962	/// The voter bags-list is loosely kept up to date, and the real source of truth for the score
963	/// of each node is the staking pallet.
964	type ScoreProvider = Staking;
965	type BagThresholds = BagThresholds;
966	type MaxAutoRebagPerBlock = AutoRebagNumber;
967	type Score = VoteWeight;
968}
969
970parameter_types! {
971	pub const DelegatedStakingPalletId: PalletId = PalletId(*b"py/dlstk");
972	pub const SlashRewardFraction: Perbill = Perbill::from_percent(1);
973}
974
975impl pallet_delegated_staking::Config for Runtime {
976	type RuntimeEvent = RuntimeEvent;
977	type PalletId = DelegatedStakingPalletId;
978	type Currency = Balances;
979	type OnSlash = ();
980	type SlashRewardFraction = SlashRewardFraction;
981	type RuntimeHoldReason = RuntimeHoldReason;
982	type CoreStaking = Staking;
983}
984
985parameter_types! {
986	// Buffer (4) + bonding duration (24 * 28).
987	pub const MaxUnbondingPools: u32 = 24 * 28 + 4;
988	pub const NominationPoolsPalletId: PalletId = PalletId(*b"py/nopls");
989	pub const MaxPointsToBalance: u8 = 10;
990}
991
992use sp_runtime::traits::{Convert, Keccak256};
993pub struct BalanceToU256;
994impl Convert<Balance, sp_core::U256> for BalanceToU256 {
995	fn convert(balance: Balance) -> sp_core::U256 {
996		sp_core::U256::from(balance)
997	}
998}
999pub struct U256ToBalance;
1000impl Convert<sp_core::U256, Balance> for U256ToBalance {
1001	fn convert(n: sp_core::U256) -> Balance {
1002		n.try_into().unwrap_or(Balance::MAX)
1003	}
1004}
1005
1006impl pallet_nomination_pools::Config for Runtime {
1007	type WeightInfo = ();
1008	type RuntimeEvent = RuntimeEvent;
1009	type Currency = Balances;
1010	type RuntimeFreezeReason = RuntimeFreezeReason;
1011	type RewardCounter = FixedU128;
1012	type BalanceToU256 = BalanceToU256;
1013	type U256ToBalance = U256ToBalance;
1014	type StakeAdapter =
1015		pallet_nomination_pools::adapter::DelegateStake<Self, Staking, DelegatedStaking>;
1016	type MaxUnbondingPools = MaxUnbondingPools;
1017	type MaxMetadataLen = ConstU32<256>;
1018	type MaxUnbonding = ConstU32<8>;
1019	type PalletId = NominationPoolsPalletId;
1020	type MaxPointsToBalance = MaxPointsToBalance;
1021	type AdminOrigin = EitherOfDiverse<
1022		EnsureRoot<AccountId>,
1023		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 3, 4>,
1024	>;
1025	type BlockNumberProvider = System;
1026	type Filter = Nothing;
1027}
1028
1029parameter_types! {
1030	pub const VoteLockingPeriod: BlockNumber = 30 * DAYS;
1031}
1032
1033impl pallet_conviction_voting::Config for Runtime {
1034	type WeightInfo = pallet_conviction_voting::weights::SubstrateWeight<Self>;
1035	type RuntimeEvent = RuntimeEvent;
1036	type Currency = Balances;
1037	type VoteLockingPeriod = VoteLockingPeriod;
1038	type MaxVotes = ConstU32<512>;
1039	type MaxTurnout = frame_support::traits::TotalIssuanceOf<Balances, Self::AccountId>;
1040	type Polls = Referenda;
1041	type BlockNumberProvider = System;
1042	type VotingHooks = ();
1043}
1044
1045parameter_types! {
1046	pub const AlarmInterval: BlockNumber = 1;
1047	pub const SubmissionDeposit: Balance = 100 * DOLLARS;
1048	pub const UndecidingTimeout: BlockNumber = 28 * DAYS;
1049}
1050
1051pub struct TracksInfo;
1052impl pallet_referenda::TracksInfo<Balance, BlockNumber> for TracksInfo {
1053	type Id = u16;
1054	type RuntimeOrigin = <RuntimeOrigin as frame_support::traits::OriginTrait>::PalletsOrigin;
1055
1056	fn tracks(
1057	) -> impl Iterator<Item = Cow<'static, pallet_referenda::Track<Self::Id, Balance, BlockNumber>>>
1058	{
1059		dynamic_params::referenda::Tracks::get().into_iter().map(Cow::Owned)
1060	}
1061	fn track_for(id: &Self::RuntimeOrigin) -> Result<Self::Id, ()> {
1062		dynamic_params::referenda::Origins::get()
1063			.iter()
1064			.find(|(o, _)| id == o)
1065			.map(|(_, track_id)| *track_id)
1066			.ok_or(())
1067	}
1068}
1069
1070impl pallet_referenda::Config for Runtime {
1071	type WeightInfo = pallet_referenda::weights::SubstrateWeight<Self>;
1072	type RuntimeCall = RuntimeCall;
1073	type RuntimeEvent = RuntimeEvent;
1074	type Scheduler = Scheduler;
1075	type Currency = pallet_balances::Pallet<Self>;
1076	type SubmitOrigin = EnsureSigned<AccountId>;
1077	type CancelOrigin = EnsureRoot<AccountId>;
1078	type KillOrigin = EnsureRoot<AccountId>;
1079	type Slash = ();
1080	type Votes = pallet_conviction_voting::VotesOf<Runtime>;
1081	type Tally = pallet_conviction_voting::TallyOf<Runtime>;
1082	type SubmissionDeposit = SubmissionDeposit;
1083	type MaxQueued = ConstU32<100>;
1084	type UndecidingTimeout = UndecidingTimeout;
1085	type AlarmInterval = AlarmInterval;
1086	type Tracks = TracksInfo;
1087	type Preimages = Preimage;
1088	type BlockNumberProvider = System;
1089}
1090
1091impl pallet_referenda::Config<pallet_referenda::Instance2> for Runtime {
1092	type WeightInfo = pallet_referenda::weights::SubstrateWeight<Self>;
1093	type RuntimeCall = RuntimeCall;
1094	type RuntimeEvent = RuntimeEvent;
1095	type Scheduler = Scheduler;
1096	type Currency = pallet_balances::Pallet<Self>;
1097	type SubmitOrigin = EnsureSigned<AccountId>;
1098	type CancelOrigin = EnsureRoot<AccountId>;
1099	type KillOrigin = EnsureRoot<AccountId>;
1100	type Slash = ();
1101	type Votes = pallet_ranked_collective::Votes;
1102	type Tally = pallet_ranked_collective::TallyOf<Runtime>;
1103	type SubmissionDeposit = SubmissionDeposit;
1104	type MaxQueued = ConstU32<100>;
1105	type UndecidingTimeout = UndecidingTimeout;
1106	type AlarmInterval = AlarmInterval;
1107	type Tracks = TracksInfo;
1108	type Preimages = Preimage;
1109	type BlockNumberProvider = System;
1110}
1111
1112impl pallet_ranked_collective::Config for Runtime {
1113	type WeightInfo = pallet_ranked_collective::weights::SubstrateWeight<Self>;
1114	type RuntimeEvent = RuntimeEvent;
1115	type AddOrigin = EnsureRoot<AccountId>;
1116	type RemoveOrigin = Self::DemoteOrigin;
1117	type PromoteOrigin = EnsureRootWithSuccess<AccountId, ConstU16<65535>>;
1118	type DemoteOrigin = EnsureRootWithSuccess<AccountId, ConstU16<65535>>;
1119	type ExchangeOrigin = EnsureRootWithSuccess<AccountId, ConstU16<65535>>;
1120	type Polls = RankedPolls;
1121	type MinRankOfClass = traits::Identity;
1122	type VoteWeight = pallet_ranked_collective::Geometric;
1123	type MemberSwappedHandler = (CoreFellowship, Salary);
1124	type MaxMemberCount = ();
1125	#[cfg(feature = "runtime-benchmarks")]
1126	type BenchmarkSetup = (CoreFellowship, Salary);
1127}
1128
1129impl pallet_remark::Config for Runtime {
1130	type WeightInfo = pallet_remark::weights::SubstrateWeight<Self>;
1131	type RuntimeEvent = RuntimeEvent;
1132}
1133
1134impl pallet_root_testing::Config for Runtime {
1135	type RuntimeEvent = RuntimeEvent;
1136}
1137
1138parameter_types! {
1139	pub const LaunchPeriod: BlockNumber = 28 * 24 * 60 * MINUTES;
1140	pub const VotingPeriod: BlockNumber = 28 * 24 * 60 * MINUTES;
1141	pub const FastTrackVotingPeriod: BlockNumber = 3 * 24 * 60 * MINUTES;
1142	pub const MinimumDeposit: Balance = 100 * DOLLARS;
1143	pub const EnactmentPeriod: BlockNumber = 30 * 24 * 60 * MINUTES;
1144	pub const CooloffPeriod: BlockNumber = 28 * 24 * 60 * MINUTES;
1145	pub const MaxProposals: u32 = 100;
1146}
1147
1148impl pallet_democracy::Config for Runtime {
1149	type RuntimeEvent = RuntimeEvent;
1150	type Currency = Balances;
1151	type EnactmentPeriod = EnactmentPeriod;
1152	type LaunchPeriod = LaunchPeriod;
1153	type VotingPeriod = VotingPeriod;
1154	type VoteLockingPeriod = EnactmentPeriod; // Same as EnactmentPeriod
1155	type MinimumDeposit = MinimumDeposit;
1156	/// A straight majority of the council can decide what their next motion is.
1157	type ExternalOrigin =
1158		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 2>;
1159	/// A super-majority can have the next scheduled referendum be a straight majority-carries vote.
1160	type ExternalMajorityOrigin =
1161		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 3, 4>;
1162	/// A unanimous council can have the next scheduled referendum be a straight default-carries
1163	/// (NTB) vote.
1164	type ExternalDefaultOrigin =
1165		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 1>;
1166	type SubmitOrigin = EnsureSigned<AccountId>;
1167	/// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote
1168	/// be tabled immediately and with a shorter voting/enactment period.
1169	type FastTrackOrigin =
1170		pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCollective, 2, 3>;
1171	type InstantOrigin =
1172		pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCollective, 1, 1>;
1173	type InstantAllowed = ConstBool<true>;
1174	type FastTrackVotingPeriod = FastTrackVotingPeriod;
1175	// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
1176	type CancellationOrigin =
1177		pallet_collective::EnsureProportionAtLeast<AccountId, CouncilCollective, 2, 3>;
1178	// To cancel a proposal before it has been passed, the technical committee must be unanimous or
1179	// Root must agree.
1180	type CancelProposalOrigin = EitherOfDiverse<
1181		EnsureRoot<AccountId>,
1182		pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCollective, 1, 1>,
1183	>;
1184	type BlacklistOrigin = EnsureRoot<AccountId>;
1185	// Any single technical committee member may veto a coming council proposal, however they can
1186	// only do it once and it lasts only for the cool-off period.
1187	type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>;
1188	type CooloffPeriod = CooloffPeriod;
1189	type Slash = Treasury;
1190	type Scheduler = Scheduler;
1191	type PalletsOrigin = OriginCaller;
1192	type MaxVotes = ConstU32<100>;
1193	type WeightInfo = pallet_democracy::weights::SubstrateWeight<Runtime>;
1194	type MaxProposals = MaxProposals;
1195	type Preimages = Preimage;
1196	type MaxDeposits = ConstU32<100>;
1197	type MaxBlacklisted = ConstU32<100>;
1198}
1199
1200parameter_types! {
1201	pub const CouncilMotionDuration: BlockNumber = 5 * DAYS;
1202	pub const CouncilMaxProposals: u32 = 100;
1203	pub const CouncilMaxMembers: u32 = 100;
1204	pub const ProposalDepositOffset: Balance = ExistentialDeposit::get() + ExistentialDeposit::get();
1205	pub const ProposalHoldReason: RuntimeHoldReason =
1206		RuntimeHoldReason::Council(pallet_collective::HoldReason::ProposalSubmission);
1207}
1208
1209type CouncilCollective = pallet_collective::Instance1;
1210impl pallet_collective::Config<CouncilCollective> for Runtime {
1211	type RuntimeOrigin = RuntimeOrigin;
1212	type Proposal = RuntimeCall;
1213	type RuntimeEvent = RuntimeEvent;
1214	type MotionDuration = CouncilMotionDuration;
1215	type MaxProposals = CouncilMaxProposals;
1216	type MaxMembers = CouncilMaxMembers;
1217	type DefaultVote = pallet_collective::PrimeDefaultVote;
1218	type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
1219	type SetMembersOrigin = EnsureRoot<Self::AccountId>;
1220	type MaxProposalWeight = MaxCollectivesProposalWeight;
1221	type DisapproveOrigin = EnsureRoot<Self::AccountId>;
1222	type KillOrigin = EnsureRoot<Self::AccountId>;
1223	type Consideration = HoldConsideration<
1224		AccountId,
1225		Balances,
1226		ProposalHoldReason,
1227		pallet_collective::deposit::Delayed<
1228			ConstU32<2>,
1229			pallet_collective::deposit::Linear<ConstU32<2>, ProposalDepositOffset>,
1230		>,
1231		u32,
1232	>;
1233}
1234
1235parameter_types! {
1236	pub const CandidacyBond: Balance = 10 * DOLLARS;
1237	// 1 storage item created, key size is 32 bytes, value size is 16+16.
1238	pub const VotingBondBase: Balance = deposit(1, 64);
1239	// additional data per vote is 32 bytes (account id).
1240	pub const VotingBondFactor: Balance = deposit(0, 32);
1241	pub const TermDuration: BlockNumber = 7 * DAYS;
1242	pub const DesiredMembers: u32 = 13;
1243	pub const DesiredRunnersUp: u32 = 7;
1244	pub const MaxVotesPerVoter: u32 = 16;
1245	pub const MaxVoters: u32 = 256;
1246	pub const MaxCandidates: u32 = 128;
1247	pub const ElectionsPhragmenPalletId: LockIdentifier = *b"phrelect";
1248}
1249
1250// Make sure that there are no more than `MaxMembers` members elected via elections-phragmen.
1251const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
1252
1253impl pallet_elections_phragmen::Config for Runtime {
1254	type RuntimeEvent = RuntimeEvent;
1255	type PalletId = ElectionsPhragmenPalletId;
1256	type Currency = Balances;
1257	type ChangeMembers = Council;
1258	// NOTE: this implies that council's genesis members cannot be set directly and must come from
1259	// this module.
1260	type InitializeMembers = Council;
1261	type CurrencyToVote = sp_staking::currency_to_vote::U128CurrencyToVote;
1262	type CandidacyBond = CandidacyBond;
1263	type VotingBondBase = VotingBondBase;
1264	type VotingBondFactor = VotingBondFactor;
1265	type LoserCandidate = ();
1266	type KickedMember = ();
1267	type DesiredMembers = DesiredMembers;
1268	type DesiredRunnersUp = DesiredRunnersUp;
1269	type TermDuration = TermDuration;
1270	type MaxVoters = MaxVoters;
1271	type MaxVotesPerVoter = MaxVotesPerVoter;
1272	type MaxCandidates = MaxCandidates;
1273	type WeightInfo = pallet_elections_phragmen::weights::SubstrateWeight<Runtime>;
1274}
1275
1276parameter_types! {
1277	pub const TechnicalMotionDuration: BlockNumber = 5 * DAYS;
1278	pub const TechnicalMaxProposals: u32 = 100;
1279	pub const TechnicalMaxMembers: u32 = 100;
1280}
1281
1282type TechnicalCollective = pallet_collective::Instance2;
1283impl pallet_collective::Config<TechnicalCollective> for Runtime {
1284	type RuntimeOrigin = RuntimeOrigin;
1285	type Proposal = RuntimeCall;
1286	type RuntimeEvent = RuntimeEvent;
1287	type MotionDuration = TechnicalMotionDuration;
1288	type MaxProposals = TechnicalMaxProposals;
1289	type MaxMembers = TechnicalMaxMembers;
1290	type DefaultVote = pallet_collective::PrimeDefaultVote;
1291	type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
1292	type SetMembersOrigin = EnsureRoot<Self::AccountId>;
1293	type MaxProposalWeight = MaxCollectivesProposalWeight;
1294	type DisapproveOrigin = EnsureRoot<Self::AccountId>;
1295	type KillOrigin = EnsureRoot<Self::AccountId>;
1296	type Consideration = ();
1297}
1298
1299type EnsureRootOrHalfCouncil = EitherOfDiverse<
1300	EnsureRoot<AccountId>,
1301	pallet_collective::EnsureProportionMoreThan<AccountId, CouncilCollective, 1, 2>,
1302>;
1303impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
1304	type RuntimeEvent = RuntimeEvent;
1305	type AddOrigin = EnsureRootOrHalfCouncil;
1306	type RemoveOrigin = EnsureRootOrHalfCouncil;
1307	type SwapOrigin = EnsureRootOrHalfCouncil;
1308	type ResetOrigin = EnsureRootOrHalfCouncil;
1309	type PrimeOrigin = EnsureRootOrHalfCouncil;
1310	type MembershipInitialized = TechnicalCommittee;
1311	type MembershipChanged = TechnicalCommittee;
1312	type MaxMembers = TechnicalMaxMembers;
1313	type WeightInfo = pallet_membership::weights::SubstrateWeight<Runtime>;
1314}
1315
1316parameter_types! {
1317	pub const SpendPeriod: BlockNumber = 1 * DAYS;
1318	pub const Burn: Permill = Permill::from_percent(50);
1319	pub const TipCountdown: BlockNumber = 1 * DAYS;
1320	pub const TipFindersFee: Percent = Percent::from_percent(20);
1321	pub const TipReportDepositBase: Balance = 1 * DOLLARS;
1322	pub const DataDepositPerByte: Balance = 1 * CENTS;
1323	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
1324	pub const MaximumReasonLength: u32 = 300;
1325	pub const MaxApprovals: u32 = 100;
1326	pub const MaxBalance: Balance = Balance::MAX;
1327	pub const SpendPayoutPeriod: BlockNumber = 30 * DAYS;
1328}
1329
1330impl pallet_treasury::Config for Runtime {
1331	type PalletId = TreasuryPalletId;
1332	type Currency = Balances;
1333	type RejectOrigin = EitherOfDiverse<
1334		EnsureRoot<AccountId>,
1335		pallet_collective::EnsureProportionMoreThan<AccountId, CouncilCollective, 1, 2>,
1336	>;
1337	type RuntimeEvent = RuntimeEvent;
1338	type SpendPeriod = SpendPeriod;
1339	type Burn = Burn;
1340	type BurnDestination = ();
1341	type SpendFunds = Bounties;
1342	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;
1343	type MaxApprovals = MaxApprovals;
1344	type SpendOrigin = EnsureWithSuccess<EnsureRoot<AccountId>, AccountId, MaxBalance>;
1345	type AssetKind = NativeOrWithId<u32>;
1346	type Beneficiary = AccountId;
1347	type BeneficiaryLookup = Indices;
1348	type Paymaster = PayAssetFromAccount<NativeAndAssets, TreasuryAccount>;
1349	type BalanceConverter = AssetRate;
1350	type PayoutPeriod = SpendPayoutPeriod;
1351	type BlockNumberProvider = System;
1352	#[cfg(feature = "runtime-benchmarks")]
1353	type BenchmarkHelper = PalletTreasuryArguments;
1354}
1355
1356impl pallet_asset_rate::Config for Runtime {
1357	type CreateOrigin = EnsureRoot<AccountId>;
1358	type RemoveOrigin = EnsureRoot<AccountId>;
1359	type UpdateOrigin = EnsureRoot<AccountId>;
1360	type Currency = Balances;
1361	type AssetKind = NativeOrWithId<u32>;
1362	type RuntimeEvent = RuntimeEvent;
1363	type WeightInfo = pallet_asset_rate::weights::SubstrateWeight<Runtime>;
1364	#[cfg(feature = "runtime-benchmarks")]
1365	type BenchmarkHelper = AssetRateArguments;
1366}
1367
1368parameter_types! {
1369	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);
1370	pub const BountyValueMinimum: Balance = 5 * DOLLARS;
1371	pub const BountyDepositBase: Balance = 1 * DOLLARS;
1372	pub const CuratorDepositFromFeeMultiplier: Permill = Permill::from_percent(50);
1373	pub const CuratorDepositMin: Balance = 1 * DOLLARS;
1374	pub const CuratorDepositMax: Balance = 100 * DOLLARS;
1375	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;
1376	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;
1377}
1378
1379impl pallet_bounties::Config for Runtime {
1380	type RuntimeEvent = RuntimeEvent;
1381	type BountyDepositBase = BountyDepositBase;
1382	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
1383	type BountyUpdatePeriod = BountyUpdatePeriod;
1384	type CuratorDepositMultiplier = CuratorDepositFromFeeMultiplier;
1385	type CuratorDepositMin = CuratorDepositMin;
1386	type CuratorDepositMax = CuratorDepositMax;
1387	type BountyValueMinimum = BountyValueMinimum;
1388	type DataDepositPerByte = DataDepositPerByte;
1389	type MaximumReasonLength = MaximumReasonLength;
1390	type WeightInfo = pallet_bounties::weights::SubstrateWeight<Runtime>;
1391	type ChildBountyManager = ChildBounties;
1392	type OnSlash = Treasury;
1393	type TransferAllAssets = pallet_bounties::TransferFungible<AccountId, Balances>;
1394}
1395
1396parameter_types! {
1397	/// Allocate at most 20% of each block for message processing.
1398	///
1399	/// Is set to 20% since the scheduler can already consume a maximum of 80%.
1400	pub MessageQueueServiceWeight: Option<Weight> = Some(Perbill::from_percent(20) * RuntimeBlockWeights::get().max_block);
1401}
1402
1403impl pallet_message_queue::Config for Runtime {
1404	type RuntimeEvent = RuntimeEvent;
1405	type WeightInfo = ();
1406	/// NOTE: Always set this to `NoopMessageProcessor` for benchmarking.
1407	type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<u32>;
1408	type Size = u32;
1409	type QueueChangeHandler = ();
1410	type QueuePausedQuery = ();
1411	type HeapSize = ConstU32<{ 64 * 1024 }>;
1412	type MaxStale = ConstU32<128>;
1413	type ServiceWeight = MessageQueueServiceWeight;
1414	type IdleMaxServiceWeight = ();
1415}
1416
1417parameter_types! {
1418	pub const ChildBountyValueMinimum: Balance = 1 * DOLLARS;
1419	pub const MaxActiveChildBountyCount: u32 = 5;
1420}
1421
1422impl pallet_child_bounties::Config for Runtime {
1423	type RuntimeEvent = RuntimeEvent;
1424	type MaxActiveChildBountyCount = MaxActiveChildBountyCount;
1425	type ChildBountyValueMinimum = ChildBountyValueMinimum;
1426	type WeightInfo = pallet_child_bounties::weights::SubstrateWeight<Runtime>;
1427}
1428
1429parameter_types! {
1430	pub const CuratorDepositFromValueMultiplier: Permill = Permill::from_percent(10);
1431	pub const CuratorHoldReason: RuntimeHoldReason =
1432		RuntimeHoldReason::MultiAssetBounties(pallet_multi_asset_bounties::HoldReason::CuratorDeposit);
1433}
1434
1435impl pallet_multi_asset_bounties::Config for Runtime {
1436	type Balance = Balance;
1437	type RejectOrigin = EitherOfDiverse<
1438		EnsureRoot<AccountId>,
1439		pallet_collective::EnsureProportionMoreThan<AccountId, CouncilCollective, 1, 2>,
1440	>;
1441	type SpendOrigin = EnsureWithSuccess<EnsureRoot<AccountId>, AccountId, MaxBalance>;
1442	type AssetKind = NativeOrWithId<u32>;
1443	type Beneficiary = AccountId;
1444	type BeneficiaryLookup = Indices;
1445	type BountyValueMinimum = BountyValueMinimum;
1446	type ChildBountyValueMinimum = ChildBountyValueMinimum;
1447	type MaxActiveChildBountyCount = MaxActiveChildBountyCount;
1448	type WeightInfo = pallet_multi_asset_bounties::weights::SubstrateWeight<Runtime>;
1449	type FundingSource = pallet_multi_asset_bounties::PalletIdAsFundingSource<
1450		TreasuryPalletId,
1451		Runtime,
1452		sp_runtime::traits::Identity,
1453	>;
1454	type BountySource = pallet_multi_asset_bounties::BountySourceFromPalletId<
1455		TreasuryPalletId,
1456		pallet_multi_asset_bounties::BountyAccountPrefix,
1457		Runtime,
1458		sp_runtime::traits::Identity,
1459	>;
1460	type ChildBountySource = pallet_multi_asset_bounties::ChildBountySourceFromPalletId<
1461		TreasuryPalletId,
1462		pallet_multi_asset_bounties::ChildBountyAccountPrefix,
1463		Runtime,
1464		sp_runtime::traits::Identity,
1465	>;
1466	type Paymaster = PayWithFungibles<NativeAndAssets, AccountId>;
1467	type BalanceConverter = AssetRate;
1468	type Preimages = Preimage;
1469	type Consideration = HoldConsideration<
1470		AccountId,
1471		Balances,
1472		CuratorHoldReason,
1473		pallet_multi_asset_bounties::CuratorDepositAmount<
1474			CuratorDepositFromValueMultiplier,
1475			CuratorDepositMin,
1476			CuratorDepositMax,
1477			Balance,
1478		>,
1479		Balance,
1480	>;
1481	#[cfg(feature = "runtime-benchmarks")]
1482	type BenchmarkHelper = PalletMultiAssetBountiesArguments;
1483}
1484
1485impl pallet_assets_precompiles::ForeignAssetsConfig for Runtime {
1486	type ForeignAssetId = u32;
1487	#[cfg(feature = "runtime-benchmarks")]
1488	type AssetsInstance = Instance1;
1489}
1490
1491impl pallet_assets_precompiles::PermitConfig for Runtime {
1492	type ChainId = ConstU64<420_420_420>;
1493	type WeightInfo = pallet_assets_precompiles::weights::SubstrateWeight<Runtime>;
1494}
1495
1496impl pallet_tips::Config for Runtime {
1497	type RuntimeEvent = RuntimeEvent;
1498	type DataDepositPerByte = DataDepositPerByte;
1499	type MaximumReasonLength = MaximumReasonLength;
1500	type Tippers = Elections;
1501	type TipCountdown = TipCountdown;
1502	type TipFindersFee = TipFindersFee;
1503	type TipReportDepositBase = TipReportDepositBase;
1504	type MaxTipAmount = ConstU128<{ 500 * DOLLARS }>;
1505	type WeightInfo = pallet_tips::weights::SubstrateWeight<Runtime>;
1506	type OnSlash = Treasury;
1507}
1508
1509parameter_types! {
1510	pub const DepositPerItem: Balance = deposit(1, 0);
1511	pub const DepositPerChildTrieItem: Balance = deposit(1, 0) / 100;
1512	pub const DepositPerByte: Balance = deposit(0, 1);
1513	pub const DefaultDepositLimit: Balance = deposit(1024, 1024 * 1024);
1514	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();
1515	pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(30);
1516	pub const MaxEthExtrinsicWeight: FixedU128 = FixedU128::from_rational(9, 10);
1517}
1518
1519impl pallet_contracts::Config for Runtime {
1520	type Time = Timestamp;
1521	type Randomness = RandomnessCollectiveFlip;
1522	type Currency = Balances;
1523	type RuntimeEvent = RuntimeEvent;
1524	type RuntimeCall = RuntimeCall;
1525	/// The safest default is to allow no calls at all.
1526	///
1527	/// Runtimes should whitelist dispatchables that are allowed to be called from contracts
1528	/// and make sure they are stable. Dispatchables exposed to contracts are not allowed to
1529	/// change because that would break already deployed contracts. The `Call` structure itself
1530	/// is not allowed to change the indices of existing pallets, too.
1531	type CallFilter = Nothing;
1532	type DepositPerItem = DepositPerItem;
1533	type DepositPerByte = DepositPerByte;
1534	type DefaultDepositLimit = DefaultDepositLimit;
1535	type CallStack = [pallet_contracts::Frame<Self>; 5];
1536	type WeightPrice = pallet_transaction_payment::Pallet<Self>;
1537	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
1538	type ChainExtension = ();
1539	type Schedule = Schedule;
1540	type AddressGenerator = pallet_contracts::DefaultAddressGenerator;
1541	type MaxCodeLen = ConstU32<{ 123 * 1024 }>;
1542	type MaxStorageKeyLen = ConstU32<128>;
1543	type UnsafeUnstableInterface = ConstBool<false>;
1544	type UploadOrigin = EnsureSigned<Self::AccountId>;
1545	type InstantiateOrigin = EnsureSigned<Self::AccountId>;
1546	type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
1547	type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>;
1548	type RuntimeHoldReason = RuntimeHoldReason;
1549	#[cfg(not(feature = "runtime-benchmarks"))]
1550	type Migrations = ();
1551	#[cfg(feature = "runtime-benchmarks")]
1552	type Migrations = pallet_contracts::migration::codegen::BenchMigrations;
1553	type MaxDelegateDependencies = ConstU32<32>;
1554	type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
1555	type Debug = ();
1556	type Environment = ();
1557	type ApiVersion = ();
1558	type Xcm = ();
1559}
1560
1561impl pallet_revive::Config for Runtime {
1562	type Time = Timestamp;
1563	type Balance = Balance;
1564	type Currency = Balances;
1565	type RuntimeEvent = RuntimeEvent;
1566	type RuntimeCall = RuntimeCall;
1567	type RuntimeOrigin = RuntimeOrigin;
1568	type DepositPerItem = DepositPerItem;
1569	type DepositPerChildTrieItem = DepositPerChildTrieItem;
1570	type DepositPerByte = DepositPerByte;
1571	type WeightInfo = pallet_revive::weights::SubstrateWeight<Self>;
1572	type Precompiles = (
1573		ERC20<Self, InlineIdConfig<0x1>, Instance1>,
1574		ERC20<Self, InlineIdConfig<0x2>, Instance2>,
1575		VestingPrecompile<Self>,
1576	);
1577	type AddressMapper = pallet_revive::AccountId32Mapper<Self>;
1578	type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
1579	type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
1580	type UploadOrigin = EnsureSigned<Self::AccountId>;
1581	type InstantiateOrigin = EnsureSigned<Self::AccountId>;
1582	type RuntimeHoldReason = RuntimeHoldReason;
1583	type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
1584	type ChainId = ConstU64<420_420_420>;
1585	type NativeToEthRatio = ConstU32<1_000_000>; // 10^(18 - 12) Eth is 10^18, Native is 10^12.
1586	type FindAuthor = <Runtime as pallet_authorship::Config>::FindAuthor;
1587	type AllowEVMBytecode = ConstBool<true>;
1588	type FeeInfo = pallet_revive::evm::fees::Info<Address, Signature, EthExtraImpl>;
1589	type MaxEthExtrinsicWeight = MaxEthExtrinsicWeight;
1590	type DebugEnabled = ConstBool<false>;
1591	type AutoMap = ConstBool<false>;
1592	type GasScale = ConstU32<1000>;
1593	type OnBurn = ();
1594	// A backstop on the buffer's size only: each log's weight is charged where it is emitted, so
1595	// the block fills before the cap is reached. Nothing here mirrors balance changes, and the
1596	// pallet's benchmarks fill the buffer past any cap, so the value is never reached.
1597	type MaxOutsideFrameLogs = ConstU32<2048>;
1598	type Deposit = ();
1599}
1600
1601impl pallet_vesting_precompiles::pallet::Config for Runtime {
1602	type WeightInfo = pallet_vesting_precompiles::weights::SubstrateWeight<Runtime>;
1603}
1604
1605impl pallet_sudo::Config for Runtime {
1606	type RuntimeEvent = RuntimeEvent;
1607	type RuntimeCall = RuntimeCall;
1608	type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
1609}
1610
1611parameter_types! {
1612	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::MAX;
1613	/// We prioritize im-online heartbeats over election solution submission.
1614	pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::MAX / 2;
1615	pub const MaxAuthorities: u32 = 1000;
1616	pub const MaxKeys: u32 = 10_000;
1617	pub const MaxPeerInHeartbeats: u32 = 10_000;
1618}
1619
1620impl<LocalCall> frame_system::offchain::CreateTransaction<LocalCall> for Runtime
1621where
1622	RuntimeCall: From<LocalCall>,
1623{
1624	type Extension = TxExtension;
1625
1626	fn create_transaction(call: RuntimeCall, extension: TxExtension) -> UncheckedExtrinsic {
1627		generic::UncheckedExtrinsic::new_transaction(call, extension).into()
1628	}
1629}
1630
1631impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
1632where
1633	RuntimeCall: From<LocalCall>,
1634{
1635	fn create_signed_transaction<
1636		C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>,
1637	>(
1638		call: RuntimeCall,
1639		public: <Signature as traits::Verify>::Signer,
1640		account: AccountId,
1641		nonce: Nonce,
1642	) -> Option<UncheckedExtrinsic> {
1643		let tip = 0;
1644		// take the biggest period possible.
1645		let period =
1646			BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
1647		let current_block = System::block_number()
1648			.saturated_into::<u64>()
1649			// The `System::block_number` is initialized with `n+1`,
1650			// so the actual block number is `n`.
1651			.saturating_sub(1);
1652		let era = Era::mortal(period, current_block);
1653		let tx_ext: TxExtension = (
1654			frame_system::AuthorizeCall::<Runtime>::new(),
1655			frame_system::CheckNonZeroSender::<Runtime>::new(),
1656			frame_system::CheckSpecVersion::<Runtime>::new(),
1657			frame_system::CheckTxVersion::<Runtime>::new(),
1658			frame_system::CheckGenesis::<Runtime>::new(),
1659			frame_system::CheckEra::<Runtime>::from(era),
1660			frame_system::CheckNonce::<Runtime>::from(nonce),
1661			frame_system::CheckWeight::<Runtime>::new(),
1662			pallet_skip_feeless_payment::SkipCheckIfFeeless::from(
1663				pallet_asset_conversion_tx_payment::ChargeAssetTxPayment::<Runtime>::from(
1664					tip, None,
1665				),
1666			),
1667			frame_metadata_hash_extension::CheckMetadataHash::new(false),
1668			pallet_revive::evm::tx_extension::SetOrigin::<Runtime>::default(),
1669			frame_system::WeightReclaim::<Runtime>::new(),
1670		);
1671
1672		let raw_payload = SignedPayload::new(call, tx_ext)
1673			.map_err(|e| {
1674				log::warn!("Unable to create signed payload: {:?}", e);
1675			})
1676			.ok()?;
1677		let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
1678		let address = Indices::unlookup(account);
1679		let (call, tx_ext, _) = raw_payload.deconstruct();
1680		let transaction =
1681			generic::UncheckedExtrinsic::new_signed(call, address, signature, tx_ext).into();
1682		Some(transaction)
1683	}
1684}
1685
1686impl<LocalCall> frame_system::offchain::CreateBare<LocalCall> for Runtime
1687where
1688	RuntimeCall: From<LocalCall>,
1689{
1690	fn create_bare(call: RuntimeCall) -> UncheckedExtrinsic {
1691		generic::UncheckedExtrinsic::new_bare(call).into()
1692	}
1693}
1694
1695impl frame_system::offchain::SigningTypes for Runtime {
1696	type Public = <Signature as traits::Verify>::Signer;
1697	type Signature = Signature;
1698}
1699
1700impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
1701where
1702	RuntimeCall: From<C>,
1703{
1704	type Extrinsic = UncheckedExtrinsic;
1705	type RuntimeCall = RuntimeCall;
1706}
1707
1708impl<C> frame_system::offchain::CreateAuthorizedTransaction<C> for Runtime
1709where
1710	RuntimeCall: From<C>,
1711{
1712	fn create_extension() -> Self::Extension {
1713		(
1714			frame_system::AuthorizeCall::<Runtime>::new(),
1715			frame_system::CheckNonZeroSender::<Runtime>::new(),
1716			frame_system::CheckSpecVersion::<Runtime>::new(),
1717			frame_system::CheckTxVersion::<Runtime>::new(),
1718			frame_system::CheckGenesis::<Runtime>::new(),
1719			frame_system::CheckEra::<Runtime>::from(Era::Immortal),
1720			frame_system::CheckNonce::<Runtime>::from(0),
1721			frame_system::CheckWeight::<Runtime>::new(),
1722			pallet_skip_feeless_payment::SkipCheckIfFeeless::from(
1723				pallet_asset_conversion_tx_payment::ChargeAssetTxPayment::<Runtime>::from(0, None),
1724			),
1725			frame_metadata_hash_extension::CheckMetadataHash::new(false),
1726			pallet_revive::evm::tx_extension::SetOrigin::<Runtime>::default(),
1727			frame_system::WeightReclaim::<Runtime>::new(),
1728		)
1729	}
1730}
1731
1732impl pallet_im_online::Config for Runtime {
1733	type AuthorityId = ImOnlineId;
1734	type RuntimeEvent = RuntimeEvent;
1735	type NextSessionRotation = Babe;
1736	type ValidatorSet = Historical;
1737	type ReportUnresponsiveness = Offences;
1738	type UnsignedPriority = ImOnlineUnsignedPriority;
1739	type WeightInfo = pallet_im_online::weights::SubstrateWeight<Runtime>;
1740	type MaxKeys = MaxKeys;
1741	type MaxPeerInHeartbeats = MaxPeerInHeartbeats;
1742}
1743
1744impl pallet_offences::Config for Runtime {
1745	type RuntimeEvent = RuntimeEvent;
1746	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
1747	type OnOffenceHandler = Staking;
1748}
1749
1750impl pallet_authority_discovery::Config for Runtime {
1751	type MaxAuthorities = MaxAuthorities;
1752}
1753
1754parameter_types! {
1755	pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
1756}
1757
1758impl pallet_grandpa::Config for Runtime {
1759	type RuntimeEvent = RuntimeEvent;
1760	type WeightInfo = ();
1761	type MaxAuthorities = MaxAuthorities;
1762	type MaxNominators = MaxNominators;
1763	type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
1764	type KeyOwnerProof = sp_session::MembershipProof;
1765	type EquivocationReportSystem =
1766		pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
1767}
1768
1769parameter_types! {
1770	// difference of 26 bytes on-chain for the registration and 9 bytes on-chain for the identity
1771	// information, already accounted for by the byte deposit
1772	pub const BasicDeposit: Balance = deposit(1, 17);
1773	pub const ByteDeposit: Balance = deposit(0, 1);
1774	pub const UsernameDeposit: Balance = deposit(0, 32);
1775	pub const SubAccountDeposit: Balance = 2 * DOLLARS;   // 53 bytes on-chain
1776	pub const MaxSubAccounts: u32 = 100;
1777	pub const MaxAdditionalFields: u32 = 100;
1778	pub const MaxRegistrars: u32 = 20;
1779}
1780
1781impl pallet_identity::Config for Runtime {
1782	type RuntimeEvent = RuntimeEvent;
1783	type Currency = Balances;
1784	type BasicDeposit = BasicDeposit;
1785	type ByteDeposit = ByteDeposit;
1786	type UsernameDeposit = UsernameDeposit;
1787	type SubAccountDeposit = SubAccountDeposit;
1788	type MaxSubAccounts = MaxSubAccounts;
1789	type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
1790	type MaxRegistrars = MaxRegistrars;
1791	type Slashed = Treasury;
1792	type ForceOrigin = EnsureRootOrHalfCouncil;
1793	type RegistrarOrigin = EnsureRootOrHalfCouncil;
1794	type OffchainSignature = Signature;
1795	type SigningPublicKey = <Signature as traits::Verify>::Signer;
1796	type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
1797	type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
1798	type UsernameGracePeriod = ConstU32<{ 30 * DAYS }>;
1799	type MaxSuffixLength = ConstU32<7>;
1800	type MaxUsernameLength = ConstU32<32>;
1801	#[cfg(feature = "runtime-benchmarks")]
1802	type BenchmarkHelper = ();
1803	type WeightInfo = pallet_identity::weights::SubstrateWeight<Runtime>;
1804}
1805
1806impl pallet_recovery::Config for Runtime {
1807	type RuntimeCall = RuntimeCall;
1808	type RuntimeHoldReason = RuntimeHoldReason;
1809	type BlockNumberProvider = frame_system::Pallet<Runtime>;
1810	type Currency = Balances;
1811	type FriendGroupsConsideration = ();
1812	type AttemptConsideration = ();
1813	type InheritorConsideration = ();
1814	type SecurityDeposit = ();
1815	type MaxFriendsPerConfig = ConstU32<100>;
1816	type WeightInfo = ();
1817	type Slash = (); // burn
1818}
1819
1820parameter_types! {
1821	pub const GraceStrikes: u32 = 10;
1822	pub const SocietyVotingPeriod: BlockNumber = 80 * HOURS;
1823	pub const ClaimPeriod: BlockNumber = 80 * HOURS;
1824	pub const PeriodSpend: Balance = 500 * DOLLARS;
1825	pub const MaxLockDuration: BlockNumber = 36 * 30 * DAYS;
1826	pub const ChallengePeriod: BlockNumber = 7 * DAYS;
1827	pub const MaxPayouts: u32 = 10;
1828	pub const MaxBids: u32 = 10;
1829	pub const SocietyPalletId: PalletId = PalletId(*b"py/socie");
1830}
1831
1832impl pallet_society::Config for Runtime {
1833	type RuntimeEvent = RuntimeEvent;
1834	type PalletId = SocietyPalletId;
1835	type Currency = Balances;
1836	type Randomness = RandomnessCollectiveFlip;
1837	type GraceStrikes = GraceStrikes;
1838	type PeriodSpend = PeriodSpend;
1839	type VotingPeriod = SocietyVotingPeriod;
1840	type ClaimPeriod = ClaimPeriod;
1841	type MaxLockDuration = MaxLockDuration;
1842	type FounderSetOrigin =
1843		pallet_collective::EnsureProportionMoreThan<AccountId, CouncilCollective, 1, 2>;
1844	type ChallengePeriod = ChallengePeriod;
1845	type MaxPayouts = MaxPayouts;
1846	type MaxBids = MaxBids;
1847	type BlockNumberProvider = System;
1848	type WeightInfo = pallet_society::weights::SubstrateWeight<Runtime>;
1849}
1850
1851parameter_types! {
1852	pub const MinVestedTransfer: Balance = 100 * DOLLARS;
1853	pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
1854		WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
1855}
1856
1857impl pallet_vesting::Config for Runtime {
1858	type RuntimeEvent = RuntimeEvent;
1859	type Currency = Balances;
1860	type BlockNumberToBalance = ConvertInto;
1861	type MinVestedTransfer = MinVestedTransfer;
1862	type WeightInfo = pallet_vesting::weights::SubstrateWeight<Runtime>;
1863	type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons;
1864	type BlockNumberProvider = System;
1865	// `VestingInfo` encode length is 36bytes. 28 schedules gets encoded as 1009 bytes, which is the
1866	// highest number of schedules that encodes less than 2^10.
1867	const MAX_VESTING_SCHEDULES: u32 = 28;
1868}
1869
1870impl pallet_mmr::Config for Runtime {
1871	const INDEXING_PREFIX: &'static [u8] = b"mmr";
1872	type Hashing = Keccak256;
1873	type LeafData = pallet_mmr::ParentNumberAndHash<Self>;
1874	type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest<Runtime>;
1875	type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider<Runtime>;
1876	type WeightInfo = ();
1877	#[cfg(feature = "runtime-benchmarks")]
1878	type BenchmarkHelper = ();
1879}
1880
1881parameter_types! {
1882	pub LeafVersion: MmrLeafVersion = MmrLeafVersion::new(0, 0);
1883}
1884
1885impl pallet_beefy_mmr::Config for Runtime {
1886	type LeafVersion = LeafVersion;
1887	type BeefyAuthorityToMerkleLeaf = pallet_beefy_mmr::BeefyEcdsaToEthereum;
1888	type LeafExtra = Vec<u8>;
1889	type BeefyDataProvider = ();
1890	type WeightInfo = ();
1891}
1892
1893parameter_types! {
1894	pub const LotteryPalletId: PalletId = PalletId(*b"py/lotto");
1895	pub const MaxCalls: u32 = 10;
1896	pub const MaxGenerateRandom: u32 = 10;
1897}
1898
1899impl pallet_lottery::Config for Runtime {
1900	type PalletId = LotteryPalletId;
1901	type RuntimeCall = RuntimeCall;
1902	type Currency = Balances;
1903	type Randomness = RandomnessCollectiveFlip;
1904	type RuntimeEvent = RuntimeEvent;
1905	type ManagerOrigin = EnsureRoot<AccountId>;
1906	type MaxCalls = MaxCalls;
1907	type ValidateCall = Lottery;
1908	type MaxGenerateRandom = MaxGenerateRandom;
1909	type WeightInfo = pallet_lottery::weights::SubstrateWeight<Runtime>;
1910}
1911
1912parameter_types! {
1913	pub const AssetDeposit: Balance = 100 * DOLLARS;
1914	pub const ApprovalDeposit: Balance = 1 * DOLLARS;
1915	pub const StringLimit: u32 = 50;
1916	pub const MetadataDepositBase: Balance = 10 * DOLLARS;
1917	pub const MetadataDepositPerByte: Balance = 1 * DOLLARS;
1918}
1919
1920impl pallet_assets::Config<Instance1> for Runtime {
1921	type RuntimeEvent = RuntimeEvent;
1922	type Balance = u128;
1923	type AssetId = u32;
1924	type AssetIdParameter = codec::Compact<u32>;
1925	type ReserveData = ();
1926	type Currency = Balances;
1927	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
1928	type ForceOrigin = EnsureRoot<AccountId>;
1929	type AssetDeposit = AssetDeposit;
1930	type AssetAccountDeposit = ConstU128<DOLLARS>;
1931	type MetadataDepositBase = MetadataDepositBase;
1932	type MetadataDepositPerByte = MetadataDepositPerByte;
1933	type ApprovalDeposit = ApprovalDeposit;
1934	type StringLimit = StringLimit;
1935	type Holder = ();
1936	type Freezer = ();
1937	type Extra = ();
1938	type CallbackHandle = (pallet_assets_precompiles::ForeignAssetId<Runtime, Instance1>,);
1939	type AssetIdAllocator = ();
1940	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
1941	type RemoveItemsLimit = ConstU32<1000>;
1942	#[cfg(feature = "runtime-benchmarks")]
1943	type BenchmarkHelper = ();
1944}
1945
1946ord_parameter_types! {
1947	pub const AssetConversionOrigin: AccountId = AccountIdConversion::<AccountId>::into_account_truncating(&AssetConversionPalletId::get());
1948}
1949
1950impl pallet_assets::Config<Instance2> for Runtime {
1951	type RuntimeEvent = RuntimeEvent;
1952	type Balance = u128;
1953	type AssetId = u32;
1954	type AssetIdParameter = codec::Compact<u32>;
1955	type ReserveData = ();
1956	type Currency = Balances;
1957	type CreateOrigin = AsEnsureOriginWithArg<EnsureSignedBy<AssetConversionOrigin, AccountId>>;
1958	type ForceOrigin = EnsureRoot<AccountId>;
1959	type AssetDeposit = AssetDeposit;
1960	type AssetAccountDeposit = ConstU128<DOLLARS>;
1961	type MetadataDepositBase = MetadataDepositBase;
1962	type MetadataDepositPerByte = MetadataDepositPerByte;
1963	type ApprovalDeposit = ApprovalDeposit;
1964	type StringLimit = StringLimit;
1965	type Holder = ();
1966	type Freezer = ();
1967	type Extra = ();
1968	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
1969	type RemoveItemsLimit = ConstU32<1000>;
1970	type CallbackHandle = ();
1971	type AssetIdAllocator = ();
1972	#[cfg(feature = "runtime-benchmarks")]
1973	type BenchmarkHelper = ();
1974}
1975
1976parameter_types! {
1977	pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon");
1978	pub const PoolSetupFee: Balance = 1 * DOLLARS; // should be more or equal to the existential deposit
1979	pub const MintMinLiquidity: Balance = 100;  // 100 is good enough when the main currency has 10-12 decimals.
1980	pub LpFee: Permill = Permill::from_rational(3u32, 1_000u32); // 0.3%
1981	pub MaxSwapFee: Permill = Permill::from_percent(2);
1982	pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0);
1983	pub const Native: NativeOrWithId<u32> = NativeOrWithId::Native;
1984}
1985
1986pub type NativeAndAssets =
1987	UnionOf<Balances, Assets, NativeFromLeft, NativeOrWithId<u32>, AccountId>;
1988
1989impl pallet_asset_conversion::Config for Runtime {
1990	type RuntimeEvent = RuntimeEvent;
1991	type Balance = u128;
1992	type HigherPrecisionBalance = sp_core::U256;
1993	type AssetKind = NativeOrWithId<u32>;
1994	type Assets = NativeAndAssets;
1995	type PoolId = (Self::AssetKind, Self::AssetKind);
1996	type PoolLocator = Chain<
1997		WithFirstAsset<
1998			Native,
1999			AccountId,
2000			NativeOrWithId<u32>,
2001			AccountIdConverter<AssetConversionPalletId, Self::PoolId>,
2002		>,
2003		Ascending<
2004			AccountId,
2005			NativeOrWithId<u32>,
2006			AccountIdConverter<AssetConversionPalletId, Self::PoolId>,
2007		>,
2008	>;
2009	type PoolAssetId = <Self as pallet_assets::Config<Instance2>>::AssetId;
2010	type PoolAssets = PoolAssets;
2011	type PoolSetupFee = PoolSetupFee;
2012	type PoolSetupFeeAsset = Native;
2013	type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
2014	type PalletId = AssetConversionPalletId;
2015	type LPFee = LpFee;
2016	type AdminOrigin = EnsureRoot<AccountId>;
2017	type MaxSwapFee = MaxSwapFee;
2018	type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
2019	type WeightInfo = pallet_asset_conversion::weights::SubstrateWeight<Runtime>;
2020	type MaxSwapPathLength = ConstU32<4>;
2021	type MintMinLiquidity = MintMinLiquidity;
2022	#[cfg(feature = "runtime-benchmarks")]
2023	type BenchmarkHelper = ();
2024}
2025
2026pub type NativeAndAssetsFreezer =
2027	UnionOf<Balances, AssetsFreezer, NativeFromLeft, NativeOrWithId<u32>, AccountId>;
2028
2029/// Benchmark Helper
2030#[cfg(feature = "runtime-benchmarks")]
2031pub struct AssetRewardsBenchmarkHelper;
2032
2033#[cfg(feature = "runtime-benchmarks")]
2034impl pallet_asset_rewards::benchmarking::BenchmarkHelper<NativeOrWithId<u32>>
2035	for AssetRewardsBenchmarkHelper
2036{
2037	fn staked_asset() -> NativeOrWithId<u32> {
2038		NativeOrWithId::<u32>::WithId(100)
2039	}
2040	fn reward_asset() -> NativeOrWithId<u32> {
2041		NativeOrWithId::<u32>::WithId(101)
2042	}
2043}
2044
2045parameter_types! {
2046	pub const StakingRewardsPalletId: PalletId = PalletId(*b"py/stkrd");
2047	pub const CreationHoldReason: RuntimeHoldReason =
2048		RuntimeHoldReason::AssetRewards(pallet_asset_rewards::HoldReason::PoolCreation);
2049	// 1 item, 135 bytes into the storage on pool creation.
2050	pub const StakePoolCreationDeposit: Balance = deposit(1, 135);
2051}
2052
2053impl pallet_asset_rewards::Config for Runtime {
2054	type RuntimeEvent = RuntimeEvent;
2055	type RuntimeFreezeReason = RuntimeFreezeReason;
2056	type AssetId = NativeOrWithId<u32>;
2057	type Balance = Balance;
2058	type Assets = NativeAndAssets;
2059	type PalletId = StakingRewardsPalletId;
2060	type CreatePoolOrigin = EnsureSigned<AccountId>;
2061	type WeightInfo = ();
2062	type AssetsFreezer = NativeAndAssetsFreezer;
2063	type Consideration = HoldConsideration<
2064		AccountId,
2065		Balances,
2066		CreationHoldReason,
2067		ConstantStoragePrice<StakePoolCreationDeposit, Balance>,
2068	>;
2069	type BlockNumberProvider = frame_system::Pallet<Runtime>;
2070	#[cfg(feature = "runtime-benchmarks")]
2071	type BenchmarkHelper = AssetRewardsBenchmarkHelper;
2072}
2073
2074impl pallet_asset_conversion_ops::Config for Runtime {
2075	type RuntimeEvent = RuntimeEvent;
2076	type PriorAccountIdConverter = pallet_asset_conversion::AccountIdConverterNoSeed<(
2077		NativeOrWithId<u32>,
2078		NativeOrWithId<u32>,
2079	)>;
2080	type AssetsRefund = <Runtime as pallet_asset_conversion::Config>::Assets;
2081	type PoolAssetsRefund = <Runtime as pallet_asset_conversion::Config>::PoolAssets;
2082	type PoolAssetsTeam = <Runtime as pallet_asset_conversion::Config>::PoolAssets;
2083	type DepositAsset = Balances;
2084	type WeightInfo = pallet_asset_conversion_ops::weights::SubstrateWeight<Runtime>;
2085}
2086
2087parameter_types! {
2088	pub const QueueCount: u32 = 300;
2089	pub const MaxQueueLen: u32 = 1000;
2090	pub const FifoQueueLen: u32 = 500;
2091	pub const NisBasePeriod: BlockNumber = 30 * DAYS;
2092	pub const MinBid: Balance = 100 * DOLLARS;
2093	pub const MinReceipt: Perquintill = Perquintill::from_percent(1);
2094	pub const IntakePeriod: BlockNumber = 10;
2095	pub MaxIntakeWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;
2096	pub const ThawThrottle: (Perquintill, BlockNumber) = (Perquintill::from_percent(25), 5);
2097	pub Target: Perquintill = Perquintill::zero();
2098	pub const NisPalletId: PalletId = PalletId(*b"py/nis  ");
2099}
2100
2101impl pallet_nis::Config for Runtime {
2102	type WeightInfo = pallet_nis::weights::SubstrateWeight<Runtime>;
2103	type RuntimeEvent = RuntimeEvent;
2104	type Currency = Balances;
2105	type CurrencyBalance = Balance;
2106	type FundOrigin = frame_system::EnsureSigned<AccountId>;
2107	type Counterpart = ItemOf<Assets, ConstU32<9u32>, AccountId>;
2108	type CounterpartAmount = WithMaximumOf<ConstU128<21_000_000_000_000_000_000u128>>;
2109	type Deficit = ();
2110	type IgnoredIssuance = ();
2111	type Target = Target;
2112	type PalletId = NisPalletId;
2113	type QueueCount = QueueCount;
2114	type MaxQueueLen = MaxQueueLen;
2115	type FifoQueueLen = FifoQueueLen;
2116	type BasePeriod = NisBasePeriod;
2117	type MinBid = MinBid;
2118	type MinReceipt = MinReceipt;
2119	type IntakePeriod = IntakePeriod;
2120	type MaxIntakeWeight = MaxIntakeWeight;
2121	type ThawThrottle = ThawThrottle;
2122	type RuntimeHoldReason = RuntimeHoldReason;
2123	#[cfg(feature = "runtime-benchmarks")]
2124	type BenchmarkSetup = SetupAsset;
2125}
2126
2127#[cfg(feature = "runtime-benchmarks")]
2128pub struct SetupAsset;
2129#[cfg(feature = "runtime-benchmarks")]
2130impl pallet_nis::BenchmarkSetup for SetupAsset {
2131	fn create_counterpart_asset() {
2132		let owner = AccountId::from([0u8; 32]);
2133		// this may or may not fail depending on if the chain spec or runtime genesis is used.
2134		let _ = Assets::force_create(
2135			RuntimeOrigin::root(),
2136			9u32.into(),
2137			sp_runtime::MultiAddress::Id(owner),
2138			true,
2139			1,
2140		);
2141	}
2142}
2143
2144parameter_types! {
2145	pub const CollectionDeposit: Balance = 100 * DOLLARS;
2146	pub const ItemDeposit: Balance = 1 * DOLLARS;
2147	pub const ApprovalsLimit: u32 = 20;
2148	pub const ItemAttributesApprovalsLimit: u32 = 20;
2149	pub const MaxTips: u32 = 10;
2150	pub const MaxDeadlineDuration: BlockNumber = 12 * 30 * DAYS;
2151}
2152
2153impl pallet_uniques::Config for Runtime {
2154	type RuntimeEvent = RuntimeEvent;
2155	type CollectionId = u32;
2156	type ItemId = u32;
2157	type Currency = Balances;
2158	type ForceOrigin = frame_system::EnsureRoot<AccountId>;
2159	type CollectionDeposit = CollectionDeposit;
2160	type ItemDeposit = ItemDeposit;
2161	type MetadataDepositBase = MetadataDepositBase;
2162	type AttributeDepositBase = MetadataDepositBase;
2163	type DepositPerByte = MetadataDepositPerByte;
2164	type StringLimit = ConstU32<128>;
2165	type KeyLimit = ConstU32<32>;
2166	type ValueLimit = ConstU32<64>;
2167	type WeightInfo = pallet_uniques::weights::SubstrateWeight<Runtime>;
2168	#[cfg(feature = "runtime-benchmarks")]
2169	type Helper = ();
2170	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
2171	type Locker = ();
2172}
2173
2174parameter_types! {
2175	pub const Budget: Balance = 10_000 * DOLLARS;
2176	pub TreasuryAccount: AccountId = Treasury::account_id();
2177}
2178
2179pub struct SalaryForRank;
2180impl GetSalary<u16, AccountId, Balance> for SalaryForRank {
2181	fn get_salary(a: u16, _: &AccountId) -> Balance {
2182		Balance::from(a) * 1000 * DOLLARS
2183	}
2184}
2185
2186impl pallet_salary::Config for Runtime {
2187	type WeightInfo = ();
2188	type RuntimeEvent = RuntimeEvent;
2189	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
2190	type Members = RankedCollective;
2191	type Salary = SalaryForRank;
2192	type RegistrationPeriod = ConstU32<200>;
2193	type PayoutPeriod = ConstU32<200>;
2194	type Budget = Budget;
2195}
2196
2197impl pallet_core_fellowship::Config for Runtime {
2198	type WeightInfo = ();
2199	type RuntimeEvent = RuntimeEvent;
2200	type Members = RankedCollective;
2201	type Balance = Balance;
2202	type ParamsOrigin = frame_system::EnsureRoot<AccountId>;
2203	type InductOrigin = pallet_core_fellowship::EnsureInducted<Runtime, (), 1>;
2204	type ApproveOrigin = EnsureRootWithSuccess<AccountId, ConstU16<9>>;
2205	type PromoteOrigin = EnsureRootWithSuccess<AccountId, ConstU16<9>>;
2206	type FastPromoteOrigin = Self::PromoteOrigin;
2207	type EvidenceSize = ConstU32<16_384>;
2208	type MaxRank = ConstU16<9>;
2209	type BlockNumberProvider = System;
2210}
2211
2212parameter_types! {
2213	pub const NftFractionalizationPalletId: PalletId = PalletId(*b"fraction");
2214	pub NewAssetSymbol: BoundedVec<u8, StringLimit> = (*b"FRAC").to_vec().try_into().unwrap();
2215	pub NewAssetName: BoundedVec<u8, StringLimit> = (*b"Frac").to_vec().try_into().unwrap();
2216}
2217
2218impl pallet_nft_fractionalization::Config for Runtime {
2219	type RuntimeEvent = RuntimeEvent;
2220	type Deposit = AssetDeposit;
2221	type Currency = Balances;
2222	type NewAssetSymbol = NewAssetSymbol;
2223	type NewAssetName = NewAssetName;
2224	type StringLimit = StringLimit;
2225	type NftCollectionId = <Self as pallet_nfts::Config>::CollectionId;
2226	type NftId = <Self as pallet_nfts::Config>::ItemId;
2227	type AssetBalance = <Self as pallet_balances::Config>::Balance;
2228	type AssetId = <Self as pallet_assets::Config<Instance1>>::AssetId;
2229	type Assets = Assets;
2230	type Nfts = Nfts;
2231	type PalletId = NftFractionalizationPalletId;
2232	type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight<Runtime>;
2233	type RuntimeHoldReason = RuntimeHoldReason;
2234	#[cfg(feature = "runtime-benchmarks")]
2235	type BenchmarkHelper = ();
2236}
2237
2238parameter_types! {
2239	pub Features: PalletFeatures = PalletFeatures::all_enabled();
2240	pub const MaxAttributesPerCall: u32 = 10;
2241}
2242
2243impl pallet_nfts::Config for Runtime {
2244	type RuntimeEvent = RuntimeEvent;
2245	type CollectionId = u32;
2246	type ItemId = u32;
2247	type Currency = Balances;
2248	type ForceOrigin = frame_system::EnsureRoot<AccountId>;
2249	type CollectionDeposit = CollectionDeposit;
2250	type ItemDeposit = ItemDeposit;
2251	type MetadataDepositBase = MetadataDepositBase;
2252	type AttributeDepositBase = MetadataDepositBase;
2253	type DepositPerByte = MetadataDepositPerByte;
2254	type StringLimit = ConstU32<256>;
2255	type KeyLimit = ConstU32<64>;
2256	type ValueLimit = ConstU32<256>;
2257	type ApprovalsLimit = ApprovalsLimit;
2258	type ItemAttributesApprovalsLimit = ItemAttributesApprovalsLimit;
2259	type MaxTips = MaxTips;
2260	type MaxDeadlineDuration = MaxDeadlineDuration;
2261	type MaxAttributesPerCall = MaxAttributesPerCall;
2262	type Features = Features;
2263	type OffchainSignature = Signature;
2264	type OffchainPublic = <Signature as traits::Verify>::Signer;
2265	type WeightInfo = pallet_nfts::weights::SubstrateWeight<Runtime>;
2266	#[cfg(feature = "runtime-benchmarks")]
2267	type Helper = ();
2268	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
2269	type Locker = ();
2270	type BlockNumberProvider = frame_system::Pallet<Runtime>;
2271}
2272
2273impl pallet_transaction_storage::Config for Runtime {
2274	type RuntimeEvent = RuntimeEvent;
2275	type Currency = Balances;
2276	type RuntimeHoldReason = RuntimeHoldReason;
2277	type RuntimeCall = RuntimeCall;
2278	type FeeDestination = ();
2279	type WeightInfo = pallet_transaction_storage::weights::SubstrateWeight<Runtime>;
2280	type MaxBlockTransactions =
2281		ConstU32<{ pallet_transaction_storage::DEFAULT_MAX_BLOCK_TRANSACTIONS }>;
2282	type MaxTransactionSize =
2283		ConstU32<{ pallet_transaction_storage::DEFAULT_MAX_TRANSACTION_SIZE }>;
2284}
2285
2286impl pallet_verify_signature::Config for Runtime {
2287	type Signature = MultiSignature;
2288	type AccountIdentifier = MultiSigner;
2289	type WeightInfo = pallet_verify_signature::weights::SubstrateWeight<Runtime>;
2290	#[cfg(feature = "runtime-benchmarks")]
2291	type BenchmarkHelper = ();
2292}
2293
2294impl pallet_whitelist::Config for Runtime {
2295	type RuntimeEvent = RuntimeEvent;
2296	type RuntimeCall = RuntimeCall;
2297	type WhitelistOrigin = EnsureRoot<AccountId>;
2298	// Opt into permissionless dispatch.
2299	type DispatchWhitelistedOrigin =
2300		EitherOfDiverse<EnsureRoot<AccountId>, EnsureAuthorized<AccountId>>;
2301	type Preimages = Preimage;
2302	type DeferredDispatchExpiration = ConstU32<{ 28 * DAYS }>;
2303	type BlockNumberProvider = frame_system::Pallet<Runtime>;
2304	type WeightInfo = pallet_whitelist::weights::SubstrateWeight<Runtime>;
2305}
2306
2307parameter_types! {
2308	pub const MigrationSignedDepositPerItem: Balance = 1 * CENTS;
2309	pub const MigrationSignedDepositBase: Balance = 20 * DOLLARS;
2310	pub const MigrationMaxKeyLen: u32 = 512;
2311}
2312
2313impl pallet_state_trie_migration::Config for Runtime {
2314	type RuntimeEvent = RuntimeEvent;
2315	type ControlOrigin = EnsureRoot<AccountId>;
2316	type Currency = Balances;
2317	type RuntimeHoldReason = RuntimeHoldReason;
2318	type MaxKeyLen = MigrationMaxKeyLen;
2319	type SignedDepositPerItem = MigrationSignedDepositPerItem;
2320	type SignedDepositBase = MigrationSignedDepositBase;
2321	// Warning: this is not advised, as it might allow the chain to be temporarily DOS-ed.
2322	// Preferably, if the chain's governance/maintenance team is planning on using a specific
2323	// account for the migration, put it here to make sure only that account can trigger the signed
2324	// migrations.
2325	type SignedFilter = EnsureSigned<Self::AccountId>;
2326	type WeightInfo = ();
2327}
2328
2329const ALLIANCE_MOTION_DURATION_IN_BLOCKS: BlockNumber = 5 * DAYS;
2330
2331parameter_types! {
2332	pub const AllianceMotionDuration: BlockNumber = ALLIANCE_MOTION_DURATION_IN_BLOCKS;
2333	pub const AllianceMaxProposals: u32 = 100;
2334	pub const AllianceMaxMembers: u32 = 100;
2335}
2336
2337type AllianceCollective = pallet_collective::Instance3;
2338impl pallet_collective::Config<AllianceCollective> for Runtime {
2339	type RuntimeOrigin = RuntimeOrigin;
2340	type Proposal = RuntimeCall;
2341	type RuntimeEvent = RuntimeEvent;
2342	type MotionDuration = AllianceMotionDuration;
2343	type MaxProposals = AllianceMaxProposals;
2344	type MaxMembers = AllianceMaxMembers;
2345	type DefaultVote = pallet_collective::PrimeDefaultVote;
2346	type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
2347	type SetMembersOrigin = EnsureRoot<Self::AccountId>;
2348	type MaxProposalWeight = MaxCollectivesProposalWeight;
2349	type DisapproveOrigin = EnsureRoot<Self::AccountId>;
2350	type KillOrigin = EnsureRoot<Self::AccountId>;
2351	type Consideration = ();
2352}
2353
2354parameter_types! {
2355	pub const MaxFellows: u32 = AllianceMaxMembers::get();
2356	pub const MaxAllies: u32 = 100;
2357	pub const AllyDeposit: Balance = 10 * DOLLARS;
2358	pub const RetirementPeriod: BlockNumber = ALLIANCE_MOTION_DURATION_IN_BLOCKS + (1 * DAYS);
2359}
2360
2361impl pallet_alliance::Config for Runtime {
2362	type RuntimeEvent = RuntimeEvent;
2363	type Proposal = RuntimeCall;
2364	type AdminOrigin = EitherOfDiverse<
2365		EnsureRoot<AccountId>,
2366		pallet_collective::EnsureProportionMoreThan<AccountId, AllianceCollective, 2, 3>,
2367	>;
2368	type MembershipManager = EitherOfDiverse<
2369		EnsureRoot<AccountId>,
2370		pallet_collective::EnsureProportionMoreThan<AccountId, AllianceCollective, 2, 3>,
2371	>;
2372	type AnnouncementOrigin = EitherOfDiverse<
2373		EnsureRoot<AccountId>,
2374		pallet_collective::EnsureProportionMoreThan<AccountId, AllianceCollective, 2, 3>,
2375	>;
2376	type Currency = Balances;
2377	type Slashed = Treasury;
2378	type InitializeMembers = AllianceMotion;
2379	type MembershipChanged = AllianceMotion;
2380	#[cfg(not(feature = "runtime-benchmarks"))]
2381	type IdentityVerifier = AllianceIdentityVerifier;
2382	#[cfg(feature = "runtime-benchmarks")]
2383	type IdentityVerifier = ();
2384	type ProposalProvider = AllianceProposalProvider;
2385	type MaxProposals = AllianceMaxProposals;
2386	type MaxFellows = MaxFellows;
2387	type MaxAllies = MaxAllies;
2388	type MaxUnscrupulousItems = ConstU32<100>;
2389	type MaxWebsiteUrlLength = ConstU32<255>;
2390	type MaxAnnouncementsCount = ConstU32<100>;
2391	type MaxMembersCount = AllianceMaxMembers;
2392	type AllyDeposit = AllyDeposit;
2393	type WeightInfo = pallet_alliance::weights::SubstrateWeight<Runtime>;
2394	type RetirementPeriod = RetirementPeriod;
2395}
2396
2397impl frame_benchmarking_pallet_pov::Config for Runtime {
2398	type RuntimeEvent = RuntimeEvent;
2399}
2400
2401parameter_types! {
2402	pub StatementCost: Balance = 1 * DOLLARS;
2403	pub StatementByteCost: Balance = 100 * MILLICENTS;
2404	pub const MinAllowedStatements: u32 = 4;
2405	pub const MaxAllowedStatements: u32 = 10;
2406	pub const MinAllowedBytes: u32 = 1024;
2407	pub const MaxAllowedBytes: u32 = 4096;
2408}
2409
2410impl pallet_statement::Config for Runtime {
2411	type RuntimeEvent = RuntimeEvent;
2412	type Currency = Balances;
2413	type StatementCost = StatementCost;
2414	type ByteCost = StatementByteCost;
2415	type MinAllowedStatements = MinAllowedStatements;
2416	type MaxAllowedStatements = MaxAllowedStatements;
2417	type MinAllowedBytes = MinAllowedBytes;
2418	type MaxAllowedBytes = MaxAllowedBytes;
2419}
2420
2421parameter_types! {
2422	pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
2423}
2424
2425impl pallet_migrations::Config for Runtime {
2426	type RuntimeEvent = RuntimeEvent;
2427	#[cfg(not(feature = "runtime-benchmarks"))]
2428	type Migrations = ();
2429	// Benchmarks need mocked migrations to guarantee that they succeed.
2430	#[cfg(feature = "runtime-benchmarks")]
2431	type Migrations = pallet_migrations::mock_helpers::MockedMigrations;
2432	type CursorMaxLen = ConstU32<65_536>;
2433	type IdentifierMaxLen = ConstU32<256>;
2434	type MigrationStatusHandler = ();
2435	type FailedMigrationHandler = frame_support::migrations::FreezeChainOnFailedMigration;
2436	type MaxServiceWeight = MbmServiceWeight;
2437	type WeightInfo = pallet_migrations::weights::SubstrateWeight<Runtime>;
2438}
2439
2440parameter_types! {
2441	pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
2442	pub const MinimumCreditPurchase: Balance =  100 * MILLICENTS;
2443}
2444
2445pub struct IntoAuthor;
2446impl OnUnbalanced<Credit<AccountId, Balances>> for IntoAuthor {
2447	fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
2448		if let Some(author) = Authorship::author() {
2449			let _ = <Balances as Balanced<_>>::resolve(&author, credit);
2450		}
2451	}
2452}
2453
2454pub struct CoretimeProvider;
2455impl CoretimeInterface for CoretimeProvider {
2456	type AccountId = AccountId;
2457	type Balance = Balance;
2458	type RelayChainBlockNumberProvider = System;
2459	fn request_core_count(_count: CoreIndex) {}
2460	fn request_revenue_info_at(_when: u32) {}
2461	fn credit_account(_who: Self::AccountId, _amount: Self::Balance) {}
2462	fn assign_core(
2463		_core: CoreIndex,
2464		_begin: u32,
2465		_assignment: Vec<(CoreAssignment, PartsOf57600)>,
2466		_end_hint: Option<u32>,
2467	) {
2468	}
2469}
2470
2471pub struct SovereignAccountOf;
2472// Dummy implementation which converts `TaskId` to `AccountId`.
2473impl MaybeConvert<TaskId, AccountId> for SovereignAccountOf {
2474	fn maybe_convert(task: TaskId) -> Option<AccountId> {
2475		let mut account: [u8; 32] = [0; 32];
2476		account[..4].copy_from_slice(&task.to_le_bytes());
2477		Some(account.into())
2478	}
2479}
2480impl pallet_broker::Config for Runtime {
2481	type RuntimeEvent = RuntimeEvent;
2482	type Currency = Balances;
2483	type OnRevenue = IntoAuthor;
2484	type TimeslicePeriod = ConstU32<2>;
2485	type MaxLeasedCores = ConstU32<5>;
2486	type MaxReservedCores = ConstU32<5>;
2487	type Coretime = CoretimeProvider;
2488	type OnDemandRevenue = OnDemand;
2489	type ConvertBalance = traits::Identity;
2490	type WeightInfo = ();
2491	type PalletId = BrokerPalletId;
2492	type AdminOrigin = EnsureRoot<AccountId>;
2493	type SovereignAccountOf = SovereignAccountOf;
2494	type MaxAutoRenewals = ConstU32<10>;
2495	type PriceAdapter = pallet_broker::CenterTargetPrice<Balance>;
2496	type MinimumCreditPurchase = MinimumCreditPurchase;
2497}
2498
2499parameter_types! {
2500	pub const OnDemandPalletId: PalletId = PalletId(*b"py/ondmd");
2501}
2502
2503/// The size of the on-demand pool as seen by `pallet_on_demand_para`.
2504///
2505/// On a real Coretime chain this reflects the number of cores the Relay chain has assigned to the
2506/// on-demand pool. This runtime has no Relay chain, so we report a fixed non-zero size.
2507pub struct OnDemandPoolCapacity;
2508impl pallet_on_demand_para::PoolCapacityProvider for OnDemandPoolCapacity {
2509	fn pool_cores() -> u32 {
2510		1
2511	}
2512
2513	#[cfg(feature = "runtime-benchmarks")]
2514	fn ensure_pool_cores(cores: u32) {
2515		assert!(cores <= Self::pool_cores(), "the on-demand pool has a fixed size");
2516	}
2517}
2518
2519impl pallet_on_demand_para::Config for Runtime {
2520	type WeightInfo = pallet_on_demand_para::weights::SubstrateWeight<Runtime>;
2521	type Currency = Balances;
2522	type AdminOrigin = EnsureRoot<AccountId>;
2523	type RelayBlockNumberProvider = System;
2524	type PoolCapacityProvider = OnDemandPoolCapacity;
2525	type PricingProvider = pallet_on_demand_para::DefaultPricingProvider;
2526	// Orders are dropped instead of being forwarded to a Relay chain.
2527	type OrderQueue = ();
2528	type MaxBatchSize = ConstU32<1000>;
2529	type TimeslicePeriod = <Runtime as pallet_broker::Config>::TimeslicePeriod;
2530	type MaxUnclaimedTimeslices = ConstU32<5>;
2531	type PalletId = OnDemandPalletId;
2532}
2533
2534parameter_types! {
2535	pub const MixnetNumCoverToCurrentBlocks: BlockNumber = 3;
2536	pub const MixnetNumRequestsToCurrentBlocks: BlockNumber = 3;
2537	pub const MixnetNumCoverToPrevBlocks: BlockNumber = 3;
2538	pub const MixnetNumRegisterStartSlackBlocks: BlockNumber = 3;
2539	pub const MixnetNumRegisterEndSlackBlocks: BlockNumber = 3;
2540	pub const MixnetRegistrationPriority: TransactionPriority = ImOnlineUnsignedPriority::get() - 1;
2541}
2542
2543impl pallet_mixnet::Config for Runtime {
2544	type MaxAuthorities = MaxAuthorities;
2545	type MaxExternalAddressSize = ConstU32<128>;
2546	type MaxExternalAddressesPerMixnode = ConstU32<16>;
2547	type NextSessionRotation = Babe;
2548	type NumCoverToCurrentBlocks = MixnetNumCoverToCurrentBlocks;
2549	type NumRequestsToCurrentBlocks = MixnetNumRequestsToCurrentBlocks;
2550	type NumCoverToPrevBlocks = MixnetNumCoverToPrevBlocks;
2551	type NumRegisterStartSlackBlocks = MixnetNumRegisterStartSlackBlocks;
2552	type NumRegisterEndSlackBlocks = MixnetNumRegisterEndSlackBlocks;
2553	type RegistrationPriority = MixnetRegistrationPriority;
2554	type MinMixnodes = ConstU32<7>; // Low to allow small testing networks
2555}
2556
2557/// Dynamic parameters that can be changed at runtime through the
2558/// `pallet_parameters::set_parameter`.
2559#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
2560pub mod dynamic_params {
2561	use super::*;
2562
2563	#[dynamic_pallet_params]
2564	#[codec(index = 0)]
2565	pub mod storage {
2566		/// Configures the base deposit of storing some data.
2567		#[codec(index = 0)]
2568		pub static BaseDeposit: Balance = 1 * DOLLARS;
2569
2570		/// Configures the per-byte deposit of storing some data.
2571		#[codec(index = 1)]
2572		pub static ByteDeposit: Balance = 1 * CENTS;
2573	}
2574
2575	#[dynamic_pallet_params]
2576	#[codec(index = 1)]
2577	pub mod referenda {
2578		/// The configuration for the tracks
2579		#[codec(index = 0)]
2580		pub static Tracks: BoundedVec<
2581			pallet_referenda::Track<u16, Balance, BlockNumber>,
2582			ConstU32<100>,
2583		> = BoundedVec::truncate_from(vec![pallet_referenda::Track {
2584			id: 0u16,
2585			info: pallet_referenda::TrackInfo {
2586				name: s("root"),
2587				max_deciding: 1,
2588				decision_deposit: 10,
2589				prepare_period: 4,
2590				decision_period: 4,
2591				confirm_period: 2,
2592				min_enactment_period: 4,
2593				min_approval: pallet_referenda::Curve::LinearDecreasing {
2594					length: Perbill::from_percent(100),
2595					floor: Perbill::from_percent(50),
2596					ceil: Perbill::from_percent(100),
2597				},
2598				min_support: pallet_referenda::Curve::LinearDecreasing {
2599					length: Perbill::from_percent(100),
2600					floor: Perbill::from_percent(0),
2601					ceil: Perbill::from_percent(100),
2602				},
2603			},
2604		}]);
2605
2606		/// A list mapping every origin with a track Id
2607		#[codec(index = 1)]
2608		pub static Origins: BoundedVec<(OriginCaller, u16), ConstU32<100>> =
2609			BoundedVec::truncate_from(vec![(
2610				OriginCaller::system(frame_system::RawOrigin::Root),
2611				0,
2612			)]);
2613	}
2614}
2615
2616#[cfg(feature = "runtime-benchmarks")]
2617impl Default for RuntimeParameters {
2618	fn default() -> Self {
2619		RuntimeParameters::Storage(dynamic_params::storage::Parameters::BaseDeposit(
2620			dynamic_params::storage::BaseDeposit,
2621			Some(1 * DOLLARS),
2622		))
2623	}
2624}
2625
2626pub struct DynamicParametersManagerOrigin;
2627impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParametersManagerOrigin {
2628	type Success = ();
2629
2630	fn try_origin(
2631		origin: RuntimeOrigin,
2632		key: &RuntimeParametersKey,
2633	) -> Result<Self::Success, RuntimeOrigin> {
2634		match key {
2635			RuntimeParametersKey::Storage(_) => {
2636				frame_system::ensure_root(origin.clone()).map_err(|_| origin)?;
2637				return Ok(());
2638			},
2639			RuntimeParametersKey::Referenda(_) => {
2640				frame_system::ensure_root(origin.clone()).map_err(|_| origin)?;
2641				return Ok(());
2642			},
2643		}
2644	}
2645
2646	#[cfg(feature = "runtime-benchmarks")]
2647	fn try_successful_origin(_key: &RuntimeParametersKey) -> Result<RuntimeOrigin, ()> {
2648		Ok(RuntimeOrigin::root())
2649	}
2650}
2651
2652impl pallet_parameters::Config for Runtime {
2653	type RuntimeParameters = RuntimeParameters;
2654	type RuntimeEvent = RuntimeEvent;
2655	type AdminOrigin = DynamicParametersManagerOrigin;
2656	type WeightInfo = ();
2657}
2658
2659pub type MetaTxExtension = (
2660	pallet_verify_signature::VerifySignature<Runtime>,
2661	pallet_meta_tx::MetaTxMarker<Runtime>,
2662	frame_system::CheckNonZeroSender<Runtime>,
2663	frame_system::CheckSpecVersion<Runtime>,
2664	frame_system::CheckTxVersion<Runtime>,
2665	frame_system::CheckGenesis<Runtime>,
2666	frame_system::CheckEra<Runtime>,
2667	frame_system::CheckNonce<Runtime>,
2668	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
2669);
2670
2671impl pallet_meta_tx::Config for Runtime {
2672	type WeightInfo = ();
2673	type RuntimeEvent = RuntimeEvent;
2674	#[cfg(not(feature = "runtime-benchmarks"))]
2675	type Extension = MetaTxExtension;
2676	#[cfg(feature = "runtime-benchmarks")]
2677	type Extension = pallet_meta_tx::WeightlessExtension<Runtime>;
2678}
2679
2680/// Discards registrar messages; the counterpart chain is not modelled here.
2681pub struct DiscardRegistrarMessages;
2682
2683impl pallet_registrar_para::SendToRelay for DiscardRegistrarMessages {
2684	type AccountId = AccountId;
2685
2686	fn send(_message: registrar_primitives::MessageToRelay<AccountId>) -> Result<(), ()> {
2687		Ok(())
2688	}
2689}
2690
2691impl pallet_registrar_relay::SendToPara for DiscardRegistrarMessages {
2692	fn send(_message: registrar_primitives::MessageToPara) -> Result<(), ()> {
2693		Ok(())
2694	}
2695}
2696
2697parameter_types! {
2698	pub const ParaIdReservationDeposit: Balance = 100 * DOLLARS;
2699	pub const RegistrationDepositPerByte: Balance = 10 * MILLICENTS;
2700	pub const ParaIdReservationHoldReason: RuntimeHoldReason =
2701		RuntimeHoldReason::RegistrarPara(pallet_registrar_para::HoldReason::ParaIdReservation);
2702	pub const RegistrationHoldReason: RuntimeHoldReason =
2703		RuntimeHoldReason::RegistrarPara(pallet_registrar_para::HoldReason::Registration);
2704	// No parachain-system here, so a fixed stand-in for the relay chain's host configuration.
2705	pub storage RegistrarHostConfig: Option<polkadot_primitives::AbridgedHostConfiguration> =
2706		Some(polkadot_primitives::AbridgedHostConfiguration {
2707			max_code_size: 3 * 1024 * 1024,
2708			max_head_data_size: 1024 * 1024,
2709			max_upward_queue_count: 0,
2710			max_upward_queue_size: 0,
2711			max_upward_message_size: 0,
2712			max_upward_message_num_per_candidate: 0,
2713			hrmp_max_message_num_per_candidate: 0,
2714			validation_upgrade_cooldown: 0,
2715			validation_upgrade_delay: 0,
2716			async_backing_params: polkadot_primitives::AsyncBackingParams {
2717				allowed_ancestry_len: 0,
2718				max_candidate_depth: 0,
2719			},
2720		});
2721}
2722
2723#[cfg(feature = "runtime-benchmarks")]
2724impl pallet_registrar_para::BenchmarkHelper for RegistrarHostConfig {
2725	fn set_host_configuration(config: polkadot_primitives::AbridgedHostConfiguration) {
2726		RegistrarHostConfig::set(&Some(config));
2727	}
2728}
2729
2730impl pallet_registrar_para::Config for Runtime {
2731	type ReservationConsideration = HoldConsideration<
2732		AccountId,
2733		Balances,
2734		ParaIdReservationHoldReason,
2735		ConstantStoragePrice<ParaIdReservationDeposit, Balance>,
2736	>;
2737	type RegistrationConsideration = HoldConsideration<
2738		AccountId,
2739		Balances,
2740		RegistrationHoldReason,
2741		LinearStoragePrice<ConstU128<0>, RegistrationDepositPerByte, Balance>,
2742	>;
2743	type SendToRelay = DiscardRegistrarMessages;
2744	type RelayOrigin = EnsureRoot<AccountId>;
2745	type ParachainOrigin = frame_system::EnsureNever<registrar_primitives::ParaId>;
2746	type ForceOrigin = EnsureRoot<AccountId>;
2747	type FirstPublicParaId = ConstU32<2000>;
2748	type MinCodeSize = ConstU32<9>;
2749	type HostConfiguration = RegistrarHostConfig;
2750	type PendingDeadline = ConstU32<600>;
2751	type BlockNumberProvider = System;
2752	type WeightInfo = pallet_registrar_para::weights::SubstrateWeight<Runtime>;
2753	#[cfg(feature = "runtime-benchmarks")]
2754	type BenchmarkHelper = RegistrarHostConfig;
2755}
2756
2757/// A registrar that accepts everything; only which ids it holds is modelled, not the paras stack.
2758pub struct AcceptingRegistrar;
2759
2760impl AcceptingRegistrar {
2761	fn key(para_id: registrar_primitives::ParaId) -> Vec<u8> {
2762		(b"AcceptingRegistrar", para_id).encode()
2763	}
2764}
2765
2766impl registrar_primitives::ParachainRegistrar for AcceptingRegistrar {
2767	type AccountId = AccountId;
2768
2769	fn check_onboarding(_head_len: u32, _code_len: u32) -> Result<(), ()> {
2770		Ok(())
2771	}
2772
2773	fn is_registered(para_id: registrar_primitives::ParaId) -> bool {
2774		frame_support::storage::unhashed::exists(&Self::key(para_id))
2775	}
2776
2777	fn register(
2778		_manager: AccountId,
2779		para_id: registrar_primitives::ParaId,
2780		_genesis_head: Vec<u8>,
2781		_validation_code: Vec<u8>,
2782	) -> sp_runtime::DispatchResult {
2783		frame_support::storage::unhashed::put(&Self::key(para_id), &true);
2784		Ok(())
2785	}
2786
2787	fn deregister(para_id: registrar_primitives::ParaId) -> sp_runtime::DispatchResult {
2788		frame_support::storage::unhashed::kill(&Self::key(para_id));
2789		Ok(())
2790	}
2791
2792	#[cfg(feature = "runtime-benchmarks")]
2793	fn setup_worst_case_deregister(
2794		para_id: registrar_primitives::ParaId,
2795	) -> sp_runtime::DispatchResult {
2796		frame_support::storage::unhashed::put(&Self::key(para_id), &true);
2797		Ok(())
2798	}
2799
2800	fn check_head_data(_head_len: u32) -> Result<(), ()> {
2801		Ok(())
2802	}
2803
2804	fn set_current_head(_para_id: registrar_primitives::ParaId, _head: Vec<u8>) {}
2805
2806	fn check_code_upgrade(
2807		_para_id: registrar_primitives::ParaId,
2808		_code_len: u32,
2809	) -> Result<(), ()> {
2810		Ok(())
2811	}
2812
2813	#[cfg(feature = "runtime-benchmarks")]
2814	fn setup_worst_case_code_upgrade(
2815		para_id: registrar_primitives::ParaId,
2816	) -> sp_runtime::DispatchResult {
2817		frame_support::storage::unhashed::put(&Self::key(para_id), &true);
2818		Ok(())
2819	}
2820
2821	fn schedule_code_upgrade(
2822		_para_id: registrar_primitives::ParaId,
2823		_validation_code: Vec<u8>,
2824	) -> sp_runtime::DispatchResult {
2825		Ok(())
2826	}
2827}
2828
2829impl pallet_registrar_relay::Config for Runtime {
2830	type RuntimeEvent = RuntimeEvent;
2831	type ParaOrigin = EnsureRoot<AccountId>;
2832	type SendToPara = DiscardRegistrarMessages;
2833	type Registrar = AcceptingRegistrar;
2834	type MaxHeadDataSize = ConstU32<{ 1024 * 1024 }>;
2835	type MaxCodeSize = ConstU32<{ 3 * 1024 * 1024 }>;
2836	type MaxPendingRegistrations = ConstU32<128>;
2837	type CodeUpgradeValidPeriod = ConstU32<600>;
2838	type UnsignedPriority = ConstU64<100>;
2839	type WeightInfo = pallet_registrar_relay::weights::SubstrateWeight<Runtime>;
2840}
2841
2842impl parachains_origin::Config for Runtime {}
2843
2844/// Discards HRMP deposit messages; the counterpart chain is not modelled here.
2845pub struct DiscardHrmpMessages;
2846
2847impl pallet_hrmp_relay::SendToPara for DiscardHrmpMessages {
2848	fn send(_message: MessageToPara) -> Result<(), ()> {
2849		Ok(())
2850	}
2851}
2852
2853impl pallet_hrmp_para::SendToRelay for DiscardHrmpMessages {
2854	fn send(_message: MessageToRelay) -> Result<(), ()> {
2855		Ok(())
2856	}
2857}
2858
2859/// Ignores the answers to HRMP deposit requests; the relay chain's `hrmp` pallet is not here.
2860pub struct IgnoreDepositAnswers;
2861
2862impl OnDepositSet for IgnoreDepositAnswers {
2863	fn on_deposit_set(_request: DepositChangeRequest, _result: Result<(), DepositError>) {}
2864
2865	fn weight_of_on_deposit_set(_action: &DepositAction) -> Weight {
2866		Weight::zero()
2867	}
2868}
2869
2870parameter_types! {
2871	pub const HrmpHolderParaId: ParaId = ParaId::new(1005);
2872}
2873
2874impl pallet_hrmp_relay::Config for Runtime {
2875	type OnDepositSet = IgnoreDepositAnswers;
2876	type HolderParaId = HrmpHolderParaId;
2877	type SendToPara = DiscardHrmpMessages;
2878	type MaxFailedReleases = ConstU32<16>;
2879	type WeightInfo = pallet_hrmp_relay::weights::SubstrateWeight<Runtime>;
2880	#[cfg(feature = "runtime-benchmarks")]
2881	type BenchmarkHelper = ();
2882}
2883
2884/// A para's sovereign account, as the relay chain derives it.
2885pub struct ParaSovereignAccount;
2886
2887impl Convert<hrmp_primitives::ParaId, AccountId> for ParaSovereignAccount {
2888	fn convert(para: hrmp_primitives::ParaId) -> AccountId {
2889		ParaId::from(para).into_account_truncating()
2890	}
2891}
2892
2893impl pallet_hrmp_para::Config for Runtime {
2894	type Currency = Balances;
2895	type SendToRelay = DiscardHrmpMessages;
2896	type SovereignAccountOf = ParaSovereignAccount;
2897	type WeightInfo = pallet_hrmp_para::weights::SubstrateWeight<Runtime>;
2898	#[cfg(feature = "runtime-benchmarks")]
2899	type BenchmarkHelper = ();
2900}
2901
2902#[frame_support::runtime]
2903mod runtime {
2904	use super::*;
2905
2906	#[runtime::runtime]
2907	#[runtime::derive(
2908		RuntimeCall,
2909		RuntimeEvent,
2910		RuntimeError,
2911		RuntimeOrigin,
2912		RuntimeFreezeReason,
2913		RuntimeHoldReason,
2914		RuntimeSlashReason,
2915		RuntimeLockId,
2916		RuntimeTask,
2917		RuntimeViewFunction
2918	)]
2919	pub struct Runtime;
2920
2921	#[runtime::pallet_index(0)]
2922	pub type System = frame_system::Pallet<Runtime>;
2923
2924	#[runtime::pallet_index(1)]
2925	pub type Utility = pallet_utility::Pallet<Runtime>;
2926
2927	#[runtime::pallet_index(2)]
2928	pub type Babe = pallet_babe::Pallet<Runtime>;
2929
2930	#[runtime::pallet_index(3)]
2931	pub type Timestamp = pallet_timestamp::Pallet<Runtime>;
2932
2933	// Authorship must be before session in order to note author in the correct session and era
2934	// for im-online and staking.
2935	#[runtime::pallet_index(4)]
2936	pub type Authorship = pallet_authorship::Pallet<Runtime>;
2937
2938	#[runtime::pallet_index(5)]
2939	pub type Indices = pallet_indices::Pallet<Runtime>;
2940
2941	#[runtime::pallet_index(6)]
2942	pub type Balances = pallet_balances::Pallet<Runtime>;
2943
2944	#[runtime::pallet_index(7)]
2945	pub type TransactionPayment = pallet_transaction_payment::Pallet<Runtime>;
2946
2947	#[runtime::pallet_index(9)]
2948	pub type AssetConversionTxPayment = pallet_asset_conversion_tx_payment::Pallet<Runtime>;
2949
2950	#[runtime::pallet_index(10)]
2951	pub type ElectionProviderMultiPhase = pallet_election_provider_multi_phase::Pallet<Runtime>;
2952
2953	#[runtime::pallet_index(11)]
2954	pub type Staking = pallet_staking::Pallet<Runtime>;
2955
2956	#[runtime::pallet_index(12)]
2957	pub type Session = pallet_session::Pallet<Runtime>;
2958
2959	#[runtime::pallet_index(13)]
2960	pub type Democracy = pallet_democracy::Pallet<Runtime>;
2961
2962	#[runtime::pallet_index(14)]
2963	pub type Council = pallet_collective::Pallet<Runtime, Instance1>;
2964
2965	#[runtime::pallet_index(15)]
2966	pub type TechnicalCommittee = pallet_collective::Pallet<Runtime, Instance2>;
2967
2968	#[runtime::pallet_index(16)]
2969	pub type Elections = pallet_elections_phragmen::Pallet<Runtime>;
2970
2971	#[runtime::pallet_index(17)]
2972	pub type TechnicalMembership = pallet_membership::Pallet<Runtime, Instance1>;
2973
2974	#[runtime::pallet_index(18)]
2975	pub type Grandpa = pallet_grandpa::Pallet<Runtime>;
2976
2977	#[runtime::pallet_index(19)]
2978	pub type Treasury = pallet_treasury::Pallet<Runtime>;
2979
2980	#[runtime::pallet_index(20)]
2981	pub type AssetRate = pallet_asset_rate::Pallet<Runtime>;
2982
2983	#[runtime::pallet_index(21)]
2984	pub type Contracts = pallet_contracts::Pallet<Runtime>;
2985
2986	#[runtime::pallet_index(22)]
2987	pub type Sudo = pallet_sudo::Pallet<Runtime>;
2988
2989	#[runtime::pallet_index(23)]
2990	pub type ImOnline = pallet_im_online::Pallet<Runtime>;
2991
2992	#[runtime::pallet_index(24)]
2993	pub type AuthorityDiscovery = pallet_authority_discovery::Pallet<Runtime>;
2994
2995	#[runtime::pallet_index(25)]
2996	pub type Offences = pallet_offences::Pallet<Runtime>;
2997
2998	#[runtime::pallet_index(26)]
2999	pub type Historical = pallet_session_historical::Pallet<Runtime>;
3000
3001	#[runtime::pallet_index(27)]
3002	pub type RandomnessCollectiveFlip = pallet_insecure_randomness_collective_flip::Pallet<Runtime>;
3003
3004	#[runtime::pallet_index(28)]
3005	pub type Identity = pallet_identity::Pallet<Runtime>;
3006
3007	#[runtime::pallet_index(29)]
3008	pub type Society = pallet_society::Pallet<Runtime>;
3009
3010	#[runtime::pallet_index(30)]
3011	pub type Recovery = pallet_recovery::Pallet<Runtime>;
3012
3013	#[runtime::pallet_index(31)]
3014	pub type Vesting = pallet_vesting::Pallet<Runtime>;
3015
3016	#[runtime::pallet_index(32)]
3017	pub type Scheduler = pallet_scheduler::Pallet<Runtime>;
3018
3019	#[runtime::pallet_index(33)]
3020	pub type Glutton = pallet_glutton::Pallet<Runtime>;
3021
3022	#[runtime::pallet_index(34)]
3023	pub type Preimage = pallet_preimage::Pallet<Runtime>;
3024
3025	#[runtime::pallet_index(35)]
3026	pub type Proxy = pallet_proxy::Pallet<Runtime>;
3027
3028	#[runtime::pallet_index(36)]
3029	pub type Multisig = pallet_multisig::Pallet<Runtime>;
3030
3031	#[runtime::pallet_index(37)]
3032	pub type Bounties = pallet_bounties::Pallet<Runtime>;
3033
3034	#[runtime::pallet_index(38)]
3035	pub type Tips = pallet_tips::Pallet<Runtime>;
3036
3037	#[runtime::pallet_index(39)]
3038	pub type Assets = pallet_assets::Pallet<Runtime, Instance1>;
3039
3040	#[runtime::pallet_index(40)]
3041	pub type PoolAssets = pallet_assets::Pallet<Runtime, Instance2>;
3042
3043	#[runtime::pallet_index(41)]
3044	pub type Beefy = pallet_beefy::Pallet<Runtime>;
3045
3046	// MMR leaf construction must be after session in order to have a leaf's next_auth_set
3047	// refer to block<N>. See issue polkadot-fellows/runtimes#160 for details.
3048	#[runtime::pallet_index(42)]
3049	pub type Mmr = pallet_mmr::Pallet<Runtime>;
3050
3051	#[runtime::pallet_index(43)]
3052	pub type MmrLeaf = pallet_beefy_mmr::Pallet<Runtime>;
3053
3054	#[runtime::pallet_index(44)]
3055	pub type Lottery = pallet_lottery::Pallet<Runtime>;
3056
3057	#[runtime::pallet_index(45)]
3058	pub type Nis = pallet_nis::Pallet<Runtime>;
3059
3060	#[runtime::pallet_index(46)]
3061	pub type Uniques = pallet_uniques::Pallet<Runtime>;
3062
3063	#[runtime::pallet_index(47)]
3064	pub type Nfts = pallet_nfts::Pallet<Runtime>;
3065
3066	#[runtime::pallet_index(48)]
3067	pub type NftFractionalization = pallet_nft_fractionalization::Pallet<Runtime>;
3068
3069	#[runtime::pallet_index(49)]
3070	pub type Salary = pallet_salary::Pallet<Runtime>;
3071
3072	#[runtime::pallet_index(50)]
3073	pub type CoreFellowship = pallet_core_fellowship::Pallet<Runtime>;
3074
3075	#[runtime::pallet_index(51)]
3076	pub type TransactionStorage = pallet_transaction_storage::Pallet<Runtime>;
3077
3078	#[runtime::pallet_index(52)]
3079	pub type VoterList = pallet_bags_list::Pallet<Runtime, Instance1>;
3080
3081	#[runtime::pallet_index(53)]
3082	pub type StateTrieMigration = pallet_state_trie_migration::Pallet<Runtime>;
3083
3084	#[runtime::pallet_index(54)]
3085	pub type ChildBounties = pallet_child_bounties::Pallet<Runtime>;
3086
3087	#[runtime::pallet_index(55)]
3088	pub type Referenda = pallet_referenda::Pallet<Runtime>;
3089
3090	#[runtime::pallet_index(56)]
3091	pub type Remark = pallet_remark::Pallet<Runtime>;
3092
3093	#[runtime::pallet_index(57)]
3094	pub type RootTesting = pallet_root_testing::Pallet<Runtime>;
3095
3096	#[runtime::pallet_index(58)]
3097	pub type ConvictionVoting = pallet_conviction_voting::Pallet<Runtime>;
3098
3099	#[runtime::pallet_index(59)]
3100	pub type Whitelist = pallet_whitelist::Pallet<Runtime>;
3101
3102	#[runtime::pallet_index(60)]
3103	pub type AllianceMotion = pallet_collective::Pallet<Runtime, Instance3>;
3104
3105	#[runtime::pallet_index(61)]
3106	pub type Alliance = pallet_alliance::Pallet<Runtime>;
3107
3108	#[runtime::pallet_index(62)]
3109	pub type NominationPools = pallet_nomination_pools::Pallet<Runtime>;
3110
3111	#[runtime::pallet_index(63)]
3112	pub type RankedPolls = pallet_referenda::Pallet<Runtime, Instance2>;
3113
3114	#[runtime::pallet_index(64)]
3115	pub type RankedCollective = pallet_ranked_collective::Pallet<Runtime>;
3116
3117	#[runtime::pallet_index(65)]
3118	pub type AssetConversion = pallet_asset_conversion::Pallet<Runtime>;
3119
3120	#[runtime::pallet_index(66)]
3121	pub type FastUnstake = pallet_fast_unstake::Pallet<Runtime>;
3122
3123	#[runtime::pallet_index(67)]
3124	pub type MessageQueue = pallet_message_queue::Pallet<Runtime>;
3125
3126	#[runtime::pallet_index(68)]
3127	pub type Pov = frame_benchmarking_pallet_pov::Pallet<Runtime>;
3128
3129	#[runtime::pallet_index(69)]
3130	pub type TxPause = pallet_tx_pause::Pallet<Runtime>;
3131
3132	#[runtime::pallet_index(70)]
3133	pub type SafeMode = pallet_safe_mode::Pallet<Runtime>;
3134
3135	#[runtime::pallet_index(71)]
3136	pub type Statement = pallet_statement::Pallet<Runtime>;
3137
3138	#[runtime::pallet_index(72)]
3139	pub type MultiBlockMigrations = pallet_migrations::Pallet<Runtime>;
3140
3141	#[runtime::pallet_index(73)]
3142	pub type Broker = pallet_broker::Pallet<Runtime>;
3143
3144	#[runtime::pallet_index(74)]
3145	pub type TasksExample = pallet_example_tasks::Pallet<Runtime>;
3146
3147	#[runtime::pallet_index(75)]
3148	pub type Mixnet = pallet_mixnet::Pallet<Runtime>;
3149
3150	#[runtime::pallet_index(76)]
3151	pub type Parameters = pallet_parameters::Pallet<Runtime>;
3152
3153	#[runtime::pallet_index(77)]
3154	pub type SkipFeelessPayment = pallet_skip_feeless_payment::Pallet<Runtime>;
3155
3156	#[runtime::pallet_index(78)]
3157	pub type PalletExampleMbms = pallet_example_mbm::Pallet<Runtime>;
3158
3159	#[runtime::pallet_index(79)]
3160	pub type AssetConversionMigration = pallet_asset_conversion_ops::Pallet<Runtime>;
3161
3162	#[runtime::pallet_index(80)]
3163	pub type Revive = pallet_revive::Pallet<Runtime>;
3164
3165	#[runtime::pallet_index(81)]
3166	pub type VerifySignature = pallet_verify_signature::Pallet<Runtime>;
3167
3168	#[runtime::pallet_index(82)]
3169	pub type DelegatedStaking = pallet_delegated_staking::Pallet<Runtime>;
3170
3171	#[runtime::pallet_index(83)]
3172	pub type AssetRewards = pallet_asset_rewards::Pallet<Runtime>;
3173
3174	#[runtime::pallet_index(84)]
3175	pub type AssetsFreezer = pallet_assets_freezer::Pallet<Runtime, Instance1>;
3176
3177	#[runtime::pallet_index(85)]
3178	pub type Oracle = pallet_oracle::Pallet<Runtime>;
3179
3180	#[runtime::pallet_index(86)]
3181	pub type Psm = pallet_psm::Pallet<Runtime>;
3182
3183	#[runtime::pallet_index(89)]
3184	pub type MetaTx = pallet_meta_tx::Pallet<Runtime>;
3185
3186	#[runtime::pallet_index(90)]
3187	pub type MultiAssetBounties = pallet_multi_asset_bounties::Pallet<Runtime>;
3188
3189	#[runtime::pallet_index(91)]
3190	pub type AssetsPrecompiles = pallet_assets_precompiles::pallet::Pallet<Runtime>;
3191
3192	#[runtime::pallet_index(92)]
3193	pub type AssetsPrecompilesPermit = pallet_assets_precompiles::permit::pallet::Pallet<Runtime>;
3194
3195	#[runtime::pallet_index(93)]
3196	pub type VestingPrecompiles = pallet_vesting_precompiles::pallet::Pallet<Runtime>;
3197
3198	#[runtime::pallet_index(94)]
3199	pub type Dap = pallet_dap::Pallet<Runtime>;
3200
3201	#[runtime::pallet_index(95)]
3202	pub type RegistrarPara = pallet_registrar_para::Pallet<Runtime>;
3203
3204	#[runtime::pallet_index(96)]
3205	pub type RegistrarRelay = pallet_registrar_relay::Pallet<Runtime>;
3206
3207	#[runtime::pallet_index(97)]
3208	pub type OnDemand = pallet_on_demand_para::Pallet<Runtime>;
3209
3210	#[runtime::pallet_index(98)]
3211	pub type ParachainsOrigin = parachains_origin::Pallet<Runtime>;
3212
3213	#[runtime::pallet_index(99)]
3214	pub type HrmpRelay = pallet_hrmp_relay::Pallet<Runtime>;
3215
3216	#[runtime::pallet_index(100)]
3217	pub type HrmpPara = pallet_hrmp_para::Pallet<Runtime>;
3218}
3219
3220/// The address format for describing accounts.
3221pub type Address = sp_runtime::MultiAddress<AccountId, AccountIndex>;
3222/// Block header type as expected by this runtime.
3223pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
3224/// Block type as expected by this runtime.
3225pub type Block = generic::Block<Header, UncheckedExtrinsic>;
3226/// A Block signed with a Justification
3227pub type SignedBlock = generic::SignedBlock<Block>;
3228/// BlockId type as expected by this runtime.
3229pub type BlockId = generic::BlockId<Block>;
3230/// The TransactionExtension to the basic transaction logic.
3231///
3232/// When you change this, you **MUST** modify [`sign`] in `bin/node/testing/src/keyring.rs`!
3233///
3234/// [`sign`]: <../../testing/src/keyring.rs.html>
3235pub type TxExtension = (
3236	frame_system::AuthorizeCall<Runtime>,
3237	frame_system::CheckNonZeroSender<Runtime>,
3238	frame_system::CheckSpecVersion<Runtime>,
3239	frame_system::CheckTxVersion<Runtime>,
3240	frame_system::CheckGenesis<Runtime>,
3241	frame_system::CheckEra<Runtime>,
3242	frame_system::CheckNonce<Runtime>,
3243	frame_system::CheckWeight<Runtime>,
3244	pallet_skip_feeless_payment::SkipCheckIfFeeless<
3245		Runtime,
3246		pallet_asset_conversion_tx_payment::ChargeAssetTxPayment<Runtime>,
3247	>,
3248	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
3249	pallet_revive::evm::tx_extension::SetOrigin<Runtime>,
3250	frame_system::WeightReclaim<Runtime>,
3251);
3252
3253#[derive(Clone, PartialEq, Eq, Debug)]
3254pub struct EthExtraImpl;
3255
3256impl EthExtra for EthExtraImpl {
3257	type Config = Runtime;
3258	type ExtensionV0 = TxExtension;
3259	type ExtensionOtherVersions = sp_runtime::traits::InvalidVersion;
3260
3261	fn get_eth_extension(nonce: u32, tip: Balance) -> Self::ExtensionV0 {
3262		(
3263			frame_system::AuthorizeCall::<Runtime>::new(),
3264			frame_system::CheckNonZeroSender::<Runtime>::new(),
3265			frame_system::CheckSpecVersion::<Runtime>::new(),
3266			frame_system::CheckTxVersion::<Runtime>::new(),
3267			frame_system::CheckGenesis::<Runtime>::new(),
3268			frame_system::CheckEra::from(crate::generic::Era::Immortal),
3269			frame_system::CheckNonce::<Runtime>::from(nonce),
3270			frame_system::CheckWeight::<Runtime>::new(),
3271			pallet_asset_conversion_tx_payment::ChargeAssetTxPayment::<Runtime>::from(tip, None)
3272				.into(),
3273			frame_metadata_hash_extension::CheckMetadataHash::<Runtime>::new(false),
3274			pallet_revive::evm::tx_extension::SetOrigin::<Runtime>::new_from_eth_transaction(),
3275			frame_system::WeightReclaim::<Runtime>::new(),
3276		)
3277	}
3278}
3279
3280/// Unchecked extrinsic type as expected by this runtime.
3281pub type UncheckedExtrinsic =
3282	pallet_revive::evm::runtime::UncheckedExtrinsic<Address, Signature, EthExtraImpl>;
3283/// Unchecked signature payload type as expected by this runtime.
3284pub type UncheckedSignaturePayload =
3285	generic::UncheckedSignaturePayload<Address, Signature, TxExtension>;
3286/// The payload being signed in transactions.
3287pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
3288/// Extrinsic type that has already been checked.
3289pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
3290/// Executive: handles dispatch to the various modules.
3291pub type Executive = frame_executive::Executive<
3292	Runtime,
3293	Block,
3294	frame_system::ChainContext<Runtime>,
3295	Runtime,
3296	AllPalletsWithSystem,
3297>;
3298
3299// We don't have a limit in the Relay Chain.
3300const IDENTITY_MIGRATION_KEY_LIMIT: u64 = u64::MAX;
3301
3302// All migrations executed on runtime upgrade as a nested tuple of types implementing
3303// `OnRuntimeUpgrade`. Note: These are examples and do not need to be run directly
3304// after the genesis block.
3305type Migrations = (
3306	pallet_nomination_pools::migration::versioned::V6ToV7<Runtime>,
3307	pallet_alliance::migration::Migration<Runtime>,
3308	pallet_contracts::Migration<Runtime>,
3309	pallet_identity::migration::versioned::V0ToV1<Runtime, IDENTITY_MIGRATION_KEY_LIMIT>,
3310	pallet_collective::migrations::v5::MigrateToV5<Runtime, CouncilCollective>,
3311	pallet_collective::migrations::v5::MigrateToV5<Runtime, TechnicalCollective>,
3312	pallet_collective::migrations::v5::MigrateToV5<Runtime, AllianceCollective>,
3313);
3314
3315type EventRecord = frame_system::EventRecord<
3316	<Runtime as frame_system::Config>::RuntimeEvent,
3317	<Runtime as frame_system::Config>::Hash,
3318>;
3319
3320parameter_types! {
3321	pub const BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
3322}
3323
3324impl pallet_beefy::Config for Runtime {
3325	type BeefyId = BeefyId;
3326	type MaxAuthorities = MaxAuthorities;
3327	type MaxNominators = ConstU32<0>;
3328	type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
3329	type OnNewValidatorSet = MmrLeaf;
3330	type AncestryHelper = MmrLeaf;
3331	type WeightInfo = ();
3332	type KeyOwnerProof = sp_session::MembershipProof;
3333	type EquivocationReportSystem =
3334		pallet_beefy::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
3335}
3336
3337parameter_types! {
3338	pub const OracleMaxHasDispatchedSize: u32 = 20;
3339	pub const RootOperatorAccountId: AccountId = AccountId::new([0xffu8; 32]);
3340
3341	pub const OracleMaxFeedValues: u32 = 10;
3342}
3343
3344#[cfg(feature = "runtime-benchmarks")]
3345pub struct OracleBenchmarkingHelper;
3346
3347#[cfg(feature = "runtime-benchmarks")]
3348impl pallet_oracle::BenchmarkHelper<u32, u128, OracleMaxFeedValues> for OracleBenchmarkingHelper {
3349	fn get_currency_id_value_pairs() -> BoundedVec<(u32, u128), OracleMaxFeedValues> {
3350		use rand::{distributions::Uniform, prelude::*};
3351
3352		// Use seeded RNG like in contracts benchmarking
3353		let mut rng = rand_pcg::Pcg32::seed_from_u64(0x1234567890ABCDEF);
3354		let max_values = OracleMaxFeedValues::get() as usize;
3355
3356		// Generate random pairs like in election-provider-multi-phase
3357		let currency_range = Uniform::new_inclusive(1, 1000);
3358		let value_range = Uniform::new_inclusive(1000, 1_000_000);
3359
3360		let pairs: Vec<(u32, u128)> = (0..max_values)
3361			.map(|_| {
3362				let currency_id = rng.sample(currency_range);
3363				let value = rng.sample(value_range);
3364				(currency_id, value)
3365			})
3366			.collect();
3367
3368		// Use try_from pattern like in core-fellowship and broker
3369		BoundedVec::try_from(pairs).unwrap_or_default()
3370	}
3371}
3372
3373parameter_types! {
3374	pub const OraclePalletId: PalletId = PalletId(*b"py/oracl");
3375}
3376
3377impl pallet_oracle::Config for Runtime {
3378	type OnNewData = ();
3379	type CombineData = pallet_oracle::DefaultCombineData<Self, ConstU32<5>, ConstU64<3600>>;
3380	type Time = Timestamp;
3381	type OracleKey = u32;
3382	type OracleValue = u128;
3383	type PalletId = OraclePalletId;
3384	type Members = TechnicalMembership;
3385	type WeightInfo = ();
3386	type MaxHasDispatchedSize = OracleMaxHasDispatchedSize;
3387	type MaxFeedValues = OracleMaxFeedValues;
3388	#[cfg(feature = "runtime-benchmarks")]
3389	type BenchmarkHelper = OracleBenchmarkingHelper;
3390}
3391
3392parameter_types! {
3393	/// PalletId for deriving the PSM system account.
3394	pub const PsmPalletId: PalletId = PalletId(*b"py/pegsm");
3395	/// Base deposit held for the footprint of a PSM created via `create_psm`.
3396	pub const PsmCreationDeposit: Balance = 10 * DOLLARS;
3397	/// Per-byte deposit slope; PSM footprints are fixed-size, so this is zero.
3398	pub const PsmDepositSlope: Balance = 0;
3399	pub PsmHoldReason: RuntimeHoldReason = RuntimeHoldReason::Psm(pallet_psm::HoldReason::CreationDeposit);
3400}
3401
3402#[cfg(feature = "runtime-benchmarks")]
3403pub struct PsmBenchmarkHelper;
3404#[cfg(feature = "runtime-benchmarks")]
3405impl pallet_psm::BenchmarkHelper<u32, AccountId> for PsmBenchmarkHelper {
3406	fn get_asset_id(asset_index: u32) -> u32 {
3407		asset_index
3408	}
3409	fn create_asset(asset_id: u32, owner: &AccountId, decimals: u8) {
3410		use frame_support::traits::fungibles::{metadata::Mutate as MetadataMutate, Create};
3411		if !<Assets as frame_support::traits::fungibles::Inspect<AccountId>>::asset_exists(asset_id)
3412		{
3413			let _ = <Assets as Create<AccountId>>::create(asset_id, owner.clone(), true, 1);
3414		}
3415		let _ = Balances::force_set_balance(
3416			RuntimeOrigin::root(),
3417			owner.clone().into(),
3418			10u128.pow(18),
3419		);
3420		let _ = <Assets as MetadataMutate<AccountId>>::set(
3421			asset_id,
3422			owner,
3423			b"Benchmark".to_vec(),
3424			b"BNC".to_vec(),
3425			decimals,
3426		);
3427	}
3428}
3429
3430/// Configure the PSM (Peg Stability Module) pallet.
3431impl pallet_psm::Config for Runtime {
3432	type Fungibles = Assets;
3433	type Consideration = HoldConsideration<
3434		AccountId,
3435		Balances,
3436		PsmHoldReason,
3437		LinearStoragePrice<PsmCreationDeposit, PsmDepositSlope, Balance>,
3438	>;
3439	type CreateOrigin = pallet_psm::EnsureAssetOwner<Runtime>;
3440	type RuntimeOrigin = RuntimeOrigin;
3441	type PalletsOrigin = OriginCaller;
3442	type AssetId = u32;
3443	type WeightInfo = pallet_psm::weights::SubstrateWeight<Runtime>;
3444	type PalletId = PsmPalletId;
3445	type MaxExternals = ConstU32<10>;
3446	#[cfg(feature = "runtime-benchmarks")]
3447	type BenchmarkHelper = PsmBenchmarkHelper;
3448}
3449
3450/// MMR helper types.
3451mod mmr {
3452	use super::*;
3453	pub use pallet_mmr::primitives::*;
3454
3455	pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
3456	pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
3457	pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
3458}
3459
3460#[cfg(feature = "runtime-benchmarks")]
3461pub struct AssetConversionTxHelper;
3462
3463#[cfg(feature = "runtime-benchmarks")]
3464impl
3465	pallet_asset_conversion_tx_payment::BenchmarkHelperTrait<
3466		AccountId,
3467		NativeOrWithId<u32>,
3468		NativeOrWithId<u32>,
3469	> for AssetConversionTxHelper
3470{
3471	fn create_asset_id_parameter(seed: u32) -> (NativeOrWithId<u32>, NativeOrWithId<u32>) {
3472		(NativeOrWithId::WithId(seed), NativeOrWithId::WithId(seed))
3473	}
3474
3475	fn setup_balances_and_pool(asset_id: NativeOrWithId<u32>, account: AccountId) {
3476		use frame_support::{assert_ok, traits::fungibles::Mutate};
3477		let NativeOrWithId::WithId(asset_idx) = asset_id.clone() else { unimplemented!() };
3478		assert_ok!(Assets::force_create(
3479			RuntimeOrigin::root(),
3480			asset_idx.into(),
3481			account.clone().into(), // owner
3482			true,                   // is_sufficient
3483			1,
3484		));
3485
3486		let lp_provider = account.clone();
3487		let _ = Balances::deposit_creating(&lp_provider, ((u64::MAX as u128) * 100).into());
3488		assert_ok!(Assets::mint_into(
3489			asset_idx.into(),
3490			&lp_provider,
3491			((u64::MAX as u128) * 100).into()
3492		));
3493
3494		let token_native = alloc::boxed::Box::new(NativeOrWithId::Native);
3495		let token_second = alloc::boxed::Box::new(asset_id);
3496
3497		assert_ok!(AssetConversion::create_pool(
3498			RuntimeOrigin::signed(lp_provider.clone()),
3499			token_native.clone(),
3500			token_second.clone()
3501		));
3502
3503		assert_ok!(AssetConversion::add_liquidity(
3504			RuntimeOrigin::signed(lp_provider.clone()),
3505			token_native,
3506			token_second,
3507			u64::MAX.into(), // 1 desired
3508			u64::MAX.into(), // 2 desired
3509			1,               // 1 min
3510			1,               // 2 min
3511			lp_provider,
3512		));
3513	}
3514}
3515
3516#[cfg(feature = "runtime-benchmarks")]
3517mod benches {
3518	polkadot_sdk::frame_benchmarking::define_benchmarks!(
3519		[frame_benchmarking, BaselineBench::<Runtime>]
3520		[frame_benchmarking_pallet_pov, Pov]
3521		[pallet_alliance, Alliance]
3522		[pallet_assets, Assets]
3523		[pallet_babe, Babe]
3524		[pallet_bags_list, VoterList]
3525		[pallet_balances, Balances]
3526		[pallet_beefy_mmr, MmrLeaf]
3527		[pallet_bounties, Bounties]
3528		[pallet_broker, Broker]
3529		[pallet_child_bounties, ChildBounties]
3530		[pallet_collective, Council]
3531		[pallet_conviction_voting, ConvictionVoting]
3532		[pallet_contracts, Contracts]
3533		[pallet_revive, Revive]
3534		[pallet_core_fellowship, CoreFellowship]
3535		[pallet_example_tasks, TasksExample]
3536		[pallet_democracy, Democracy]
3537		[pallet_asset_conversion, AssetConversion]
3538		[pallet_asset_rewards, AssetRewards]
3539		[pallet_asset_conversion_tx_payment, AssetConversionTxPayment]
3540		[pallet_transaction_payment, TransactionPayment]
3541		[pallet_election_provider_multi_phase, ElectionProviderMultiPhase]
3542		[pallet_election_provider_support_benchmarking, EPSBench::<Runtime>]
3543		[pallet_elections_phragmen, Elections]
3544		[pallet_fast_unstake, FastUnstake]
3545		[pallet_nis, Nis]
3546		[pallet_parameters, Parameters]
3547		[pallet_grandpa, Grandpa]
3548		[pallet_hrmp_para, HrmpPara]
3549		[pallet_hrmp_relay, HrmpRelay]
3550		[pallet_identity, Identity]
3551		[pallet_im_online, ImOnline]
3552		[pallet_indices, Indices]
3553		[pallet_lottery, Lottery]
3554		[pallet_membership, TechnicalMembership]
3555		[pallet_message_queue, MessageQueue]
3556		[pallet_migrations, MultiBlockMigrations]
3557		[pallet_mmr, Mmr]
3558		[pallet_multi_asset_bounties, MultiAssetBounties]
3559		[pallet_assets_precompiles, AssetsPrecompiles]
3560		[pallet_vesting_precompiles, VestingPrecompiles]
3561		[pallet_multisig, Multisig]
3562		[pallet_offences, OffencesBench::<Runtime>]
3563		[pallet_on_demand_para, OnDemand]
3564		[pallet_oracle, Oracle]
3565		[pallet_preimage, Preimage]
3566		[pallet_proxy, Proxy]
3567		[pallet_ranked_collective, RankedCollective]
3568		[pallet_referenda, Referenda]
3569		[pallet_recovery, Recovery]
3570		[pallet_registrar_para, RegistrarPara]
3571		[pallet_registrar_relay, RegistrarRelay]
3572		[pallet_remark, Remark]
3573		[pallet_salary, Salary]
3574		[pallet_scheduler, Scheduler]
3575		[pallet_glutton, Glutton]
3576		[pallet_session, SessionBench::<Runtime>]
3577		[pallet_society, Society]
3578		[pallet_dap, Dap]
3579		[pallet_staking, Staking]
3580		[pallet_state_trie_migration, StateTrieMigration]
3581		[pallet_sudo, Sudo]
3582		[frame_system, SystemBench::<Runtime>]
3583		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
3584		[pallet_timestamp, Timestamp]
3585		[pallet_tips, Tips]
3586		[pallet_transaction_storage, TransactionStorage]
3587		[pallet_treasury, Treasury]
3588		[pallet_asset_rate, AssetRate]
3589		[pallet_uniques, Uniques]
3590		[pallet_nfts, Nfts]
3591		[pallet_nft_fractionalization, NftFractionalization]
3592		[pallet_utility, Utility]
3593		[pallet_vesting, Vesting]
3594		[pallet_whitelist, Whitelist]
3595		[pallet_tx_pause, TxPause]
3596		[pallet_safe_mode, SafeMode]
3597		[pallet_example_mbm, PalletExampleMbms]
3598		[pallet_asset_conversion_ops, AssetConversionMigration]
3599		[pallet_verify_signature, VerifySignature]
3600		[pallet_meta_tx, MetaTx]
3601		[pallet_psm, Psm]
3602	);
3603}
3604
3605pallet_revive::impl_runtime_apis_plus_revive_traits!(
3606	Runtime,
3607	Revive,
3608	Executive,
3609	EthExtraImpl,
3610
3611	impl sp_api::Core<Block> for Runtime {
3612		fn version() -> RuntimeVersion {
3613			VERSION
3614		}
3615
3616		fn execute_block(block: <Block as BlockT>::LazyBlock) {
3617			Executive::execute_block(block);
3618		}
3619
3620		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
3621			Executive::initialize_block(header)
3622		}
3623	}
3624
3625	impl sp_api::Metadata<Block> for Runtime {
3626		fn metadata() -> OpaqueMetadata {
3627			OpaqueMetadata::new(Runtime::metadata().into())
3628		}
3629
3630		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
3631			Runtime::metadata_at_version(version)
3632		}
3633
3634		fn metadata_versions() -> alloc::vec::Vec<u32> {
3635			Runtime::metadata_versions()
3636		}
3637	}
3638
3639	impl frame_support::view_functions::runtime_api::RuntimeViewFunction<Block> for Runtime {
3640		fn execute_view_function(id: frame_support::view_functions::ViewFunctionId, input: Vec<u8>) -> Result<Vec<u8>, frame_support::view_functions::ViewFunctionDispatchError> {
3641			Runtime::execute_view_function(id, input)
3642		}
3643	}
3644
3645	impl sp_block_builder::BlockBuilder<Block> for Runtime {
3646		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
3647			Executive::apply_extrinsic(extrinsic)
3648		}
3649
3650		fn finalize_block() -> <Block as BlockT>::Header {
3651			Executive::finalize_block()
3652		}
3653
3654		fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
3655			data.create_extrinsics()
3656		}
3657
3658		fn check_inherents(block: <Block as BlockT>::LazyBlock, data: InherentData) -> CheckInherentsResult {
3659			data.check_extrinsics(&block)
3660		}
3661	}
3662
3663	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
3664		fn validate_transaction(
3665			source: TransactionSource,
3666			tx: <Block as BlockT>::Extrinsic,
3667			block_hash: <Block as BlockT>::Hash,
3668		) -> TransactionValidity {
3669			Executive::validate_transaction(source, tx, block_hash)
3670		}
3671	}
3672
3673	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
3674		fn offchain_worker(header: &<Block as BlockT>::Header) {
3675			Executive::offchain_worker(header)
3676		}
3677	}
3678
3679	impl sp_consensus_grandpa::GrandpaApi<Block> for Runtime {
3680		fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
3681			Grandpa::grandpa_authorities()
3682		}
3683
3684		fn current_set_id() -> sp_consensus_grandpa::SetId {
3685			pallet_grandpa::CurrentSetId::<Runtime>::get()
3686		}
3687
3688		fn submit_report_equivocation_unsigned_extrinsic(
3689			equivocation_proof: sp_consensus_grandpa::EquivocationProof<
3690				<Block as BlockT>::Hash,
3691				NumberFor<Block>,
3692			>,
3693			key_owner_proof: sp_consensus_grandpa::OpaqueKeyOwnershipProof,
3694		) -> Option<()> {
3695			let key_owner_proof = key_owner_proof.decode()?;
3696
3697			Grandpa::submit_unsigned_equivocation_report(
3698				equivocation_proof,
3699				key_owner_proof,
3700			)
3701		}
3702
3703		fn generate_key_ownership_proof(
3704			_set_id: sp_consensus_grandpa::SetId,
3705			authority_id: GrandpaId,
3706		) -> Option<sp_consensus_grandpa::OpaqueKeyOwnershipProof> {
3707			use codec::Encode;
3708
3709			Historical::prove((sp_consensus_grandpa::KEY_TYPE, authority_id))
3710				.map(|p| p.encode())
3711				.map(sp_consensus_grandpa::OpaqueKeyOwnershipProof::new)
3712		}
3713	}
3714
3715	impl pallet_nomination_pools_runtime_api::NominationPoolsApi<Block, AccountId, Balance> for Runtime {
3716		fn pending_rewards(who: AccountId) -> Balance {
3717			NominationPools::api_pending_rewards(who).unwrap_or_default()
3718		}
3719
3720		fn points_to_balance(pool_id: PoolId, points: Balance) -> Balance {
3721			NominationPools::api_points_to_balance(pool_id, points)
3722		}
3723
3724		fn balance_to_points(pool_id: PoolId, new_funds: Balance) -> Balance {
3725			NominationPools::api_balance_to_points(pool_id, new_funds)
3726		}
3727
3728		fn pool_pending_slash(pool_id: PoolId) -> Balance {
3729			NominationPools::api_pool_pending_slash(pool_id)
3730		}
3731
3732		fn member_pending_slash(member: AccountId) -> Balance {
3733			NominationPools::api_member_pending_slash(member)
3734		}
3735
3736		fn pool_needs_delegate_migration(pool_id: PoolId) -> bool {
3737			NominationPools::api_pool_needs_delegate_migration(pool_id)
3738		}
3739
3740		fn member_needs_delegate_migration(member: AccountId) -> bool {
3741			NominationPools::api_member_needs_delegate_migration(member)
3742		}
3743
3744		fn member_total_balance(member: AccountId) -> Balance {
3745			NominationPools::api_member_total_balance(member)
3746		}
3747
3748		fn pool_balance(pool_id: PoolId) -> Balance {
3749			NominationPools::api_pool_balance(pool_id)
3750		}
3751
3752		fn pool_accounts(pool_id: PoolId) -> (AccountId, AccountId) {
3753			NominationPools::api_pool_accounts(pool_id)
3754		}
3755	}
3756
3757	impl pallet_staking_runtime_api::StakingApi<Block, Balance, AccountId> for Runtime {
3758		fn nominations_quota(balance: Balance) -> u32 {
3759			Staking::api_nominations_quota(balance)
3760		}
3761
3762		fn eras_stakers_page_count(era: sp_staking::EraIndex, account: AccountId) -> sp_staking::Page {
3763			Staking::api_eras_stakers_page_count(era, account)
3764		}
3765
3766		fn pending_rewards(era: sp_staking::EraIndex, account: AccountId) -> bool {
3767			Staking::api_pending_rewards(era, account)
3768		}
3769	}
3770
3771	impl sp_consensus_babe::BabeApi<Block> for Runtime {
3772		fn configuration() -> sp_consensus_babe::BabeConfiguration {
3773			let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG);
3774			sp_consensus_babe::BabeConfiguration {
3775				slot_duration: Babe::slot_duration(),
3776				epoch_length: EpochDuration::get(),
3777				c: epoch_config.c,
3778				authorities: Babe::authorities().to_vec(),
3779				randomness: Babe::randomness(),
3780				allowed_slots: epoch_config.allowed_slots,
3781			}
3782		}
3783
3784		fn current_epoch_start() -> sp_consensus_babe::Slot {
3785			Babe::current_epoch_start()
3786		}
3787
3788		fn current_epoch() -> sp_consensus_babe::Epoch {
3789			Babe::current_epoch()
3790		}
3791
3792		fn next_epoch() -> sp_consensus_babe::Epoch {
3793			Babe::next_epoch()
3794		}
3795
3796		fn generate_key_ownership_proof(
3797			_slot: sp_consensus_babe::Slot,
3798			authority_id: sp_consensus_babe::AuthorityId,
3799		) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
3800			use codec::Encode;
3801
3802			Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
3803				.map(|p| p.encode())
3804				.map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
3805		}
3806
3807		fn submit_report_equivocation_unsigned_extrinsic(
3808			equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
3809			key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
3810		) -> Option<()> {
3811			let key_owner_proof = key_owner_proof.decode()?;
3812
3813			Babe::submit_unsigned_equivocation_report(
3814				equivocation_proof,
3815				key_owner_proof,
3816			)
3817		}
3818	}
3819
3820	impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
3821		fn authorities() -> Vec<AuthorityDiscoveryId> {
3822			AuthorityDiscovery::authorities()
3823		}
3824	}
3825
3826	impl polkadot_sdk::pallet_oracle_runtime_api::OracleApi<Block, u32, u32, u128> for Runtime {
3827		fn get_value(_provider_id: u32, key: u32) -> Option<u128> {
3828			// ProviderId is unused as we only have 1 provider
3829			pallet_oracle::Pallet::<Runtime>::get(&key).map(|v| v.value)
3830		}
3831
3832		fn get_all_values(_provider_id: u32) -> Vec<(u32, Option<u128>)> {
3833			use pallet_oracle::DataProviderExtended;
3834			pallet_oracle::Pallet::<Runtime>::get_all_values()
3835				.map(|(k, v)| (k, v.map(|tv| tv.value)))
3836				.collect()
3837		}
3838	}
3839
3840	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
3841		fn account_nonce(account: AccountId) -> Nonce {
3842			System::account_nonce(account)
3843		}
3844	}
3845
3846	impl assets_api::AssetsApi<
3847		Block,
3848		AccountId,
3849		Balance,
3850		u32,
3851	> for Runtime
3852	{
3853		fn account_balances(account: AccountId) -> Vec<(u32, Balance)> {
3854			Assets::account_balances(account)
3855		}
3856	}
3857
3858	impl pallet_contracts::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash, EventRecord> for Runtime
3859	{
3860		fn call(
3861			origin: AccountId,
3862			dest: AccountId,
3863			value: Balance,
3864			gas_limit: Option<Weight>,
3865			storage_deposit_limit: Option<Balance>,
3866			input_data: Vec<u8>,
3867		) -> pallet_contracts::ContractExecResult<Balance, EventRecord> {
3868			let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block);
3869			Contracts::bare_call(
3870				origin,
3871				dest,
3872				value,
3873				gas_limit,
3874				storage_deposit_limit,
3875				input_data,
3876				pallet_contracts::DebugInfo::UnsafeDebug,
3877				pallet_contracts::CollectEvents::UnsafeCollect,
3878				pallet_contracts::Determinism::Enforced,
3879			)
3880		}
3881
3882		fn instantiate(
3883			origin: AccountId,
3884			value: Balance,
3885			gas_limit: Option<Weight>,
3886			storage_deposit_limit: Option<Balance>,
3887			code: pallet_contracts::Code<Hash>,
3888			data: Vec<u8>,
3889			salt: Vec<u8>,
3890		) -> pallet_contracts::ContractInstantiateResult<AccountId, Balance, EventRecord>
3891		{
3892			let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block);
3893			Contracts::bare_instantiate(
3894				origin,
3895				value,
3896				gas_limit,
3897				storage_deposit_limit,
3898				code,
3899				data,
3900				salt,
3901				pallet_contracts::DebugInfo::UnsafeDebug,
3902				pallet_contracts::CollectEvents::UnsafeCollect,
3903			)
3904		}
3905
3906		fn upload_code(
3907			origin: AccountId,
3908			code: Vec<u8>,
3909			storage_deposit_limit: Option<Balance>,
3910			determinism: pallet_contracts::Determinism,
3911		) -> pallet_contracts::CodeUploadResult<Hash, Balance>
3912		{
3913			Contracts::bare_upload_code(
3914				origin,
3915				code,
3916				storage_deposit_limit,
3917				determinism,
3918			)
3919		}
3920
3921		fn get_storage(
3922			address: AccountId,
3923			key: Vec<u8>,
3924		) -> pallet_contracts::GetStorageResult {
3925			Contracts::get_storage(
3926				address,
3927				key
3928			)
3929		}
3930	}
3931
3932	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
3933		Block,
3934		Balance,
3935	> for Runtime {
3936		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
3937			TransactionPayment::query_info(uxt, len)
3938		}
3939		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
3940			TransactionPayment::query_fee_details(uxt, len)
3941		}
3942		fn query_weight_to_fee(weight: Weight) -> Balance {
3943			TransactionPayment::weight_to_fee(weight)
3944		}
3945		fn query_length_to_fee(length: u32) -> Balance {
3946			TransactionPayment::length_to_fee(length)
3947		}
3948	}
3949
3950	impl pallet_asset_conversion::AssetConversionApi<
3951		Block,
3952		Balance,
3953		NativeOrWithId<u32>
3954	> for Runtime
3955	{
3956		fn quote_price_exact_tokens_for_tokens(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>, amount: Balance, include_fee: bool) -> Option<Balance> {
3957			AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee)
3958		}
3959
3960		fn quote_price_tokens_for_exact_tokens(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>, amount: Balance, include_fee: bool) -> Option<Balance> {
3961			AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee)
3962		}
3963
3964		fn get_reserves(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>) -> Option<(Balance, Balance)> {
3965			AssetConversion::get_reserves(asset1, asset2).ok()
3966		}
3967	}
3968
3969	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
3970		for Runtime
3971	{
3972		fn query_call_info(call: RuntimeCall, len: u32) -> RuntimeDispatchInfo<Balance> {
3973			TransactionPayment::query_call_info(call, len)
3974		}
3975		fn query_call_fee_details(call: RuntimeCall, len: u32) -> FeeDetails<Balance> {
3976			TransactionPayment::query_call_fee_details(call, len)
3977		}
3978		fn query_weight_to_fee(weight: Weight) -> Balance {
3979			TransactionPayment::weight_to_fee(weight)
3980		}
3981		fn query_length_to_fee(length: u32) -> Balance {
3982			TransactionPayment::length_to_fee(length)
3983		}
3984	}
3985
3986	impl pallet_nfts_runtime_api::NftsApi<Block, AccountId, u32, u32> for Runtime {
3987		fn owner(collection: u32, item: u32) -> Option<AccountId> {
3988			<Nfts as Inspect<AccountId>>::owner(&collection, &item)
3989		}
3990
3991		fn collection_owner(collection: u32) -> Option<AccountId> {
3992			<Nfts as Inspect<AccountId>>::collection_owner(&collection)
3993		}
3994
3995		fn attribute(
3996			collection: u32,
3997			item: u32,
3998			key: Vec<u8>,
3999		) -> Option<Vec<u8>> {
4000			<Nfts as Inspect<AccountId>>::attribute(&collection, &item, &key)
4001		}
4002
4003		fn custom_attribute(
4004			account: AccountId,
4005			collection: u32,
4006			item: u32,
4007			key: Vec<u8>,
4008		) -> Option<Vec<u8>> {
4009			<Nfts as Inspect<AccountId>>::custom_attribute(
4010				&account,
4011				&collection,
4012				&item,
4013				&key,
4014			)
4015		}
4016
4017		fn system_attribute(
4018			collection: u32,
4019			item: Option<u32>,
4020			key: Vec<u8>,
4021		) -> Option<Vec<u8>> {
4022			<Nfts as Inspect<AccountId>>::system_attribute(&collection, item.as_ref(), &key)
4023		}
4024
4025		fn collection_attribute(collection: u32, key: Vec<u8>) -> Option<Vec<u8>> {
4026			<Nfts as Inspect<AccountId>>::collection_attribute(&collection, &key)
4027		}
4028	}
4029
4030	#[api_version(6)]
4031	impl sp_consensus_beefy::BeefyApi<Block, BeefyId> for Runtime {
4032		fn beefy_genesis() -> Option<BlockNumber> {
4033			pallet_beefy::GenesisBlock::<Runtime>::get()
4034		}
4035
4036		fn validator_set() -> Option<sp_consensus_beefy::ValidatorSet<BeefyId>> {
4037			Beefy::validator_set()
4038		}
4039
4040		fn submit_report_double_voting_unsigned_extrinsic(
4041			equivocation_proof: sp_consensus_beefy::DoubleVotingProof<
4042				BlockNumber,
4043				BeefyId,
4044				BeefySignature,
4045			>,
4046			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
4047		) -> Option<()> {
4048			let key_owner_proof = key_owner_proof.decode()?;
4049
4050			Beefy::submit_unsigned_double_voting_report(
4051				equivocation_proof,
4052				key_owner_proof,
4053			)
4054		}
4055
4056		fn submit_report_fork_voting_unsigned_extrinsic(
4057			equivocation_proof:
4058				sp_consensus_beefy::ForkVotingProof<
4059					<Block as BlockT>::Header,
4060					BeefyId,
4061					sp_runtime::OpaqueValue
4062				>,
4063			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
4064		) -> Option<()> {
4065			Beefy::submit_unsigned_fork_voting_report(
4066				equivocation_proof.try_into()?,
4067				key_owner_proof.decode()?,
4068			)
4069		}
4070
4071		fn submit_report_future_block_voting_unsigned_extrinsic(
4072			equivocation_proof: sp_consensus_beefy::FutureBlockVotingProof<BlockNumber, BeefyId>,
4073			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
4074		) -> Option<()> {
4075			Beefy::submit_unsigned_future_block_voting_report(
4076				equivocation_proof,
4077				key_owner_proof.decode()?,
4078			)
4079		}
4080
4081		fn generate_key_ownership_proof(
4082			_set_id: sp_consensus_beefy::ValidatorSetId,
4083			authority_id: BeefyId,
4084		) -> Option<sp_consensus_beefy::OpaqueKeyOwnershipProof> {
4085			Historical::prove((sp_consensus_beefy::KEY_TYPE, authority_id))
4086				.map(|p| p.encode())
4087				.map(sp_consensus_beefy::OpaqueKeyOwnershipProof::new)
4088		}
4089	}
4090
4091	#[api_version(3)]
4092	impl pallet_mmr::primitives::MmrApi<
4093		Block,
4094		mmr::Hash,
4095		BlockNumber,
4096	> for Runtime {
4097		fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
4098			Ok(pallet_mmr::RootHash::<Runtime>::get())
4099		}
4100
4101		fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
4102			Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
4103		}
4104
4105		fn generate_proof(
4106			block_numbers: Vec<BlockNumber>,
4107			best_known_block_number: Option<BlockNumber>,
4108		) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
4109			Mmr::generate_proof(block_numbers, best_known_block_number).map(
4110				|(leaves, proof)| {
4111					(
4112						leaves
4113							.into_iter()
4114							.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
4115							.collect(),
4116						proof,
4117					)
4118				},
4119			)
4120		}
4121
4122		fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
4123			-> Result<(), mmr::Error>
4124		{
4125			let leaves = leaves.into_iter().map(|leaf|
4126				leaf.into_opaque_leaf()
4127				.try_decode()
4128				.ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
4129			Mmr::verify_leaves(leaves, proof)
4130		}
4131
4132		fn generate_ancestry_proof(
4133			prev_block_number: BlockNumber,
4134			best_known_block_number: Option<BlockNumber>,
4135		) -> Result<mmr::AncestryProof<mmr::Hash>, mmr::Error> {
4136			Mmr::generate_ancestry_proof(prev_block_number, best_known_block_number)
4137		}
4138
4139		fn verify_proof_stateless(
4140			root: mmr::Hash,
4141			leaves: Vec<mmr::EncodableOpaqueLeaf>,
4142			proof: mmr::LeafProof<mmr::Hash>
4143		) -> Result<(), mmr::Error> {
4144			let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
4145			pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
4146		}
4147	}
4148
4149	impl sp_mixnet::runtime_api::MixnetApi<Block> for Runtime {
4150		fn session_status() -> sp_mixnet::types::SessionStatus {
4151			Mixnet::session_status()
4152		}
4153
4154		fn prev_mixnodes() -> Result<Vec<sp_mixnet::types::Mixnode>, sp_mixnet::types::MixnodesErr> {
4155			Mixnet::prev_mixnodes()
4156		}
4157
4158		fn current_mixnodes() -> Result<Vec<sp_mixnet::types::Mixnode>, sp_mixnet::types::MixnodesErr> {
4159			Mixnet::current_mixnodes()
4160		}
4161
4162		fn maybe_register(session_index: sp_mixnet::types::SessionIndex, mixnode: sp_mixnet::types::Mixnode) -> bool {
4163			Mixnet::maybe_register(session_index, mixnode)
4164		}
4165	}
4166
4167	impl sp_session::SessionKeys<Block> for Runtime {
4168		fn generate_session_keys(owner: Vec<u8>, seed: Option<Vec<u8>>) -> sp_session::OpaqueGeneratedSessionKeys {
4169			SessionKeys::generate(&owner, seed).into()
4170		}
4171
4172		fn decode_session_keys(
4173			encoded: Vec<u8>,
4174		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
4175			SessionKeys::decode_into_raw_public_keys(&encoded)
4176		}
4177	}
4178
4179	impl pallet_asset_rewards::AssetRewards<Block, Balance> for Runtime {
4180		fn pool_creation_cost() -> Balance {
4181			StakePoolCreationDeposit::get()
4182		}
4183	}
4184
4185	impl sp_transaction_storage_proof::runtime_api::TransactionStorageApi<Block> for Runtime {
4186		fn retention_period() -> NumberFor<Block> {
4187			TransactionStorage::retention_period()
4188		}
4189
4190		fn indexed_transactions(
4191			block: NumberFor<Block>,
4192		) -> Vec<sp_transaction_storage_proof::IndexedTransactionInfo> {
4193			TransactionStorage::indexed_transactions(block)
4194		}
4195	}
4196
4197	#[cfg(feature = "try-runtime")]
4198	impl frame_try_runtime::TryRuntime<Block> for Runtime {
4199		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
4200			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
4201			// have a backtrace here. If any of the pre/post migration checks fail, we shall stop
4202			// right here and right now.
4203			let weight = Executive::try_runtime_upgrade(checks).unwrap();
4204			(weight, RuntimeBlockWeights::get().max_block)
4205		}
4206
4207		fn execute_block(
4208			block: <Block as BlockT>::LazyBlock,
4209			state_root_check: bool,
4210			signature_check: bool,
4211			select: frame_try_runtime::TryStateSelect
4212		) -> Weight {
4213			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
4214			// have a backtrace here.
4215			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
4216		}
4217	}
4218
4219	#[cfg(feature = "runtime-benchmarks")]
4220	impl frame_benchmarking::Benchmark<Block> for Runtime {
4221		fn benchmark_metadata(extra: bool) -> (
4222			Vec<frame_benchmarking::BenchmarkList>,
4223			Vec<frame_support::traits::StorageInfo>,
4224		) {
4225			use frame_benchmarking::{baseline, BenchmarkList};
4226			use frame_support::traits::StorageInfoTrait;
4227
4228			// Trying to add benchmarks directly to the Session Pallet caused cyclic dependency
4229			// issues. To get around that, we separated the Session benchmarks into its own crate,
4230			// which is why we need these two lines below.
4231			use pallet_session_benchmarking::Pallet as SessionBench;
4232			use pallet_offences_benchmarking::Pallet as OffencesBench;
4233			use pallet_election_provider_support_benchmarking::Pallet as EPSBench;
4234			use frame_system_benchmarking::Pallet as SystemBench;
4235			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
4236			use baseline::Pallet as BaselineBench;
4237
4238			let mut list = Vec::<BenchmarkList>::new();
4239			list_benchmarks!(list, extra);
4240
4241			let storage_info = AllPalletsWithSystem::storage_info();
4242
4243			(list, storage_info)
4244		}
4245
4246		#[allow(non_local_definitions)]
4247		fn dispatch_benchmark(
4248			config: frame_benchmarking::BenchmarkConfig
4249		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
4250			use frame_benchmarking::{baseline, BenchmarkBatch};
4251			use sp_storage::TrackedStorageKey;
4252
4253			// Trying to add benchmarks directly to the Session Pallet caused cyclic dependency
4254			// issues. To get around that, we separated the Session benchmarks into its own crate,
4255			// which is why we need these two lines below.
4256			use pallet_session_benchmarking::Pallet as SessionBench;
4257			use pallet_offences_benchmarking::Pallet as OffencesBench;
4258			use pallet_election_provider_support_benchmarking::Pallet as EPSBench;
4259			use frame_system_benchmarking::Pallet as SystemBench;
4260			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
4261			use baseline::Pallet as BaselineBench;
4262
4263			impl pallet_session_benchmarking::Config for Runtime {
4264				fn generate_session_keys_and_proof(owner: Self::AccountId) -> (Self::Keys, Vec<u8>) {
4265					let keys = SessionKeys::generate(&owner.encode(), None);
4266					(keys.keys, keys.proof.encode())
4267				}
4268			}
4269			impl pallet_offences_benchmarking::Config for Runtime {}
4270			impl pallet_election_provider_support_benchmarking::Config for Runtime {}
4271			impl frame_system_benchmarking::Config for Runtime {}
4272			impl pallet_transaction_payment::BenchmarkConfig for Runtime {}
4273			impl baseline::Config for Runtime {}
4274
4275			use frame_support::traits::WhitelistedStorageKeys;
4276			let mut whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
4277
4278			// Treasury Account
4279			// TODO: this is manual for now, someday we might be able to use a
4280			// macro for this particular key
4281			let treasury_key = frame_system::Account::<Runtime>::hashed_key_for(Treasury::account_id());
4282			whitelist.push(treasury_key.to_vec().into());
4283
4284			let mut batches = Vec::<BenchmarkBatch>::new();
4285			let params = (&config, &whitelist);
4286			add_benchmarks!(params, batches);
4287			Ok(batches)
4288		}
4289	}
4290
4291	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
4292		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
4293			build_state::<RuntimeGenesisConfig>(config)
4294		}
4295
4296		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
4297			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
4298		}
4299
4300		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
4301			genesis_config_presets::preset_names()
4302		}
4303	}
4304
4305);
4306
4307#[cfg(test)]
4308mod tests {
4309	use super::*;
4310	use frame_system::offchain::CreateSignedTransaction;
4311
4312	#[test]
4313	fn validate_transaction_submitter_bounds() {
4314		fn is_submit_signed_transaction<T>()
4315		where
4316			T: CreateSignedTransaction<RuntimeCall>,
4317		{
4318		}
4319
4320		is_submit_signed_transaction::<Runtime>();
4321	}
4322
4323	#[test]
4324	fn call_size() {
4325		let size = core::mem::size_of::<RuntimeCall>();
4326		assert!(
4327			size <= CALL_PARAMS_MAX_SIZE,
4328			"size of RuntimeCall {} is more than {CALL_PARAMS_MAX_SIZE} bytes.
4329			 Some calls have too big arguments, use Box to reduce the size of RuntimeCall.
4330			 If the limit is too strong, maybe consider increase the limit.",
4331			size,
4332		);
4333	}
4334}