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