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 const LiquidityWithdrawalFee: Permill = Permill::from_percent(0);
1979	pub const Native: NativeOrWithId<u32> = NativeOrWithId::Native;
1980}
1981
1982pub type NativeAndAssets =
1983	UnionOf<Balances, Assets, NativeFromLeft, NativeOrWithId<u32>, AccountId>;
1984
1985impl pallet_asset_conversion::Config for Runtime {
1986	type RuntimeEvent = RuntimeEvent;
1987	type Balance = u128;
1988	type HigherPrecisionBalance = sp_core::U256;
1989	type AssetKind = NativeOrWithId<u32>;
1990	type Assets = NativeAndAssets;
1991	type PoolId = (Self::AssetKind, Self::AssetKind);
1992	type PoolLocator = Chain<
1993		WithFirstAsset<
1994			Native,
1995			AccountId,
1996			NativeOrWithId<u32>,
1997			AccountIdConverter<AssetConversionPalletId, Self::PoolId>,
1998		>,
1999		Ascending<
2000			AccountId,
2001			NativeOrWithId<u32>,
2002			AccountIdConverter<AssetConversionPalletId, Self::PoolId>,
2003		>,
2004	>;
2005	type PoolAssetId = <Self as pallet_assets::Config<Instance2>>::AssetId;
2006	type PoolAssets = PoolAssets;
2007	type PoolSetupFee = PoolSetupFee;
2008	type PoolSetupFeeAsset = Native;
2009	type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
2010	type PalletId = AssetConversionPalletId;
2011	type LPFee = LpFee;
2012	type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
2013	type WeightInfo = pallet_asset_conversion::weights::SubstrateWeight<Runtime>;
2014	type MaxSwapPathLength = ConstU32<4>;
2015	type MintMinLiquidity = MintMinLiquidity;
2016	#[cfg(feature = "runtime-benchmarks")]
2017	type BenchmarkHelper = ();
2018}
2019
2020pub type NativeAndAssetsFreezer =
2021	UnionOf<Balances, AssetsFreezer, NativeFromLeft, NativeOrWithId<u32>, AccountId>;
2022
2023/// Benchmark Helper
2024#[cfg(feature = "runtime-benchmarks")]
2025pub struct AssetRewardsBenchmarkHelper;
2026
2027#[cfg(feature = "runtime-benchmarks")]
2028impl pallet_asset_rewards::benchmarking::BenchmarkHelper<NativeOrWithId<u32>>
2029	for AssetRewardsBenchmarkHelper
2030{
2031	fn staked_asset() -> NativeOrWithId<u32> {
2032		NativeOrWithId::<u32>::WithId(100)
2033	}
2034	fn reward_asset() -> NativeOrWithId<u32> {
2035		NativeOrWithId::<u32>::WithId(101)
2036	}
2037}
2038
2039parameter_types! {
2040	pub const StakingRewardsPalletId: PalletId = PalletId(*b"py/stkrd");
2041	pub const CreationHoldReason: RuntimeHoldReason =
2042		RuntimeHoldReason::AssetRewards(pallet_asset_rewards::HoldReason::PoolCreation);
2043	// 1 item, 135 bytes into the storage on pool creation.
2044	pub const StakePoolCreationDeposit: Balance = deposit(1, 135);
2045}
2046
2047impl pallet_asset_rewards::Config for Runtime {
2048	type RuntimeEvent = RuntimeEvent;
2049	type RuntimeFreezeReason = RuntimeFreezeReason;
2050	type AssetId = NativeOrWithId<u32>;
2051	type Balance = Balance;
2052	type Assets = NativeAndAssets;
2053	type PalletId = StakingRewardsPalletId;
2054	type CreatePoolOrigin = EnsureSigned<AccountId>;
2055	type WeightInfo = ();
2056	type AssetsFreezer = NativeAndAssetsFreezer;
2057	type Consideration = HoldConsideration<
2058		AccountId,
2059		Balances,
2060		CreationHoldReason,
2061		ConstantStoragePrice<StakePoolCreationDeposit, Balance>,
2062	>;
2063	type BlockNumberProvider = frame_system::Pallet<Runtime>;
2064	#[cfg(feature = "runtime-benchmarks")]
2065	type BenchmarkHelper = AssetRewardsBenchmarkHelper;
2066}
2067
2068impl pallet_asset_conversion_ops::Config for Runtime {
2069	type RuntimeEvent = RuntimeEvent;
2070	type PriorAccountIdConverter = pallet_asset_conversion::AccountIdConverterNoSeed<(
2071		NativeOrWithId<u32>,
2072		NativeOrWithId<u32>,
2073	)>;
2074	type AssetsRefund = <Runtime as pallet_asset_conversion::Config>::Assets;
2075	type PoolAssetsRefund = <Runtime as pallet_asset_conversion::Config>::PoolAssets;
2076	type PoolAssetsTeam = <Runtime as pallet_asset_conversion::Config>::PoolAssets;
2077	type DepositAsset = Balances;
2078	type WeightInfo = pallet_asset_conversion_ops::weights::SubstrateWeight<Runtime>;
2079}
2080
2081parameter_types! {
2082	pub const QueueCount: u32 = 300;
2083	pub const MaxQueueLen: u32 = 1000;
2084	pub const FifoQueueLen: u32 = 500;
2085	pub const NisBasePeriod: BlockNumber = 30 * DAYS;
2086	pub const MinBid: Balance = 100 * DOLLARS;
2087	pub const MinReceipt: Perquintill = Perquintill::from_percent(1);
2088	pub const IntakePeriod: BlockNumber = 10;
2089	pub MaxIntakeWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;
2090	pub const ThawThrottle: (Perquintill, BlockNumber) = (Perquintill::from_percent(25), 5);
2091	pub Target: Perquintill = Perquintill::zero();
2092	pub const NisPalletId: PalletId = PalletId(*b"py/nis  ");
2093}
2094
2095impl pallet_nis::Config for Runtime {
2096	type WeightInfo = pallet_nis::weights::SubstrateWeight<Runtime>;
2097	type RuntimeEvent = RuntimeEvent;
2098	type Currency = Balances;
2099	type CurrencyBalance = Balance;
2100	type FundOrigin = frame_system::EnsureSigned<AccountId>;
2101	type Counterpart = ItemOf<Assets, ConstU32<9u32>, AccountId>;
2102	type CounterpartAmount = WithMaximumOf<ConstU128<21_000_000_000_000_000_000u128>>;
2103	type Deficit = ();
2104	type IgnoredIssuance = ();
2105	type Target = Target;
2106	type PalletId = NisPalletId;
2107	type QueueCount = QueueCount;
2108	type MaxQueueLen = MaxQueueLen;
2109	type FifoQueueLen = FifoQueueLen;
2110	type BasePeriod = NisBasePeriod;
2111	type MinBid = MinBid;
2112	type MinReceipt = MinReceipt;
2113	type IntakePeriod = IntakePeriod;
2114	type MaxIntakeWeight = MaxIntakeWeight;
2115	type ThawThrottle = ThawThrottle;
2116	type RuntimeHoldReason = RuntimeHoldReason;
2117	#[cfg(feature = "runtime-benchmarks")]
2118	type BenchmarkSetup = SetupAsset;
2119}
2120
2121#[cfg(feature = "runtime-benchmarks")]
2122pub struct SetupAsset;
2123#[cfg(feature = "runtime-benchmarks")]
2124impl pallet_nis::BenchmarkSetup for SetupAsset {
2125	fn create_counterpart_asset() {
2126		let owner = AccountId::from([0u8; 32]);
2127		// this may or may not fail depending on if the chain spec or runtime genesis is used.
2128		let _ = Assets::force_create(
2129			RuntimeOrigin::root(),
2130			9u32.into(),
2131			sp_runtime::MultiAddress::Id(owner),
2132			true,
2133			1,
2134		);
2135	}
2136}
2137
2138parameter_types! {
2139	pub const CollectionDeposit: Balance = 100 * DOLLARS;
2140	pub const ItemDeposit: Balance = 1 * DOLLARS;
2141	pub const ApprovalsLimit: u32 = 20;
2142	pub const ItemAttributesApprovalsLimit: u32 = 20;
2143	pub const MaxTips: u32 = 10;
2144	pub const MaxDeadlineDuration: BlockNumber = 12 * 30 * DAYS;
2145}
2146
2147impl pallet_uniques::Config for Runtime {
2148	type RuntimeEvent = RuntimeEvent;
2149	type CollectionId = u32;
2150	type ItemId = u32;
2151	type Currency = Balances;
2152	type ForceOrigin = frame_system::EnsureRoot<AccountId>;
2153	type CollectionDeposit = CollectionDeposit;
2154	type ItemDeposit = ItemDeposit;
2155	type MetadataDepositBase = MetadataDepositBase;
2156	type AttributeDepositBase = MetadataDepositBase;
2157	type DepositPerByte = MetadataDepositPerByte;
2158	type StringLimit = ConstU32<128>;
2159	type KeyLimit = ConstU32<32>;
2160	type ValueLimit = ConstU32<64>;
2161	type WeightInfo = pallet_uniques::weights::SubstrateWeight<Runtime>;
2162	#[cfg(feature = "runtime-benchmarks")]
2163	type Helper = ();
2164	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
2165	type Locker = ();
2166}
2167
2168parameter_types! {
2169	pub const Budget: Balance = 10_000 * DOLLARS;
2170	pub TreasuryAccount: AccountId = Treasury::account_id();
2171}
2172
2173pub struct SalaryForRank;
2174impl GetSalary<u16, AccountId, Balance> for SalaryForRank {
2175	fn get_salary(a: u16, _: &AccountId) -> Balance {
2176		Balance::from(a) * 1000 * DOLLARS
2177	}
2178}
2179
2180impl pallet_salary::Config for Runtime {
2181	type WeightInfo = ();
2182	type RuntimeEvent = RuntimeEvent;
2183	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
2184	type Members = RankedCollective;
2185	type Salary = SalaryForRank;
2186	type RegistrationPeriod = ConstU32<200>;
2187	type PayoutPeriod = ConstU32<200>;
2188	type Budget = Budget;
2189}
2190
2191impl pallet_core_fellowship::Config for Runtime {
2192	type WeightInfo = ();
2193	type RuntimeEvent = RuntimeEvent;
2194	type Members = RankedCollective;
2195	type Balance = Balance;
2196	type ParamsOrigin = frame_system::EnsureRoot<AccountId>;
2197	type InductOrigin = pallet_core_fellowship::EnsureInducted<Runtime, (), 1>;
2198	type ApproveOrigin = EnsureRootWithSuccess<AccountId, ConstU16<9>>;
2199	type PromoteOrigin = EnsureRootWithSuccess<AccountId, ConstU16<9>>;
2200	type FastPromoteOrigin = Self::PromoteOrigin;
2201	type EvidenceSize = ConstU32<16_384>;
2202	type MaxRank = ConstU16<9>;
2203}
2204
2205parameter_types! {
2206	pub const NftFractionalizationPalletId: PalletId = PalletId(*b"fraction");
2207	pub NewAssetSymbol: BoundedVec<u8, StringLimit> = (*b"FRAC").to_vec().try_into().unwrap();
2208	pub NewAssetName: BoundedVec<u8, StringLimit> = (*b"Frac").to_vec().try_into().unwrap();
2209}
2210
2211impl pallet_nft_fractionalization::Config for Runtime {
2212	type RuntimeEvent = RuntimeEvent;
2213	type Deposit = AssetDeposit;
2214	type Currency = Balances;
2215	type NewAssetSymbol = NewAssetSymbol;
2216	type NewAssetName = NewAssetName;
2217	type StringLimit = StringLimit;
2218	type NftCollectionId = <Self as pallet_nfts::Config>::CollectionId;
2219	type NftId = <Self as pallet_nfts::Config>::ItemId;
2220	type AssetBalance = <Self as pallet_balances::Config>::Balance;
2221	type AssetId = <Self as pallet_assets::Config<Instance1>>::AssetId;
2222	type Assets = Assets;
2223	type Nfts = Nfts;
2224	type PalletId = NftFractionalizationPalletId;
2225	type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight<Runtime>;
2226	type RuntimeHoldReason = RuntimeHoldReason;
2227	#[cfg(feature = "runtime-benchmarks")]
2228	type BenchmarkHelper = ();
2229}
2230
2231parameter_types! {
2232	pub Features: PalletFeatures = PalletFeatures::all_enabled();
2233	pub const MaxAttributesPerCall: u32 = 10;
2234}
2235
2236impl pallet_nfts::Config for Runtime {
2237	type RuntimeEvent = RuntimeEvent;
2238	type CollectionId = u32;
2239	type ItemId = u32;
2240	type Currency = Balances;
2241	type ForceOrigin = frame_system::EnsureRoot<AccountId>;
2242	type CollectionDeposit = CollectionDeposit;
2243	type ItemDeposit = ItemDeposit;
2244	type MetadataDepositBase = MetadataDepositBase;
2245	type AttributeDepositBase = MetadataDepositBase;
2246	type DepositPerByte = MetadataDepositPerByte;
2247	type StringLimit = ConstU32<256>;
2248	type KeyLimit = ConstU32<64>;
2249	type ValueLimit = ConstU32<256>;
2250	type ApprovalsLimit = ApprovalsLimit;
2251	type ItemAttributesApprovalsLimit = ItemAttributesApprovalsLimit;
2252	type MaxTips = MaxTips;
2253	type MaxDeadlineDuration = MaxDeadlineDuration;
2254	type MaxAttributesPerCall = MaxAttributesPerCall;
2255	type Features = Features;
2256	type OffchainSignature = Signature;
2257	type OffchainPublic = <Signature as traits::Verify>::Signer;
2258	type WeightInfo = pallet_nfts::weights::SubstrateWeight<Runtime>;
2259	#[cfg(feature = "runtime-benchmarks")]
2260	type Helper = ();
2261	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
2262	type Locker = ();
2263	type BlockNumberProvider = frame_system::Pallet<Runtime>;
2264}
2265
2266impl pallet_transaction_storage::Config for Runtime {
2267	type RuntimeEvent = RuntimeEvent;
2268	type Currency = Balances;
2269	type RuntimeHoldReason = RuntimeHoldReason;
2270	type RuntimeCall = RuntimeCall;
2271	type FeeDestination = ();
2272	type WeightInfo = pallet_transaction_storage::weights::SubstrateWeight<Runtime>;
2273	type MaxBlockTransactions =
2274		ConstU32<{ pallet_transaction_storage::DEFAULT_MAX_BLOCK_TRANSACTIONS }>;
2275	type MaxTransactionSize =
2276		ConstU32<{ pallet_transaction_storage::DEFAULT_MAX_TRANSACTION_SIZE }>;
2277}
2278
2279impl pallet_verify_signature::Config for Runtime {
2280	type Signature = MultiSignature;
2281	type AccountIdentifier = MultiSigner;
2282	type WeightInfo = pallet_verify_signature::weights::SubstrateWeight<Runtime>;
2283	#[cfg(feature = "runtime-benchmarks")]
2284	type BenchmarkHelper = ();
2285}
2286
2287impl pallet_whitelist::Config for Runtime {
2288	type RuntimeEvent = RuntimeEvent;
2289	type RuntimeCall = RuntimeCall;
2290	type WhitelistOrigin = EnsureRoot<AccountId>;
2291	type DispatchWhitelistedOrigin = EnsureRoot<AccountId>;
2292	type Preimages = Preimage;
2293	type WeightInfo = pallet_whitelist::weights::SubstrateWeight<Runtime>;
2294}
2295
2296parameter_types! {
2297	pub const MigrationSignedDepositPerItem: Balance = 1 * CENTS;
2298	pub const MigrationSignedDepositBase: Balance = 20 * DOLLARS;
2299	pub const MigrationMaxKeyLen: u32 = 512;
2300}
2301
2302impl pallet_state_trie_migration::Config for Runtime {
2303	type RuntimeEvent = RuntimeEvent;
2304	type ControlOrigin = EnsureRoot<AccountId>;
2305	type Currency = Balances;
2306	type RuntimeHoldReason = RuntimeHoldReason;
2307	type MaxKeyLen = MigrationMaxKeyLen;
2308	type SignedDepositPerItem = MigrationSignedDepositPerItem;
2309	type SignedDepositBase = MigrationSignedDepositBase;
2310	// Warning: this is not advised, as it might allow the chain to be temporarily DOS-ed.
2311	// Preferably, if the chain's governance/maintenance team is planning on using a specific
2312	// account for the migration, put it here to make sure only that account can trigger the signed
2313	// migrations.
2314	type SignedFilter = EnsureSigned<Self::AccountId>;
2315	type WeightInfo = ();
2316}
2317
2318const ALLIANCE_MOTION_DURATION_IN_BLOCKS: BlockNumber = 5 * DAYS;
2319
2320parameter_types! {
2321	pub const AllianceMotionDuration: BlockNumber = ALLIANCE_MOTION_DURATION_IN_BLOCKS;
2322	pub const AllianceMaxProposals: u32 = 100;
2323	pub const AllianceMaxMembers: u32 = 100;
2324}
2325
2326type AllianceCollective = pallet_collective::Instance3;
2327impl pallet_collective::Config<AllianceCollective> for Runtime {
2328	type RuntimeOrigin = RuntimeOrigin;
2329	type Proposal = RuntimeCall;
2330	type RuntimeEvent = RuntimeEvent;
2331	type MotionDuration = AllianceMotionDuration;
2332	type MaxProposals = AllianceMaxProposals;
2333	type MaxMembers = AllianceMaxMembers;
2334	type DefaultVote = pallet_collective::PrimeDefaultVote;
2335	type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
2336	type SetMembersOrigin = EnsureRoot<Self::AccountId>;
2337	type MaxProposalWeight = MaxCollectivesProposalWeight;
2338	type DisapproveOrigin = EnsureRoot<Self::AccountId>;
2339	type KillOrigin = EnsureRoot<Self::AccountId>;
2340	type Consideration = ();
2341}
2342
2343parameter_types! {
2344	pub const MaxFellows: u32 = AllianceMaxMembers::get();
2345	pub const MaxAllies: u32 = 100;
2346	pub const AllyDeposit: Balance = 10 * DOLLARS;
2347	pub const RetirementPeriod: BlockNumber = ALLIANCE_MOTION_DURATION_IN_BLOCKS + (1 * DAYS);
2348}
2349
2350impl pallet_alliance::Config for Runtime {
2351	type RuntimeEvent = RuntimeEvent;
2352	type Proposal = RuntimeCall;
2353	type AdminOrigin = EitherOfDiverse<
2354		EnsureRoot<AccountId>,
2355		pallet_collective::EnsureProportionMoreThan<AccountId, AllianceCollective, 2, 3>,
2356	>;
2357	type MembershipManager = EitherOfDiverse<
2358		EnsureRoot<AccountId>,
2359		pallet_collective::EnsureProportionMoreThan<AccountId, AllianceCollective, 2, 3>,
2360	>;
2361	type AnnouncementOrigin = EitherOfDiverse<
2362		EnsureRoot<AccountId>,
2363		pallet_collective::EnsureProportionMoreThan<AccountId, AllianceCollective, 2, 3>,
2364	>;
2365	type Currency = Balances;
2366	type Slashed = Treasury;
2367	type InitializeMembers = AllianceMotion;
2368	type MembershipChanged = AllianceMotion;
2369	#[cfg(not(feature = "runtime-benchmarks"))]
2370	type IdentityVerifier = AllianceIdentityVerifier;
2371	#[cfg(feature = "runtime-benchmarks")]
2372	type IdentityVerifier = ();
2373	type ProposalProvider = AllianceProposalProvider;
2374	type MaxProposals = AllianceMaxProposals;
2375	type MaxFellows = MaxFellows;
2376	type MaxAllies = MaxAllies;
2377	type MaxUnscrupulousItems = ConstU32<100>;
2378	type MaxWebsiteUrlLength = ConstU32<255>;
2379	type MaxAnnouncementsCount = ConstU32<100>;
2380	type MaxMembersCount = AllianceMaxMembers;
2381	type AllyDeposit = AllyDeposit;
2382	type WeightInfo = pallet_alliance::weights::SubstrateWeight<Runtime>;
2383	type RetirementPeriod = RetirementPeriod;
2384}
2385
2386impl frame_benchmarking_pallet_pov::Config for Runtime {
2387	type RuntimeEvent = RuntimeEvent;
2388}
2389
2390parameter_types! {
2391	pub StatementCost: Balance = 1 * DOLLARS;
2392	pub StatementByteCost: Balance = 100 * MILLICENTS;
2393	pub const MinAllowedStatements: u32 = 4;
2394	pub const MaxAllowedStatements: u32 = 10;
2395	pub const MinAllowedBytes: u32 = 1024;
2396	pub const MaxAllowedBytes: u32 = 4096;
2397}
2398
2399impl pallet_statement::Config for Runtime {
2400	type RuntimeEvent = RuntimeEvent;
2401	type Currency = Balances;
2402	type StatementCost = StatementCost;
2403	type ByteCost = StatementByteCost;
2404	type MinAllowedStatements = MinAllowedStatements;
2405	type MaxAllowedStatements = MaxAllowedStatements;
2406	type MinAllowedBytes = MinAllowedBytes;
2407	type MaxAllowedBytes = MaxAllowedBytes;
2408}
2409
2410parameter_types! {
2411	pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
2412}
2413
2414impl pallet_migrations::Config for Runtime {
2415	type RuntimeEvent = RuntimeEvent;
2416	#[cfg(not(feature = "runtime-benchmarks"))]
2417	type Migrations = ();
2418	// Benchmarks need mocked migrations to guarantee that they succeed.
2419	#[cfg(feature = "runtime-benchmarks")]
2420	type Migrations = pallet_migrations::mock_helpers::MockedMigrations;
2421	type CursorMaxLen = ConstU32<65_536>;
2422	type IdentifierMaxLen = ConstU32<256>;
2423	type MigrationStatusHandler = ();
2424	type FailedMigrationHandler = frame_support::migrations::FreezeChainOnFailedMigration;
2425	type MaxServiceWeight = MbmServiceWeight;
2426	type WeightInfo = pallet_migrations::weights::SubstrateWeight<Runtime>;
2427}
2428
2429parameter_types! {
2430	pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
2431	pub const MinimumCreditPurchase: Balance =  100 * MILLICENTS;
2432}
2433
2434pub struct IntoAuthor;
2435impl OnUnbalanced<Credit<AccountId, Balances>> for IntoAuthor {
2436	fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
2437		if let Some(author) = Authorship::author() {
2438			let _ = <Balances as Balanced<_>>::resolve(&author, credit);
2439		}
2440	}
2441}
2442
2443pub struct CoretimeProvider;
2444impl CoretimeInterface for CoretimeProvider {
2445	type AccountId = AccountId;
2446	type Balance = Balance;
2447	type RelayChainBlockNumberProvider = System;
2448	fn request_core_count(_count: CoreIndex) {}
2449	fn request_revenue_info_at(_when: u32) {}
2450	fn credit_account(_who: Self::AccountId, _amount: Self::Balance) {}
2451	fn assign_core(
2452		_core: CoreIndex,
2453		_begin: u32,
2454		_assignment: Vec<(CoreAssignment, PartsOf57600)>,
2455		_end_hint: Option<u32>,
2456	) {
2457	}
2458}
2459
2460pub struct SovereignAccountOf;
2461// Dummy implementation which converts `TaskId` to `AccountId`.
2462impl MaybeConvert<TaskId, AccountId> for SovereignAccountOf {
2463	fn maybe_convert(task: TaskId) -> Option<AccountId> {
2464		let mut account: [u8; 32] = [0; 32];
2465		account[..4].copy_from_slice(&task.to_le_bytes());
2466		Some(account.into())
2467	}
2468}
2469impl pallet_broker::Config for Runtime {
2470	type RuntimeEvent = RuntimeEvent;
2471	type Currency = Balances;
2472	type OnRevenue = IntoAuthor;
2473	type TimeslicePeriod = ConstU32<2>;
2474	type MaxLeasedCores = ConstU32<5>;
2475	type MaxReservedCores = ConstU32<5>;
2476	type Coretime = CoretimeProvider;
2477	type ConvertBalance = traits::Identity;
2478	type WeightInfo = ();
2479	type PalletId = BrokerPalletId;
2480	type AdminOrigin = EnsureRoot<AccountId>;
2481	type SovereignAccountOf = SovereignAccountOf;
2482	type MaxAutoRenewals = ConstU32<10>;
2483	type PriceAdapter = pallet_broker::CenterTargetPrice<Balance>;
2484	type MinimumCreditPurchase = MinimumCreditPurchase;
2485}
2486
2487parameter_types! {
2488	pub const MixnetNumCoverToCurrentBlocks: BlockNumber = 3;
2489	pub const MixnetNumRequestsToCurrentBlocks: BlockNumber = 3;
2490	pub const MixnetNumCoverToPrevBlocks: BlockNumber = 3;
2491	pub const MixnetNumRegisterStartSlackBlocks: BlockNumber = 3;
2492	pub const MixnetNumRegisterEndSlackBlocks: BlockNumber = 3;
2493	pub const MixnetRegistrationPriority: TransactionPriority = ImOnlineUnsignedPriority::get() - 1;
2494}
2495
2496impl pallet_mixnet::Config for Runtime {
2497	type MaxAuthorities = MaxAuthorities;
2498	type MaxExternalAddressSize = ConstU32<128>;
2499	type MaxExternalAddressesPerMixnode = ConstU32<16>;
2500	type NextSessionRotation = Babe;
2501	type NumCoverToCurrentBlocks = MixnetNumCoverToCurrentBlocks;
2502	type NumRequestsToCurrentBlocks = MixnetNumRequestsToCurrentBlocks;
2503	type NumCoverToPrevBlocks = MixnetNumCoverToPrevBlocks;
2504	type NumRegisterStartSlackBlocks = MixnetNumRegisterStartSlackBlocks;
2505	type NumRegisterEndSlackBlocks = MixnetNumRegisterEndSlackBlocks;
2506	type RegistrationPriority = MixnetRegistrationPriority;
2507	type MinMixnodes = ConstU32<7>; // Low to allow small testing networks
2508}
2509
2510/// Dynamic parameters that can be changed at runtime through the
2511/// `pallet_parameters::set_parameter`.
2512#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
2513pub mod dynamic_params {
2514	use super::*;
2515
2516	#[dynamic_pallet_params]
2517	#[codec(index = 0)]
2518	pub mod storage {
2519		/// Configures the base deposit of storing some data.
2520		#[codec(index = 0)]
2521		pub static BaseDeposit: Balance = 1 * DOLLARS;
2522
2523		/// Configures the per-byte deposit of storing some data.
2524		#[codec(index = 1)]
2525		pub static ByteDeposit: Balance = 1 * CENTS;
2526	}
2527
2528	#[dynamic_pallet_params]
2529	#[codec(index = 1)]
2530	pub mod referenda {
2531		/// The configuration for the tracks
2532		#[codec(index = 0)]
2533		pub static Tracks: BoundedVec<
2534			pallet_referenda::Track<u16, Balance, BlockNumber>,
2535			ConstU32<100>,
2536		> = BoundedVec::truncate_from(vec![pallet_referenda::Track {
2537			id: 0u16,
2538			info: pallet_referenda::TrackInfo {
2539				name: s("root"),
2540				max_deciding: 1,
2541				decision_deposit: 10,
2542				prepare_period: 4,
2543				decision_period: 4,
2544				confirm_period: 2,
2545				min_enactment_period: 4,
2546				min_approval: pallet_referenda::Curve::LinearDecreasing {
2547					length: Perbill::from_percent(100),
2548					floor: Perbill::from_percent(50),
2549					ceil: Perbill::from_percent(100),
2550				},
2551				min_support: pallet_referenda::Curve::LinearDecreasing {
2552					length: Perbill::from_percent(100),
2553					floor: Perbill::from_percent(0),
2554					ceil: Perbill::from_percent(100),
2555				},
2556			},
2557		}]);
2558
2559		/// A list mapping every origin with a track Id
2560		#[codec(index = 1)]
2561		pub static Origins: BoundedVec<(OriginCaller, u16), ConstU32<100>> =
2562			BoundedVec::truncate_from(vec![(
2563				OriginCaller::system(frame_system::RawOrigin::Root),
2564				0,
2565			)]);
2566	}
2567}
2568
2569#[cfg(feature = "runtime-benchmarks")]
2570impl Default for RuntimeParameters {
2571	fn default() -> Self {
2572		RuntimeParameters::Storage(dynamic_params::storage::Parameters::BaseDeposit(
2573			dynamic_params::storage::BaseDeposit,
2574			Some(1 * DOLLARS),
2575		))
2576	}
2577}
2578
2579pub struct DynamicParametersManagerOrigin;
2580impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParametersManagerOrigin {
2581	type Success = ();
2582
2583	fn try_origin(
2584		origin: RuntimeOrigin,
2585		key: &RuntimeParametersKey,
2586	) -> Result<Self::Success, RuntimeOrigin> {
2587		match key {
2588			RuntimeParametersKey::Storage(_) => {
2589				frame_system::ensure_root(origin.clone()).map_err(|_| origin)?;
2590				return Ok(());
2591			},
2592			RuntimeParametersKey::Referenda(_) => {
2593				frame_system::ensure_root(origin.clone()).map_err(|_| origin)?;
2594				return Ok(());
2595			},
2596		}
2597	}
2598
2599	#[cfg(feature = "runtime-benchmarks")]
2600	fn try_successful_origin(_key: &RuntimeParametersKey) -> Result<RuntimeOrigin, ()> {
2601		Ok(RuntimeOrigin::root())
2602	}
2603}
2604
2605impl pallet_parameters::Config for Runtime {
2606	type RuntimeParameters = RuntimeParameters;
2607	type RuntimeEvent = RuntimeEvent;
2608	type AdminOrigin = DynamicParametersManagerOrigin;
2609	type WeightInfo = ();
2610}
2611
2612pub type MetaTxExtension = (
2613	pallet_verify_signature::VerifySignature<Runtime>,
2614	pallet_meta_tx::MetaTxMarker<Runtime>,
2615	frame_system::CheckNonZeroSender<Runtime>,
2616	frame_system::CheckSpecVersion<Runtime>,
2617	frame_system::CheckTxVersion<Runtime>,
2618	frame_system::CheckGenesis<Runtime>,
2619	frame_system::CheckEra<Runtime>,
2620	frame_system::CheckNonce<Runtime>,
2621	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
2622);
2623
2624impl pallet_meta_tx::Config for Runtime {
2625	type WeightInfo = ();
2626	type RuntimeEvent = RuntimeEvent;
2627	#[cfg(not(feature = "runtime-benchmarks"))]
2628	type Extension = MetaTxExtension;
2629	#[cfg(feature = "runtime-benchmarks")]
2630	type Extension = pallet_meta_tx::WeightlessExtension<Runtime>;
2631}
2632
2633#[frame_support::runtime]
2634mod runtime {
2635	use super::*;
2636
2637	#[runtime::runtime]
2638	#[runtime::derive(
2639		RuntimeCall,
2640		RuntimeEvent,
2641		RuntimeError,
2642		RuntimeOrigin,
2643		RuntimeFreezeReason,
2644		RuntimeHoldReason,
2645		RuntimeSlashReason,
2646		RuntimeLockId,
2647		RuntimeTask,
2648		RuntimeViewFunction
2649	)]
2650	pub struct Runtime;
2651
2652	#[runtime::pallet_index(0)]
2653	pub type System = frame_system::Pallet<Runtime>;
2654
2655	#[runtime::pallet_index(1)]
2656	pub type Utility = pallet_utility::Pallet<Runtime>;
2657
2658	#[runtime::pallet_index(2)]
2659	pub type Babe = pallet_babe::Pallet<Runtime>;
2660
2661	#[runtime::pallet_index(3)]
2662	pub type Timestamp = pallet_timestamp::Pallet<Runtime>;
2663
2664	// Authorship must be before session in order to note author in the correct session and era
2665	// for im-online and staking.
2666	#[runtime::pallet_index(4)]
2667	pub type Authorship = pallet_authorship::Pallet<Runtime>;
2668
2669	#[runtime::pallet_index(5)]
2670	pub type Indices = pallet_indices::Pallet<Runtime>;
2671
2672	#[runtime::pallet_index(6)]
2673	pub type Balances = pallet_balances::Pallet<Runtime>;
2674
2675	#[runtime::pallet_index(7)]
2676	pub type TransactionPayment = pallet_transaction_payment::Pallet<Runtime>;
2677
2678	#[runtime::pallet_index(9)]
2679	pub type AssetConversionTxPayment = pallet_asset_conversion_tx_payment::Pallet<Runtime>;
2680
2681	#[runtime::pallet_index(10)]
2682	pub type ElectionProviderMultiPhase = pallet_election_provider_multi_phase::Pallet<Runtime>;
2683
2684	#[runtime::pallet_index(11)]
2685	pub type Staking = pallet_staking::Pallet<Runtime>;
2686
2687	#[runtime::pallet_index(12)]
2688	pub type Session = pallet_session::Pallet<Runtime>;
2689
2690	#[runtime::pallet_index(13)]
2691	pub type Democracy = pallet_democracy::Pallet<Runtime>;
2692
2693	#[runtime::pallet_index(14)]
2694	pub type Council = pallet_collective::Pallet<Runtime, Instance1>;
2695
2696	#[runtime::pallet_index(15)]
2697	pub type TechnicalCommittee = pallet_collective::Pallet<Runtime, Instance2>;
2698
2699	#[runtime::pallet_index(16)]
2700	pub type Elections = pallet_elections_phragmen::Pallet<Runtime>;
2701
2702	#[runtime::pallet_index(17)]
2703	pub type TechnicalMembership = pallet_membership::Pallet<Runtime, Instance1>;
2704
2705	#[runtime::pallet_index(18)]
2706	pub type Grandpa = pallet_grandpa::Pallet<Runtime>;
2707
2708	#[runtime::pallet_index(19)]
2709	pub type Treasury = pallet_treasury::Pallet<Runtime>;
2710
2711	#[runtime::pallet_index(20)]
2712	pub type AssetRate = pallet_asset_rate::Pallet<Runtime>;
2713
2714	#[runtime::pallet_index(21)]
2715	pub type Contracts = pallet_contracts::Pallet<Runtime>;
2716
2717	#[runtime::pallet_index(22)]
2718	pub type Sudo = pallet_sudo::Pallet<Runtime>;
2719
2720	#[runtime::pallet_index(23)]
2721	pub type ImOnline = pallet_im_online::Pallet<Runtime>;
2722
2723	#[runtime::pallet_index(24)]
2724	pub type AuthorityDiscovery = pallet_authority_discovery::Pallet<Runtime>;
2725
2726	#[runtime::pallet_index(25)]
2727	pub type Offences = pallet_offences::Pallet<Runtime>;
2728
2729	#[runtime::pallet_index(26)]
2730	pub type Historical = pallet_session_historical::Pallet<Runtime>;
2731
2732	#[runtime::pallet_index(27)]
2733	pub type RandomnessCollectiveFlip = pallet_insecure_randomness_collective_flip::Pallet<Runtime>;
2734
2735	#[runtime::pallet_index(28)]
2736	pub type Identity = pallet_identity::Pallet<Runtime>;
2737
2738	#[runtime::pallet_index(29)]
2739	pub type Society = pallet_society::Pallet<Runtime>;
2740
2741	#[runtime::pallet_index(30)]
2742	pub type Recovery = pallet_recovery::Pallet<Runtime>;
2743
2744	#[runtime::pallet_index(31)]
2745	pub type Vesting = pallet_vesting::Pallet<Runtime>;
2746
2747	#[runtime::pallet_index(32)]
2748	pub type Scheduler = pallet_scheduler::Pallet<Runtime>;
2749
2750	#[runtime::pallet_index(33)]
2751	pub type Glutton = pallet_glutton::Pallet<Runtime>;
2752
2753	#[runtime::pallet_index(34)]
2754	pub type Preimage = pallet_preimage::Pallet<Runtime>;
2755
2756	#[runtime::pallet_index(35)]
2757	pub type Proxy = pallet_proxy::Pallet<Runtime>;
2758
2759	#[runtime::pallet_index(36)]
2760	pub type Multisig = pallet_multisig::Pallet<Runtime>;
2761
2762	#[runtime::pallet_index(37)]
2763	pub type Bounties = pallet_bounties::Pallet<Runtime>;
2764
2765	#[runtime::pallet_index(38)]
2766	pub type Tips = pallet_tips::Pallet<Runtime>;
2767
2768	#[runtime::pallet_index(39)]
2769	pub type Assets = pallet_assets::Pallet<Runtime, Instance1>;
2770
2771	#[runtime::pallet_index(40)]
2772	pub type PoolAssets = pallet_assets::Pallet<Runtime, Instance2>;
2773
2774	#[runtime::pallet_index(41)]
2775	pub type Beefy = pallet_beefy::Pallet<Runtime>;
2776
2777	// MMR leaf construction must be after session in order to have a leaf's next_auth_set
2778	// refer to block<N>. See issue polkadot-fellows/runtimes#160 for details.
2779	#[runtime::pallet_index(42)]
2780	pub type Mmr = pallet_mmr::Pallet<Runtime>;
2781
2782	#[runtime::pallet_index(43)]
2783	pub type MmrLeaf = pallet_beefy_mmr::Pallet<Runtime>;
2784
2785	#[runtime::pallet_index(44)]
2786	pub type Lottery = pallet_lottery::Pallet<Runtime>;
2787
2788	#[runtime::pallet_index(45)]
2789	pub type Nis = pallet_nis::Pallet<Runtime>;
2790
2791	#[runtime::pallet_index(46)]
2792	pub type Uniques = pallet_uniques::Pallet<Runtime>;
2793
2794	#[runtime::pallet_index(47)]
2795	pub type Nfts = pallet_nfts::Pallet<Runtime>;
2796
2797	#[runtime::pallet_index(48)]
2798	pub type NftFractionalization = pallet_nft_fractionalization::Pallet<Runtime>;
2799
2800	#[runtime::pallet_index(49)]
2801	pub type Salary = pallet_salary::Pallet<Runtime>;
2802
2803	#[runtime::pallet_index(50)]
2804	pub type CoreFellowship = pallet_core_fellowship::Pallet<Runtime>;
2805
2806	#[runtime::pallet_index(51)]
2807	pub type TransactionStorage = pallet_transaction_storage::Pallet<Runtime>;
2808
2809	#[runtime::pallet_index(52)]
2810	pub type VoterList = pallet_bags_list::Pallet<Runtime, Instance1>;
2811
2812	#[runtime::pallet_index(53)]
2813	pub type StateTrieMigration = pallet_state_trie_migration::Pallet<Runtime>;
2814
2815	#[runtime::pallet_index(54)]
2816	pub type ChildBounties = pallet_child_bounties::Pallet<Runtime>;
2817
2818	#[runtime::pallet_index(55)]
2819	pub type Referenda = pallet_referenda::Pallet<Runtime>;
2820
2821	#[runtime::pallet_index(56)]
2822	pub type Remark = pallet_remark::Pallet<Runtime>;
2823
2824	#[runtime::pallet_index(57)]
2825	pub type RootTesting = pallet_root_testing::Pallet<Runtime>;
2826
2827	#[runtime::pallet_index(58)]
2828	pub type ConvictionVoting = pallet_conviction_voting::Pallet<Runtime>;
2829
2830	#[runtime::pallet_index(59)]
2831	pub type Whitelist = pallet_whitelist::Pallet<Runtime>;
2832
2833	#[runtime::pallet_index(60)]
2834	pub type AllianceMotion = pallet_collective::Pallet<Runtime, Instance3>;
2835
2836	#[runtime::pallet_index(61)]
2837	pub type Alliance = pallet_alliance::Pallet<Runtime>;
2838
2839	#[runtime::pallet_index(62)]
2840	pub type NominationPools = pallet_nomination_pools::Pallet<Runtime>;
2841
2842	#[runtime::pallet_index(63)]
2843	pub type RankedPolls = pallet_referenda::Pallet<Runtime, Instance2>;
2844
2845	#[runtime::pallet_index(64)]
2846	pub type RankedCollective = pallet_ranked_collective::Pallet<Runtime>;
2847
2848	#[runtime::pallet_index(65)]
2849	pub type AssetConversion = pallet_asset_conversion::Pallet<Runtime>;
2850
2851	#[runtime::pallet_index(66)]
2852	pub type FastUnstake = pallet_fast_unstake::Pallet<Runtime>;
2853
2854	#[runtime::pallet_index(67)]
2855	pub type MessageQueue = pallet_message_queue::Pallet<Runtime>;
2856
2857	#[runtime::pallet_index(68)]
2858	pub type Pov = frame_benchmarking_pallet_pov::Pallet<Runtime>;
2859
2860	#[runtime::pallet_index(69)]
2861	pub type TxPause = pallet_tx_pause::Pallet<Runtime>;
2862
2863	#[runtime::pallet_index(70)]
2864	pub type SafeMode = pallet_safe_mode::Pallet<Runtime>;
2865
2866	#[runtime::pallet_index(71)]
2867	pub type Statement = pallet_statement::Pallet<Runtime>;
2868
2869	#[runtime::pallet_index(72)]
2870	pub type MultiBlockMigrations = pallet_migrations::Pallet<Runtime>;
2871
2872	#[runtime::pallet_index(73)]
2873	pub type Broker = pallet_broker::Pallet<Runtime>;
2874
2875	#[runtime::pallet_index(74)]
2876	pub type TasksExample = pallet_example_tasks::Pallet<Runtime>;
2877
2878	#[runtime::pallet_index(75)]
2879	pub type Mixnet = pallet_mixnet::Pallet<Runtime>;
2880
2881	#[runtime::pallet_index(76)]
2882	pub type Parameters = pallet_parameters::Pallet<Runtime>;
2883
2884	#[runtime::pallet_index(77)]
2885	pub type SkipFeelessPayment = pallet_skip_feeless_payment::Pallet<Runtime>;
2886
2887	#[runtime::pallet_index(78)]
2888	pub type PalletExampleMbms = pallet_example_mbm::Pallet<Runtime>;
2889
2890	#[runtime::pallet_index(79)]
2891	pub type AssetConversionMigration = pallet_asset_conversion_ops::Pallet<Runtime>;
2892
2893	#[runtime::pallet_index(80)]
2894	pub type Revive = pallet_revive::Pallet<Runtime>;
2895
2896	#[runtime::pallet_index(81)]
2897	pub type VerifySignature = pallet_verify_signature::Pallet<Runtime>;
2898
2899	#[runtime::pallet_index(82)]
2900	pub type DelegatedStaking = pallet_delegated_staking::Pallet<Runtime>;
2901
2902	#[runtime::pallet_index(83)]
2903	pub type AssetRewards = pallet_asset_rewards::Pallet<Runtime>;
2904
2905	#[runtime::pallet_index(84)]
2906	pub type AssetsFreezer = pallet_assets_freezer::Pallet<Runtime, Instance1>;
2907
2908	#[runtime::pallet_index(85)]
2909	pub type Oracle = pallet_oracle::Pallet<Runtime>;
2910
2911	#[runtime::pallet_index(86)]
2912	pub type Psm = pallet_psm::Pallet<Runtime>;
2913
2914	#[runtime::pallet_index(89)]
2915	pub type MetaTx = pallet_meta_tx::Pallet<Runtime>;
2916
2917	#[runtime::pallet_index(90)]
2918	pub type MultiAssetBounties = pallet_multi_asset_bounties::Pallet<Runtime>;
2919
2920	#[runtime::pallet_index(91)]
2921	pub type AssetsPrecompiles = pallet_assets_precompiles::pallet::Pallet<Runtime>;
2922
2923	#[runtime::pallet_index(92)]
2924	pub type AssetsPrecompilesPermit = pallet_assets_precompiles::permit::pallet::Pallet<Runtime>;
2925
2926	#[runtime::pallet_index(93)]
2927	pub type VestingPrecompiles = pallet_vesting_precompiles::pallet::Pallet<Runtime>;
2928
2929	#[runtime::pallet_index(94)]
2930	pub type Dap = pallet_dap::Pallet<Runtime>;
2931}
2932
2933/// The address format for describing accounts.
2934pub type Address = sp_runtime::MultiAddress<AccountId, AccountIndex>;
2935/// Block header type as expected by this runtime.
2936pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
2937/// Block type as expected by this runtime.
2938pub type Block = generic::Block<Header, UncheckedExtrinsic>;
2939/// A Block signed with a Justification
2940pub type SignedBlock = generic::SignedBlock<Block>;
2941/// BlockId type as expected by this runtime.
2942pub type BlockId = generic::BlockId<Block>;
2943/// The TransactionExtension to the basic transaction logic.
2944///
2945/// When you change this, you **MUST** modify [`sign`] in `bin/node/testing/src/keyring.rs`!
2946///
2947/// [`sign`]: <../../testing/src/keyring.rs.html>
2948pub type TxExtension = (
2949	frame_system::AuthorizeCall<Runtime>,
2950	frame_system::CheckNonZeroSender<Runtime>,
2951	frame_system::CheckSpecVersion<Runtime>,
2952	frame_system::CheckTxVersion<Runtime>,
2953	frame_system::CheckGenesis<Runtime>,
2954	frame_system::CheckEra<Runtime>,
2955	frame_system::CheckNonce<Runtime>,
2956	frame_system::CheckWeight<Runtime>,
2957	pallet_skip_feeless_payment::SkipCheckIfFeeless<
2958		Runtime,
2959		pallet_asset_conversion_tx_payment::ChargeAssetTxPayment<Runtime>,
2960	>,
2961	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
2962	pallet_revive::evm::tx_extension::SetOrigin<Runtime>,
2963	frame_system::WeightReclaim<Runtime>,
2964);
2965
2966#[derive(Clone, PartialEq, Eq, Debug)]
2967pub struct EthExtraImpl;
2968
2969impl EthExtra for EthExtraImpl {
2970	type Config = Runtime;
2971	type ExtensionV0 = TxExtension;
2972	type ExtensionOtherVersions = sp_runtime::traits::InvalidVersion;
2973
2974	fn get_eth_extension(nonce: u32, tip: Balance) -> Self::ExtensionV0 {
2975		(
2976			frame_system::AuthorizeCall::<Runtime>::new(),
2977			frame_system::CheckNonZeroSender::<Runtime>::new(),
2978			frame_system::CheckSpecVersion::<Runtime>::new(),
2979			frame_system::CheckTxVersion::<Runtime>::new(),
2980			frame_system::CheckGenesis::<Runtime>::new(),
2981			frame_system::CheckEra::from(crate::generic::Era::Immortal),
2982			frame_system::CheckNonce::<Runtime>::from(nonce),
2983			frame_system::CheckWeight::<Runtime>::new(),
2984			pallet_asset_conversion_tx_payment::ChargeAssetTxPayment::<Runtime>::from(tip, None)
2985				.into(),
2986			frame_metadata_hash_extension::CheckMetadataHash::<Runtime>::new(false),
2987			pallet_revive::evm::tx_extension::SetOrigin::<Runtime>::new_from_eth_transaction(),
2988			frame_system::WeightReclaim::<Runtime>::new(),
2989		)
2990	}
2991}
2992
2993/// Unchecked extrinsic type as expected by this runtime.
2994pub type UncheckedExtrinsic =
2995	pallet_revive::evm::runtime::UncheckedExtrinsic<Address, Signature, EthExtraImpl>;
2996/// Unchecked signature payload type as expected by this runtime.
2997pub type UncheckedSignaturePayload =
2998	generic::UncheckedSignaturePayload<Address, Signature, TxExtension>;
2999/// The payload being signed in transactions.
3000pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
3001/// Extrinsic type that has already been checked.
3002pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
3003/// Executive: handles dispatch to the various modules.
3004pub type Executive = frame_executive::Executive<
3005	Runtime,
3006	Block,
3007	frame_system::ChainContext<Runtime>,
3008	Runtime,
3009	AllPalletsWithSystem,
3010>;
3011
3012// We don't have a limit in the Relay Chain.
3013const IDENTITY_MIGRATION_KEY_LIMIT: u64 = u64::MAX;
3014
3015// All migrations executed on runtime upgrade as a nested tuple of types implementing
3016// `OnRuntimeUpgrade`. Note: These are examples and do not need to be run directly
3017// after the genesis block.
3018type Migrations = (
3019	pallet_nomination_pools::migration::versioned::V6ToV7<Runtime>,
3020	pallet_alliance::migration::Migration<Runtime>,
3021	pallet_contracts::Migration<Runtime>,
3022	pallet_identity::migration::versioned::V0ToV1<Runtime, IDENTITY_MIGRATION_KEY_LIMIT>,
3023);
3024
3025type EventRecord = frame_system::EventRecord<
3026	<Runtime as frame_system::Config>::RuntimeEvent,
3027	<Runtime as frame_system::Config>::Hash,
3028>;
3029
3030parameter_types! {
3031	pub const BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
3032}
3033
3034impl pallet_beefy::Config for Runtime {
3035	type BeefyId = BeefyId;
3036	type MaxAuthorities = MaxAuthorities;
3037	type MaxNominators = ConstU32<0>;
3038	type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
3039	type OnNewValidatorSet = MmrLeaf;
3040	type AncestryHelper = MmrLeaf;
3041	type WeightInfo = ();
3042	type KeyOwnerProof = sp_session::MembershipProof;
3043	type EquivocationReportSystem =
3044		pallet_beefy::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
3045}
3046
3047parameter_types! {
3048	pub const OracleMaxHasDispatchedSize: u32 = 20;
3049	pub const RootOperatorAccountId: AccountId = AccountId::new([0xffu8; 32]);
3050
3051	pub const OracleMaxFeedValues: u32 = 10;
3052}
3053
3054#[cfg(feature = "runtime-benchmarks")]
3055pub struct OracleBenchmarkingHelper;
3056
3057#[cfg(feature = "runtime-benchmarks")]
3058impl pallet_oracle::BenchmarkHelper<u32, u128, OracleMaxFeedValues> for OracleBenchmarkingHelper {
3059	fn get_currency_id_value_pairs() -> BoundedVec<(u32, u128), OracleMaxFeedValues> {
3060		use rand::{distributions::Uniform, prelude::*};
3061
3062		// Use seeded RNG like in contracts benchmarking
3063		let mut rng = rand_pcg::Pcg32::seed_from_u64(0x1234567890ABCDEF);
3064		let max_values = OracleMaxFeedValues::get() as usize;
3065
3066		// Generate random pairs like in election-provider-multi-phase
3067		let currency_range = Uniform::new_inclusive(1, 1000);
3068		let value_range = Uniform::new_inclusive(1000, 1_000_000);
3069
3070		let pairs: Vec<(u32, u128)> = (0..max_values)
3071			.map(|_| {
3072				let currency_id = rng.sample(currency_range);
3073				let value = rng.sample(value_range);
3074				(currency_id, value)
3075			})
3076			.collect();
3077
3078		// Use try_from pattern like in core-fellowship and broker
3079		BoundedVec::try_from(pairs).unwrap_or_default()
3080	}
3081}
3082
3083parameter_types! {
3084	pub const OraclePalletId: PalletId = PalletId(*b"py/oracl");
3085}
3086
3087impl pallet_oracle::Config for Runtime {
3088	type OnNewData = ();
3089	type CombineData = pallet_oracle::DefaultCombineData<Self, ConstU32<5>, ConstU64<3600>>;
3090	type Time = Timestamp;
3091	type OracleKey = u32;
3092	type OracleValue = u128;
3093	type PalletId = OraclePalletId;
3094	type Members = TechnicalMembership;
3095	type WeightInfo = ();
3096	type MaxHasDispatchedSize = OracleMaxHasDispatchedSize;
3097	type MaxFeedValues = OracleMaxFeedValues;
3098	#[cfg(feature = "runtime-benchmarks")]
3099	type BenchmarkHelper = OracleBenchmarkingHelper;
3100}
3101
3102parameter_types! {
3103	/// The pUSD stablecoin asset ID.
3104	pub const PsmStablecoinAssetId: u32 = 4242;
3105	/// Minimum swap amount for PSM operations (100 pUSD = 100 * 10^6).
3106	pub const PsmMinSwapAmount: Balance = 100_000_000;
3107	/// PalletId for deriving the PSM system account.
3108	pub const PsmPalletId: PalletId = PalletId(*b"py/pegsm");
3109	/// Insurance fund account that receives PSM fee revenue.
3110	pub PsmInsuranceFundAccount: AccountId =
3111		sp_runtime::traits::AccountIdConversion::<AccountId>::into_account_truncating(
3112			&PalletId(*b"py/insur"),
3113		);
3114}
3115
3116type PsmInternalAsset = ItemOf<Assets, PsmStablecoinAssetId, AccountId>;
3117
3118parameter_types! {
3119	/// No debt ceiling: maximum possible issuance.
3120	pub const NoVaultsCeiling: Balance = Balance::MAX;
3121}
3122
3123/// EnsureOrigin implementation for PSM management that supports privilege levels.
3124pub struct EnsurePsmManager;
3125impl frame_support::traits::EnsureOrigin<RuntimeOrigin> for EnsurePsmManager {
3126	type Success = pallet_psm::PsmManagerLevel;
3127
3128	fn try_origin(o: RuntimeOrigin) -> Result<Self::Success, RuntimeOrigin> {
3129		use frame_system::RawOrigin;
3130
3131		match o.clone().into() {
3132			Ok(RawOrigin::Root) => Ok(pallet_psm::PsmManagerLevel::Full),
3133			_ => Err(o),
3134		}
3135	}
3136
3137	#[cfg(feature = "runtime-benchmarks")]
3138	fn try_successful_origin() -> Result<RuntimeOrigin, ()> {
3139		Ok(RuntimeOrigin::root())
3140	}
3141}
3142
3143#[cfg(feature = "runtime-benchmarks")]
3144pub struct PsmBenchmarkHelper;
3145#[cfg(feature = "runtime-benchmarks")]
3146impl pallet_psm::BenchmarkHelper<u32, AccountId> for PsmBenchmarkHelper {
3147	fn get_asset_id(asset_index: u32) -> u32 {
3148		asset_index
3149	}
3150	fn create_asset(asset_id: u32, owner: &AccountId, decimals: u8) {
3151		use frame_support::traits::fungibles::{metadata::Mutate as MetadataMutate, Create};
3152		if !<Assets as frame_support::traits::fungibles::Inspect<AccountId>>::asset_exists(asset_id)
3153		{
3154			let _ = <Assets as Create<AccountId>>::create(asset_id, owner.clone(), true, 1);
3155		}
3156		let _ = Balances::force_set_balance(
3157			RuntimeOrigin::root(),
3158			owner.clone().into(),
3159			10u128.pow(18),
3160		);
3161		let _ = <Assets as MetadataMutate<AccountId>>::set(
3162			asset_id,
3163			owner,
3164			b"Benchmark".to_vec(),
3165			b"BNC".to_vec(),
3166			decimals,
3167		);
3168	}
3169}
3170
3171/// Configure the PSM (Peg Stability Module) pallet.
3172impl pallet_psm::Config for Runtime {
3173	type Fungibles = Assets;
3174	type AssetId = u32;
3175	type MaximumIssuance = NoVaultsCeiling;
3176	type ManagerOrigin = EnsurePsmManager;
3177	type WeightInfo = pallet_psm::weights::SubstrateWeight<Runtime>;
3178	type InternalAsset = PsmInternalAsset;
3179	type FeeDestination = PsmInsuranceFundAccount;
3180	type PalletId = PsmPalletId;
3181	type MinSwapAmount = PsmMinSwapAmount;
3182	type MaxExternalAssets = ConstU32<10>;
3183	#[cfg(feature = "runtime-benchmarks")]
3184	type BenchmarkHelper = PsmBenchmarkHelper;
3185}
3186
3187/// MMR helper types.
3188mod mmr {
3189	use super::*;
3190	pub use pallet_mmr::primitives::*;
3191
3192	pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
3193	pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
3194	pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
3195}
3196
3197#[cfg(feature = "runtime-benchmarks")]
3198pub struct AssetConversionTxHelper;
3199
3200#[cfg(feature = "runtime-benchmarks")]
3201impl
3202	pallet_asset_conversion_tx_payment::BenchmarkHelperTrait<
3203		AccountId,
3204		NativeOrWithId<u32>,
3205		NativeOrWithId<u32>,
3206	> for AssetConversionTxHelper
3207{
3208	fn create_asset_id_parameter(seed: u32) -> (NativeOrWithId<u32>, NativeOrWithId<u32>) {
3209		(NativeOrWithId::WithId(seed), NativeOrWithId::WithId(seed))
3210	}
3211
3212	fn setup_balances_and_pool(asset_id: NativeOrWithId<u32>, account: AccountId) {
3213		use frame_support::{assert_ok, traits::fungibles::Mutate};
3214		let NativeOrWithId::WithId(asset_idx) = asset_id.clone() else { unimplemented!() };
3215		assert_ok!(Assets::force_create(
3216			RuntimeOrigin::root(),
3217			asset_idx.into(),
3218			account.clone().into(), // owner
3219			true,                   // is_sufficient
3220			1,
3221		));
3222
3223		let lp_provider = account.clone();
3224		let _ = Balances::deposit_creating(&lp_provider, ((u64::MAX as u128) * 100).into());
3225		assert_ok!(Assets::mint_into(
3226			asset_idx.into(),
3227			&lp_provider,
3228			((u64::MAX as u128) * 100).into()
3229		));
3230
3231		let token_native = alloc::boxed::Box::new(NativeOrWithId::Native);
3232		let token_second = alloc::boxed::Box::new(asset_id);
3233
3234		assert_ok!(AssetConversion::create_pool(
3235			RuntimeOrigin::signed(lp_provider.clone()),
3236			token_native.clone(),
3237			token_second.clone()
3238		));
3239
3240		assert_ok!(AssetConversion::add_liquidity(
3241			RuntimeOrigin::signed(lp_provider.clone()),
3242			token_native,
3243			token_second,
3244			u64::MAX.into(), // 1 desired
3245			u64::MAX.into(), // 2 desired
3246			1,               // 1 min
3247			1,               // 2 min
3248			lp_provider,
3249		));
3250	}
3251}
3252
3253#[cfg(feature = "runtime-benchmarks")]
3254mod benches {
3255	polkadot_sdk::frame_benchmarking::define_benchmarks!(
3256		[frame_benchmarking, BaselineBench::<Runtime>]
3257		[frame_benchmarking_pallet_pov, Pov]
3258		[pallet_alliance, Alliance]
3259		[pallet_assets, Assets]
3260		[pallet_babe, Babe]
3261		[pallet_bags_list, VoterList]
3262		[pallet_balances, Balances]
3263		[pallet_beefy_mmr, MmrLeaf]
3264		[pallet_bounties, Bounties]
3265		[pallet_broker, Broker]
3266		[pallet_child_bounties, ChildBounties]
3267		[pallet_collective, Council]
3268		[pallet_conviction_voting, ConvictionVoting]
3269		[pallet_contracts, Contracts]
3270		[pallet_revive, Revive]
3271		[pallet_core_fellowship, CoreFellowship]
3272		[pallet_example_tasks, TasksExample]
3273		[pallet_democracy, Democracy]
3274		[pallet_asset_conversion, AssetConversion]
3275		[pallet_asset_rewards, AssetRewards]
3276		[pallet_asset_conversion_tx_payment, AssetConversionTxPayment]
3277		[pallet_transaction_payment, TransactionPayment]
3278		[pallet_election_provider_multi_phase, ElectionProviderMultiPhase]
3279		[pallet_election_provider_support_benchmarking, EPSBench::<Runtime>]
3280		[pallet_elections_phragmen, Elections]
3281		[pallet_fast_unstake, FastUnstake]
3282		[pallet_nis, Nis]
3283		[pallet_parameters, Parameters]
3284		[pallet_grandpa, Grandpa]
3285		[pallet_identity, Identity]
3286		[pallet_im_online, ImOnline]
3287		[pallet_indices, Indices]
3288		[pallet_lottery, Lottery]
3289		[pallet_membership, TechnicalMembership]
3290		[pallet_message_queue, MessageQueue]
3291		[pallet_migrations, MultiBlockMigrations]
3292		[pallet_mmr, Mmr]
3293		[pallet_multi_asset_bounties, MultiAssetBounties]
3294		[pallet_assets_precompiles, AssetsPrecompiles]
3295		[pallet_vesting_precompiles, VestingPrecompiles]
3296		[pallet_multisig, Multisig]
3297		[pallet_nomination_pools, NominationPoolsBench::<Runtime>]
3298		[pallet_offences, OffencesBench::<Runtime>]
3299		[pallet_oracle, Oracle]
3300		[pallet_preimage, Preimage]
3301		[pallet_proxy, Proxy]
3302		[pallet_ranked_collective, RankedCollective]
3303		[pallet_referenda, Referenda]
3304		[pallet_recovery, Recovery]
3305		[pallet_remark, Remark]
3306		[pallet_salary, Salary]
3307		[pallet_scheduler, Scheduler]
3308		[pallet_glutton, Glutton]
3309		[pallet_session, SessionBench::<Runtime>]
3310		[pallet_society, Society]
3311		[pallet_dap, Dap]
3312		[pallet_staking, Staking]
3313		[pallet_state_trie_migration, StateTrieMigration]
3314		[pallet_sudo, Sudo]
3315		[frame_system, SystemBench::<Runtime>]
3316		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
3317		[pallet_timestamp, Timestamp]
3318		[pallet_tips, Tips]
3319		[pallet_transaction_storage, TransactionStorage]
3320		[pallet_treasury, Treasury]
3321		[pallet_asset_rate, AssetRate]
3322		[pallet_uniques, Uniques]
3323		[pallet_nfts, Nfts]
3324		[pallet_nft_fractionalization, NftFractionalization]
3325		[pallet_utility, Utility]
3326		[pallet_vesting, Vesting]
3327		[pallet_whitelist, Whitelist]
3328		[pallet_tx_pause, TxPause]
3329		[pallet_safe_mode, SafeMode]
3330		[pallet_example_mbm, PalletExampleMbms]
3331		[pallet_asset_conversion_ops, AssetConversionMigration]
3332		[pallet_verify_signature, VerifySignature]
3333		[pallet_meta_tx, MetaTx]
3334		[pallet_psm, Psm]
3335	);
3336}
3337
3338pallet_revive::impl_runtime_apis_plus_revive_traits!(
3339	Runtime,
3340	Revive,
3341	Executive,
3342	EthExtraImpl,
3343
3344	impl sp_api::Core<Block> for Runtime {
3345		fn version() -> RuntimeVersion {
3346			VERSION
3347		}
3348
3349		fn execute_block(block: <Block as BlockT>::LazyBlock) {
3350			Executive::execute_block(block);
3351		}
3352
3353		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
3354			Executive::initialize_block(header)
3355		}
3356	}
3357
3358	impl sp_api::Metadata<Block> for Runtime {
3359		fn metadata() -> OpaqueMetadata {
3360			OpaqueMetadata::new(Runtime::metadata().into())
3361		}
3362
3363		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
3364			Runtime::metadata_at_version(version)
3365		}
3366
3367		fn metadata_versions() -> alloc::vec::Vec<u32> {
3368			Runtime::metadata_versions()
3369		}
3370	}
3371
3372	impl frame_support::view_functions::runtime_api::RuntimeViewFunction<Block> for Runtime {
3373		fn execute_view_function(id: frame_support::view_functions::ViewFunctionId, input: Vec<u8>) -> Result<Vec<u8>, frame_support::view_functions::ViewFunctionDispatchError> {
3374			Runtime::execute_view_function(id, input)
3375		}
3376	}
3377
3378	impl sp_block_builder::BlockBuilder<Block> for Runtime {
3379		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
3380			Executive::apply_extrinsic(extrinsic)
3381		}
3382
3383		fn finalize_block() -> <Block as BlockT>::Header {
3384			Executive::finalize_block()
3385		}
3386
3387		fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
3388			data.create_extrinsics()
3389		}
3390
3391		fn check_inherents(block: <Block as BlockT>::LazyBlock, data: InherentData) -> CheckInherentsResult {
3392			data.check_extrinsics(&block)
3393		}
3394	}
3395
3396	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
3397		fn validate_transaction(
3398			source: TransactionSource,
3399			tx: <Block as BlockT>::Extrinsic,
3400			block_hash: <Block as BlockT>::Hash,
3401		) -> TransactionValidity {
3402			Executive::validate_transaction(source, tx, block_hash)
3403		}
3404	}
3405
3406	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
3407		fn offchain_worker(header: &<Block as BlockT>::Header) {
3408			Executive::offchain_worker(header)
3409		}
3410	}
3411
3412	impl sp_consensus_grandpa::GrandpaApi<Block> for Runtime {
3413		fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
3414			Grandpa::grandpa_authorities()
3415		}
3416
3417		fn current_set_id() -> sp_consensus_grandpa::SetId {
3418			pallet_grandpa::CurrentSetId::<Runtime>::get()
3419		}
3420
3421		fn submit_report_equivocation_unsigned_extrinsic(
3422			equivocation_proof: sp_consensus_grandpa::EquivocationProof<
3423				<Block as BlockT>::Hash,
3424				NumberFor<Block>,
3425			>,
3426			key_owner_proof: sp_consensus_grandpa::OpaqueKeyOwnershipProof,
3427		) -> Option<()> {
3428			let key_owner_proof = key_owner_proof.decode()?;
3429
3430			Grandpa::submit_unsigned_equivocation_report(
3431				equivocation_proof,
3432				key_owner_proof,
3433			)
3434		}
3435
3436		fn generate_key_ownership_proof(
3437			_set_id: sp_consensus_grandpa::SetId,
3438			authority_id: GrandpaId,
3439		) -> Option<sp_consensus_grandpa::OpaqueKeyOwnershipProof> {
3440			use codec::Encode;
3441
3442			Historical::prove((sp_consensus_grandpa::KEY_TYPE, authority_id))
3443				.map(|p| p.encode())
3444				.map(sp_consensus_grandpa::OpaqueKeyOwnershipProof::new)
3445		}
3446	}
3447
3448	impl pallet_nomination_pools_runtime_api::NominationPoolsApi<Block, AccountId, Balance> for Runtime {
3449		fn pending_rewards(who: AccountId) -> Balance {
3450			NominationPools::api_pending_rewards(who).unwrap_or_default()
3451		}
3452
3453		fn points_to_balance(pool_id: PoolId, points: Balance) -> Balance {
3454			NominationPools::api_points_to_balance(pool_id, points)
3455		}
3456
3457		fn balance_to_points(pool_id: PoolId, new_funds: Balance) -> Balance {
3458			NominationPools::api_balance_to_points(pool_id, new_funds)
3459		}
3460
3461		fn pool_pending_slash(pool_id: PoolId) -> Balance {
3462			NominationPools::api_pool_pending_slash(pool_id)
3463		}
3464
3465		fn member_pending_slash(member: AccountId) -> Balance {
3466			NominationPools::api_member_pending_slash(member)
3467		}
3468
3469		fn pool_needs_delegate_migration(pool_id: PoolId) -> bool {
3470			NominationPools::api_pool_needs_delegate_migration(pool_id)
3471		}
3472
3473		fn member_needs_delegate_migration(member: AccountId) -> bool {
3474			NominationPools::api_member_needs_delegate_migration(member)
3475		}
3476
3477		fn member_total_balance(member: AccountId) -> Balance {
3478			NominationPools::api_member_total_balance(member)
3479		}
3480
3481		fn pool_balance(pool_id: PoolId) -> Balance {
3482			NominationPools::api_pool_balance(pool_id)
3483		}
3484
3485		fn pool_accounts(pool_id: PoolId) -> (AccountId, AccountId) {
3486			NominationPools::api_pool_accounts(pool_id)
3487		}
3488	}
3489
3490	impl pallet_staking_runtime_api::StakingApi<Block, Balance, AccountId> for Runtime {
3491		fn nominations_quota(balance: Balance) -> u32 {
3492			Staking::api_nominations_quota(balance)
3493		}
3494
3495		fn eras_stakers_page_count(era: sp_staking::EraIndex, account: AccountId) -> sp_staking::Page {
3496			Staking::api_eras_stakers_page_count(era, account)
3497		}
3498
3499		fn pending_rewards(era: sp_staking::EraIndex, account: AccountId) -> bool {
3500			Staking::api_pending_rewards(era, account)
3501		}
3502	}
3503
3504	impl sp_consensus_babe::BabeApi<Block> for Runtime {
3505		fn configuration() -> sp_consensus_babe::BabeConfiguration {
3506			let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG);
3507			sp_consensus_babe::BabeConfiguration {
3508				slot_duration: Babe::slot_duration(),
3509				epoch_length: EpochDuration::get(),
3510				c: epoch_config.c,
3511				authorities: Babe::authorities().to_vec(),
3512				randomness: Babe::randomness(),
3513				allowed_slots: epoch_config.allowed_slots,
3514			}
3515		}
3516
3517		fn current_epoch_start() -> sp_consensus_babe::Slot {
3518			Babe::current_epoch_start()
3519		}
3520
3521		fn current_epoch() -> sp_consensus_babe::Epoch {
3522			Babe::current_epoch()
3523		}
3524
3525		fn next_epoch() -> sp_consensus_babe::Epoch {
3526			Babe::next_epoch()
3527		}
3528
3529		fn generate_key_ownership_proof(
3530			_slot: sp_consensus_babe::Slot,
3531			authority_id: sp_consensus_babe::AuthorityId,
3532		) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
3533			use codec::Encode;
3534
3535			Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
3536				.map(|p| p.encode())
3537				.map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
3538		}
3539
3540		fn submit_report_equivocation_unsigned_extrinsic(
3541			equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
3542			key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
3543		) -> Option<()> {
3544			let key_owner_proof = key_owner_proof.decode()?;
3545
3546			Babe::submit_unsigned_equivocation_report(
3547				equivocation_proof,
3548				key_owner_proof,
3549			)
3550		}
3551	}
3552
3553	impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
3554		fn authorities() -> Vec<AuthorityDiscoveryId> {
3555			AuthorityDiscovery::authorities()
3556		}
3557	}
3558
3559	impl polkadot_sdk::pallet_oracle_runtime_api::OracleApi<Block, u32, u32, u128> for Runtime {
3560		fn get_value(_provider_id: u32, key: u32) -> Option<u128> {
3561			// ProviderId is unused as we only have 1 provider
3562			pallet_oracle::Pallet::<Runtime>::get(&key).map(|v| v.value)
3563		}
3564
3565		fn get_all_values(_provider_id: u32) -> Vec<(u32, Option<u128>)> {
3566			use pallet_oracle::DataProviderExtended;
3567			pallet_oracle::Pallet::<Runtime>::get_all_values()
3568				.map(|(k, v)| (k, v.map(|tv| tv.value)))
3569				.collect()
3570		}
3571	}
3572
3573	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
3574		fn account_nonce(account: AccountId) -> Nonce {
3575			System::account_nonce(account)
3576		}
3577	}
3578
3579	impl assets_api::AssetsApi<
3580		Block,
3581		AccountId,
3582		Balance,
3583		u32,
3584	> for Runtime
3585	{
3586		fn account_balances(account: AccountId) -> Vec<(u32, Balance)> {
3587			Assets::account_balances(account)
3588		}
3589	}
3590
3591	impl pallet_contracts::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash, EventRecord> for Runtime
3592	{
3593		fn call(
3594			origin: AccountId,
3595			dest: AccountId,
3596			value: Balance,
3597			gas_limit: Option<Weight>,
3598			storage_deposit_limit: Option<Balance>,
3599			input_data: Vec<u8>,
3600		) -> pallet_contracts::ContractExecResult<Balance, EventRecord> {
3601			let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block);
3602			Contracts::bare_call(
3603				origin,
3604				dest,
3605				value,
3606				gas_limit,
3607				storage_deposit_limit,
3608				input_data,
3609				pallet_contracts::DebugInfo::UnsafeDebug,
3610				pallet_contracts::CollectEvents::UnsafeCollect,
3611				pallet_contracts::Determinism::Enforced,
3612			)
3613		}
3614
3615		fn instantiate(
3616			origin: AccountId,
3617			value: Balance,
3618			gas_limit: Option<Weight>,
3619			storage_deposit_limit: Option<Balance>,
3620			code: pallet_contracts::Code<Hash>,
3621			data: Vec<u8>,
3622			salt: Vec<u8>,
3623		) -> pallet_contracts::ContractInstantiateResult<AccountId, Balance, EventRecord>
3624		{
3625			let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block);
3626			Contracts::bare_instantiate(
3627				origin,
3628				value,
3629				gas_limit,
3630				storage_deposit_limit,
3631				code,
3632				data,
3633				salt,
3634				pallet_contracts::DebugInfo::UnsafeDebug,
3635				pallet_contracts::CollectEvents::UnsafeCollect,
3636			)
3637		}
3638
3639		fn upload_code(
3640			origin: AccountId,
3641			code: Vec<u8>,
3642			storage_deposit_limit: Option<Balance>,
3643			determinism: pallet_contracts::Determinism,
3644		) -> pallet_contracts::CodeUploadResult<Hash, Balance>
3645		{
3646			Contracts::bare_upload_code(
3647				origin,
3648				code,
3649				storage_deposit_limit,
3650				determinism,
3651			)
3652		}
3653
3654		fn get_storage(
3655			address: AccountId,
3656			key: Vec<u8>,
3657		) -> pallet_contracts::GetStorageResult {
3658			Contracts::get_storage(
3659				address,
3660				key
3661			)
3662		}
3663	}
3664
3665	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
3666		Block,
3667		Balance,
3668	> for Runtime {
3669		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
3670			TransactionPayment::query_info(uxt, len)
3671		}
3672		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
3673			TransactionPayment::query_fee_details(uxt, len)
3674		}
3675		fn query_weight_to_fee(weight: Weight) -> Balance {
3676			TransactionPayment::weight_to_fee(weight)
3677		}
3678		fn query_length_to_fee(length: u32) -> Balance {
3679			TransactionPayment::length_to_fee(length)
3680		}
3681	}
3682
3683	impl pallet_asset_conversion::AssetConversionApi<
3684		Block,
3685		Balance,
3686		NativeOrWithId<u32>
3687	> for Runtime
3688	{
3689		fn quote_price_exact_tokens_for_tokens(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>, amount: Balance, include_fee: bool) -> Option<Balance> {
3690			AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee)
3691		}
3692
3693		fn quote_price_tokens_for_exact_tokens(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>, amount: Balance, include_fee: bool) -> Option<Balance> {
3694			AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee)
3695		}
3696
3697		fn get_reserves(asset1: NativeOrWithId<u32>, asset2: NativeOrWithId<u32>) -> Option<(Balance, Balance)> {
3698			AssetConversion::get_reserves(asset1, asset2).ok()
3699		}
3700	}
3701
3702	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
3703		for Runtime
3704	{
3705		fn query_call_info(call: RuntimeCall, len: u32) -> RuntimeDispatchInfo<Balance> {
3706			TransactionPayment::query_call_info(call, len)
3707		}
3708		fn query_call_fee_details(call: RuntimeCall, len: u32) -> FeeDetails<Balance> {
3709			TransactionPayment::query_call_fee_details(call, len)
3710		}
3711		fn query_weight_to_fee(weight: Weight) -> Balance {
3712			TransactionPayment::weight_to_fee(weight)
3713		}
3714		fn query_length_to_fee(length: u32) -> Balance {
3715			TransactionPayment::length_to_fee(length)
3716		}
3717	}
3718
3719	impl pallet_nfts_runtime_api::NftsApi<Block, AccountId, u32, u32> for Runtime {
3720		fn owner(collection: u32, item: u32) -> Option<AccountId> {
3721			<Nfts as Inspect<AccountId>>::owner(&collection, &item)
3722		}
3723
3724		fn collection_owner(collection: u32) -> Option<AccountId> {
3725			<Nfts as Inspect<AccountId>>::collection_owner(&collection)
3726		}
3727
3728		fn attribute(
3729			collection: u32,
3730			item: u32,
3731			key: Vec<u8>,
3732		) -> Option<Vec<u8>> {
3733			<Nfts as Inspect<AccountId>>::attribute(&collection, &item, &key)
3734		}
3735
3736		fn custom_attribute(
3737			account: AccountId,
3738			collection: u32,
3739			item: u32,
3740			key: Vec<u8>,
3741		) -> Option<Vec<u8>> {
3742			<Nfts as Inspect<AccountId>>::custom_attribute(
3743				&account,
3744				&collection,
3745				&item,
3746				&key,
3747			)
3748		}
3749
3750		fn system_attribute(
3751			collection: u32,
3752			item: Option<u32>,
3753			key: Vec<u8>,
3754		) -> Option<Vec<u8>> {
3755			<Nfts as Inspect<AccountId>>::system_attribute(&collection, item.as_ref(), &key)
3756		}
3757
3758		fn collection_attribute(collection: u32, key: Vec<u8>) -> Option<Vec<u8>> {
3759			<Nfts as Inspect<AccountId>>::collection_attribute(&collection, &key)
3760		}
3761	}
3762
3763	#[api_version(6)]
3764	impl sp_consensus_beefy::BeefyApi<Block, BeefyId> for Runtime {
3765		fn beefy_genesis() -> Option<BlockNumber> {
3766			pallet_beefy::GenesisBlock::<Runtime>::get()
3767		}
3768
3769		fn validator_set() -> Option<sp_consensus_beefy::ValidatorSet<BeefyId>> {
3770			Beefy::validator_set()
3771		}
3772
3773		fn submit_report_double_voting_unsigned_extrinsic(
3774			equivocation_proof: sp_consensus_beefy::DoubleVotingProof<
3775				BlockNumber,
3776				BeefyId,
3777				BeefySignature,
3778			>,
3779			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
3780		) -> Option<()> {
3781			let key_owner_proof = key_owner_proof.decode()?;
3782
3783			Beefy::submit_unsigned_double_voting_report(
3784				equivocation_proof,
3785				key_owner_proof,
3786			)
3787		}
3788
3789		fn submit_report_fork_voting_unsigned_extrinsic(
3790			equivocation_proof:
3791				sp_consensus_beefy::ForkVotingProof<
3792					<Block as BlockT>::Header,
3793					BeefyId,
3794					sp_runtime::OpaqueValue
3795				>,
3796			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
3797		) -> Option<()> {
3798			Beefy::submit_unsigned_fork_voting_report(
3799				equivocation_proof.try_into()?,
3800				key_owner_proof.decode()?,
3801			)
3802		}
3803
3804		fn submit_report_future_block_voting_unsigned_extrinsic(
3805			equivocation_proof: sp_consensus_beefy::FutureBlockVotingProof<BlockNumber, BeefyId>,
3806			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
3807		) -> Option<()> {
3808			Beefy::submit_unsigned_future_block_voting_report(
3809				equivocation_proof,
3810				key_owner_proof.decode()?,
3811			)
3812		}
3813
3814		fn generate_key_ownership_proof(
3815			_set_id: sp_consensus_beefy::ValidatorSetId,
3816			authority_id: BeefyId,
3817		) -> Option<sp_consensus_beefy::OpaqueKeyOwnershipProof> {
3818			Historical::prove((sp_consensus_beefy::KEY_TYPE, authority_id))
3819				.map(|p| p.encode())
3820				.map(sp_consensus_beefy::OpaqueKeyOwnershipProof::new)
3821		}
3822	}
3823
3824	#[api_version(3)]
3825	impl pallet_mmr::primitives::MmrApi<
3826		Block,
3827		mmr::Hash,
3828		BlockNumber,
3829	> for Runtime {
3830		fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
3831			Ok(pallet_mmr::RootHash::<Runtime>::get())
3832		}
3833
3834		fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
3835			Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
3836		}
3837
3838		fn generate_proof(
3839			block_numbers: Vec<BlockNumber>,
3840			best_known_block_number: Option<BlockNumber>,
3841		) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
3842			Mmr::generate_proof(block_numbers, best_known_block_number).map(
3843				|(leaves, proof)| {
3844					(
3845						leaves
3846							.into_iter()
3847							.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
3848							.collect(),
3849						proof,
3850					)
3851				},
3852			)
3853		}
3854
3855		fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
3856			-> Result<(), mmr::Error>
3857		{
3858			let leaves = leaves.into_iter().map(|leaf|
3859				leaf.into_opaque_leaf()
3860				.try_decode()
3861				.ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
3862			Mmr::verify_leaves(leaves, proof)
3863		}
3864
3865		fn generate_ancestry_proof(
3866			prev_block_number: BlockNumber,
3867			best_known_block_number: Option<BlockNumber>,
3868		) -> Result<mmr::AncestryProof<mmr::Hash>, mmr::Error> {
3869			Mmr::generate_ancestry_proof(prev_block_number, best_known_block_number)
3870		}
3871
3872		fn verify_proof_stateless(
3873			root: mmr::Hash,
3874			leaves: Vec<mmr::EncodableOpaqueLeaf>,
3875			proof: mmr::LeafProof<mmr::Hash>
3876		) -> Result<(), mmr::Error> {
3877			let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
3878			pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
3879		}
3880	}
3881
3882	impl sp_mixnet::runtime_api::MixnetApi<Block> for Runtime {
3883		fn session_status() -> sp_mixnet::types::SessionStatus {
3884			Mixnet::session_status()
3885		}
3886
3887		fn prev_mixnodes() -> Result<Vec<sp_mixnet::types::Mixnode>, sp_mixnet::types::MixnodesErr> {
3888			Mixnet::prev_mixnodes()
3889		}
3890
3891		fn current_mixnodes() -> Result<Vec<sp_mixnet::types::Mixnode>, sp_mixnet::types::MixnodesErr> {
3892			Mixnet::current_mixnodes()
3893		}
3894
3895		fn maybe_register(session_index: sp_mixnet::types::SessionIndex, mixnode: sp_mixnet::types::Mixnode) -> bool {
3896			Mixnet::maybe_register(session_index, mixnode)
3897		}
3898	}
3899
3900	impl sp_session::SessionKeys<Block> for Runtime {
3901		fn generate_session_keys(owner: Vec<u8>, seed: Option<Vec<u8>>) -> sp_session::OpaqueGeneratedSessionKeys {
3902			SessionKeys::generate(&owner, seed).into()
3903		}
3904
3905		fn decode_session_keys(
3906			encoded: Vec<u8>,
3907		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
3908			SessionKeys::decode_into_raw_public_keys(&encoded)
3909		}
3910	}
3911
3912	impl pallet_asset_rewards::AssetRewards<Block, Balance> for Runtime {
3913		fn pool_creation_cost() -> Balance {
3914			StakePoolCreationDeposit::get()
3915		}
3916	}
3917
3918	impl sp_transaction_storage_proof::runtime_api::TransactionStorageApi<Block> for Runtime {
3919		fn retention_period() -> NumberFor<Block> {
3920			TransactionStorage::retention_period()
3921		}
3922
3923		fn indexed_transactions(
3924			block: NumberFor<Block>,
3925		) -> Vec<sp_transaction_storage_proof::IndexedTransactionInfo> {
3926			TransactionStorage::indexed_transactions(block)
3927		}
3928	}
3929
3930	#[cfg(feature = "try-runtime")]
3931	impl frame_try_runtime::TryRuntime<Block> for Runtime {
3932		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
3933			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
3934			// have a backtrace here. If any of the pre/post migration checks fail, we shall stop
3935			// right here and right now.
3936			let weight = Executive::try_runtime_upgrade(checks).unwrap();
3937			(weight, RuntimeBlockWeights::get().max_block)
3938		}
3939
3940		fn execute_block(
3941			block: <Block as BlockT>::LazyBlock,
3942			state_root_check: bool,
3943			signature_check: bool,
3944			select: frame_try_runtime::TryStateSelect
3945		) -> Weight {
3946			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
3947			// have a backtrace here.
3948			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
3949		}
3950	}
3951
3952	#[cfg(feature = "runtime-benchmarks")]
3953	impl frame_benchmarking::Benchmark<Block> for Runtime {
3954		fn benchmark_metadata(extra: bool) -> (
3955			Vec<frame_benchmarking::BenchmarkList>,
3956			Vec<frame_support::traits::StorageInfo>,
3957		) {
3958			use frame_benchmarking::{baseline, BenchmarkList};
3959			use frame_support::traits::StorageInfoTrait;
3960
3961			// Trying to add benchmarks directly to the Session Pallet caused cyclic dependency
3962			// issues. To get around that, we separated the Session benchmarks into its own crate,
3963			// which is why we need these two lines below.
3964			use pallet_session_benchmarking::Pallet as SessionBench;
3965			use pallet_offences_benchmarking::Pallet as OffencesBench;
3966			use pallet_election_provider_support_benchmarking::Pallet as EPSBench;
3967			use frame_system_benchmarking::Pallet as SystemBench;
3968			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
3969			use baseline::Pallet as BaselineBench;
3970			use pallet_nomination_pools_benchmarking::Pallet as NominationPoolsBench;
3971
3972			let mut list = Vec::<BenchmarkList>::new();
3973			list_benchmarks!(list, extra);
3974
3975			let storage_info = AllPalletsWithSystem::storage_info();
3976
3977			(list, storage_info)
3978		}
3979
3980		#[allow(non_local_definitions)]
3981		fn dispatch_benchmark(
3982			config: frame_benchmarking::BenchmarkConfig
3983		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
3984			use frame_benchmarking::{baseline, BenchmarkBatch};
3985			use sp_storage::TrackedStorageKey;
3986
3987			// Trying to add benchmarks directly to the Session Pallet caused cyclic dependency
3988			// issues. To get around that, we separated the Session benchmarks into its own crate,
3989			// which is why we need these two lines below.
3990			use pallet_session_benchmarking::Pallet as SessionBench;
3991			use pallet_offences_benchmarking::Pallet as OffencesBench;
3992			use pallet_election_provider_support_benchmarking::Pallet as EPSBench;
3993			use frame_system_benchmarking::Pallet as SystemBench;
3994			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
3995			use baseline::Pallet as BaselineBench;
3996			use pallet_nomination_pools_benchmarking::Pallet as NominationPoolsBench;
3997
3998			impl pallet_session_benchmarking::Config for Runtime {
3999				fn generate_session_keys_and_proof(owner: Self::AccountId) -> (Self::Keys, Vec<u8>) {
4000					let keys = SessionKeys::generate(&owner.encode(), None);
4001					(keys.keys, keys.proof.encode())
4002				}
4003			}
4004			impl pallet_offences_benchmarking::Config for Runtime {}
4005			impl pallet_election_provider_support_benchmarking::Config for Runtime {}
4006			impl frame_system_benchmarking::Config for Runtime {}
4007			impl pallet_transaction_payment::BenchmarkConfig for Runtime {}
4008			impl baseline::Config for Runtime {}
4009			impl pallet_nomination_pools_benchmarking::Config for Runtime {}
4010
4011			use frame_support::traits::WhitelistedStorageKeys;
4012			let mut whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
4013
4014			// Treasury Account
4015			// TODO: this is manual for now, someday we might be able to use a
4016			// macro for this particular key
4017			let treasury_key = frame_system::Account::<Runtime>::hashed_key_for(Treasury::account_id());
4018			whitelist.push(treasury_key.to_vec().into());
4019
4020			let mut batches = Vec::<BenchmarkBatch>::new();
4021			let params = (&config, &whitelist);
4022			add_benchmarks!(params, batches);
4023			Ok(batches)
4024		}
4025	}
4026
4027	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
4028		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
4029			build_state::<RuntimeGenesisConfig>(config)
4030		}
4031
4032		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
4033			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
4034		}
4035
4036		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
4037			genesis_config_presets::preset_names()
4038		}
4039	}
4040
4041);
4042
4043#[cfg(test)]
4044mod tests {
4045	use super::*;
4046	use frame_system::offchain::CreateSignedTransaction;
4047
4048	#[test]
4049	fn validate_transaction_submitter_bounds() {
4050		fn is_submit_signed_transaction<T>()
4051		where
4052			T: CreateSignedTransaction<RuntimeCall>,
4053		{
4054		}
4055
4056		is_submit_signed_transaction::<Runtime>();
4057	}
4058
4059	#[test]
4060	fn call_size() {
4061		let size = core::mem::size_of::<RuntimeCall>();
4062		assert!(
4063			size <= CALL_PARAMS_MAX_SIZE,
4064			"size of RuntimeCall {} is more than {CALL_PARAMS_MAX_SIZE} bytes.
4065			 Some calls have too big arguments, use Box to reduce the size of RuntimeCall.
4066			 If the limit is too strong, maybe consider increase the limit.",
4067			size,
4068		);
4069	}
4070}