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