1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! The Moonbeam Runtime.
18
//!
19
//! Primary features of this runtime include:
20
//! * Ethereum compatibility
21
//! * Moonbeam tokenomics
22

            
23
#![cfg_attr(not(feature = "std"), no_std)]
24
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 512.
25
#![recursion_limit = "512"]
26

            
27
// Make the WASM binary available.
28
#[cfg(feature = "std")]
29
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
30

            
31
extern crate alloc;
32

            
33
use account::AccountId20;
34
use alloc::borrow::Cow;
35
use cumulus_pallet_parachain_system::{
36
	RelayChainStateProof, RelayStateProof, RelaychainDataProvider, ValidationData,
37
};
38
use fp_rpc::TransactionStatus;
39

            
40
use cumulus_primitives_core::{relay_chain, AggregateMessageOrigin};
41
#[cfg(feature = "std")]
42
pub use fp_evm::GenesisAccount;
43
pub use frame_support::traits::Get;
44
use frame_support::{
45
	construct_runtime,
46
	dispatch::{DispatchClass, GetDispatchInfo, PostDispatchInfo},
47
	ensure,
48
	pallet_prelude::DispatchResult,
49
	parameter_types,
50
	traits::{
51
		fungible::{Balanced, Credit, HoldConsideration, Inspect, NativeOrWithId},
52
		ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, EitherOf,
53
		EitherOfDiverse, EqualPrivilegeOnly, InstanceFilter, LinearStoragePrice, OnFinalize,
54
		OnUnbalanced,
55
	},
56
	weights::{
57
		constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, Weight, WeightToFeeCoefficient,
58
		WeightToFeeCoefficients, WeightToFeePolynomial,
59
	},
60
	PalletId,
61
};
62
use frame_system::{EnsureRoot, EnsureSigned};
63
pub use moonbeam_core_primitives::{
64
	AccountId, AccountIndex, Address, AssetId, Balance, BlockNumber, DigestItem, Hash, Header,
65
	Index, Signature,
66
};
67
use moonbeam_rpc_primitives_txpool::TxPoolResponse;
68
use moonbeam_runtime_common::{
69
	impl_asset_conversion::AssetRateConverter,
70
	impl_multiasset_paymaster::MultiAssetPaymaster,
71
	timestamp::{ConsensusHookWrapperForRelayTimestamp, RelayTimestamp},
72
};
73
pub use pallet_author_slot_filter::EligibilityValue;
74
use pallet_ethereum::Call::transact;
75
use pallet_ethereum::{PostLogContent, Transaction as EthereumTransaction};
76
use pallet_evm::{
77
	Account as EVMAccount, EVMFungibleAdapter, EnsureAddressNever, EnsureAddressRoot,
78
	FeeCalculator, FrameSystemAccountProvider, GasWeightMapping, IdentityAddressMapping,
79
	OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner,
80
};
81
pub use pallet_parachain_staking::{weights::WeightInfo, InflationInfo, Range};
82
use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment};
83
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
84
use scale_info::TypeInfo;
85
use serde::{Deserialize, Serialize};
86
use smallvec::smallvec;
87
use sp_api::impl_runtime_apis;
88
use sp_consensus_slots::Slot;
89
use sp_core::{OpaqueMetadata, H160, H256, U256};
90
use sp_runtime::generic::Preamble;
91
use sp_runtime::{
92
	generic, impl_opaque_keys,
93
	traits::{
94
		BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, IdentityLookup,
95
		PostDispatchInfoOf, UniqueSaturatedInto, Zero,
96
	},
97
	transaction_validity::{
98
		InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
99
	},
100
	ApplyExtrinsicResult, DispatchErrorWithPostInfo, FixedPointNumber, Perbill, Permill,
101
	Perquintill, SaturatedConversion,
102
};
103
use sp_std::{convert::TryFrom, prelude::*};
104
use xcm::{
105
	Version as XcmVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
106
};
107
use xcm_runtime_apis::{
108
	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
109
	fees::Error as XcmPaymentApiError,
110
};
111

            
112
use runtime_params::*;
113

            
114
#[cfg(feature = "std")]
115
use sp_version::NativeVersion;
116
use sp_version::RuntimeVersion;
117

            
118
use nimbus_primitives::CanAuthor;
119

            
120
mod migrations;
121
mod precompiles;
122
pub use precompiles::{
123
	MoonbeamPrecompiles, PrecompileName, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
124
};
125

            
126
#[cfg(any(feature = "std", test))]
127
pub use sp_runtime::BuildStorage;
128

            
129
pub type Precompiles = MoonbeamPrecompiles<Runtime>;
130

            
131
pub mod asset_config;
132
#[cfg(not(feature = "disable-genesis-builder"))]
133
pub mod genesis_config_preset;
134
pub mod governance;
135
pub mod runtime_params;
136
mod weights;
137
pub mod xcm_config;
138

            
139
use governance::councils::*;
140
pub(crate) use weights as moonbeam_weights;
141

            
142
/// GLMR, the native token, uses 18 decimals of precision.
143
pub mod currency {
144
	use super::Balance;
145

            
146
	// Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
147
	pub const SUPPLY_FACTOR: Balance = 100;
148

            
149
	pub const WEI: Balance = 1;
150
	pub const KILOWEI: Balance = 1_000;
151
	pub const MEGAWEI: Balance = 1_000_000;
152
	pub const GIGAWEI: Balance = 1_000_000_000;
153
	pub const MICROGLMR: Balance = 1_000_000_000_000;
154
	pub const MILLIGLMR: Balance = 1_000_000_000_000_000;
155
	pub const GLMR: Balance = 1_000_000_000_000_000_000;
156
	pub const KILOGLMR: Balance = 1_000_000_000_000_000_000_000;
157

            
158
	pub const TRANSACTION_BYTE_FEE: Balance = 1 * GIGAWEI * SUPPLY_FACTOR;
159
	pub const STORAGE_BYTE_FEE: Balance = 100 * MICROGLMR * SUPPLY_FACTOR;
160
	pub const WEIGHT_FEE: Balance = 50 * KILOWEI * SUPPLY_FACTOR / 4;
161

            
162
24
	pub const fn deposit(items: u32, bytes: u32) -> Balance {
163
24
		items as Balance * 100 * MILLIGLMR * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
164
24
	}
165
}
166

            
167
/// Maximum PoV size we support right now.
168
// Reference: https://github.com/polkadot-fellows/runtimes/pull/553
169
pub const MAX_POV_SIZE: u32 = 10 * 1024 * 1024;
170

            
171
/// Maximum weight per block
172
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
173
	WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
174
	MAX_POV_SIZE as u64,
175
);
176

            
177
pub const MILLISECS_PER_BLOCK: u64 = 6_000;
178
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
179
pub const HOURS: BlockNumber = MINUTES * 60;
180
pub const DAYS: BlockNumber = HOURS * 24;
181
pub const WEEKS: BlockNumber = DAYS * 7;
182
pub const MONTHS: BlockNumber = DAYS * 30;
183
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
184
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
185
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
186
/// to even the core datastructures.
187
pub mod opaque {
188
	use super::*;
189

            
190
	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
191
	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
192

            
193
	impl_opaque_keys! {
194
		pub struct SessionKeys {
195
			pub nimbus: AuthorInherent,
196
			pub vrf: session_keys_primitives::VrfSessionKey,
197
		}
198
	}
199
}
200

            
201
/// This runtime version.
202
/// The spec_version is composed of 2x2 digits. The first 2 digits represent major changes
203
/// that can't be skipped, such as data migration upgrades. The last 2 digits represent minor
204
/// changes which can be skipped.
205
#[sp_version::runtime_version]
206
pub const VERSION: RuntimeVersion = RuntimeVersion {
207
	spec_name: Cow::Borrowed("moonbeam"),
208
	impl_name: Cow::Borrowed("moonbeam"),
209
	authoring_version: 3,
210
	spec_version: 3800,
211
	impl_version: 0,
212
	apis: RUNTIME_API_VERSIONS,
213
	transaction_version: 3,
214
	system_version: 1,
215
};
216

            
217
/// The version information used to identify this runtime when compiled natively.
218
#[cfg(feature = "std")]
219
pub fn native_version() -> NativeVersion {
220
	NativeVersion {
221
		runtime_version: VERSION,
222
		can_author_with: Default::default(),
223
	}
224
}
225

            
226
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
227
pub const NORMAL_WEIGHT: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_mul(3).saturating_div(4);
228
// Here we assume Ethereum's base fee of 21000 gas and convert to weight, but we
229
// subtract roughly the cost of a balance transfer from it (about 1/3 the cost)
230
// and some cost to account for per-byte-fee.
231
// TODO: we should use benchmarking's overhead feature to measure this
232
pub const EXTRINSIC_BASE_WEIGHT: Weight = Weight::from_parts(10000 * WEIGHT_PER_GAS, 0);
233

            
234
pub struct RuntimeBlockWeights;
235
impl Get<frame_system::limits::BlockWeights> for RuntimeBlockWeights {
236
361016
	fn get() -> frame_system::limits::BlockWeights {
237
361016
		frame_system::limits::BlockWeights::builder()
238
361016
			.for_class(DispatchClass::Normal, |weights| {
239
361016
				weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT;
240
361016
				weights.max_total = NORMAL_WEIGHT.into();
241
361016
			})
242
361016
			.for_class(DispatchClass::Operational, |weights| {
243
361016
				weights.max_total = MAXIMUM_BLOCK_WEIGHT.into();
244
361016
				weights.reserved = (MAXIMUM_BLOCK_WEIGHT - NORMAL_WEIGHT).into();
245
361016
			})
246
361016
			.avg_block_initialization(Perbill::from_percent(10))
247
361016
			.build()
248
361016
			.expect("Provided BlockWeight definitions are valid, qed")
249
361016
	}
250
}
251

            
252
parameter_types! {
253
	pub const Version: RuntimeVersion = VERSION;
254
	/// We allow for 5 MB blocks.
255
	pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
256
		::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
257
}
258

            
259
impl frame_system::Config for Runtime {
260
	/// The identifier used to distinguish between accounts.
261
	type AccountId = AccountId;
262
	/// The aggregated dispatch type that is available for extrinsics.
263
	type RuntimeCall = RuntimeCall;
264
	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
265
	type Lookup = IdentityLookup<AccountId>;
266
	/// The index type for storing how many extrinsics an account has signed.
267
	type Nonce = Index;
268
	/// The index type for blocks.
269
	type Block = Block;
270
	/// The type for hashing blocks and tries.
271
	type Hash = Hash;
272
	/// The hashing algorithm used.
273
	type Hashing = BlakeTwo256;
274
	/// The ubiquitous event type.
275
	type RuntimeEvent = RuntimeEvent;
276
	/// The ubiquitous origin type.
277
	type RuntimeOrigin = RuntimeOrigin;
278
	/// The aggregated RuntimeTask type.
279
	type RuntimeTask = RuntimeTask;
280
	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
281
	type BlockHashCount = ConstU32<256>;
282
	/// Maximum weight of each block. With a default weight system of 1byte == 1weight, 4mb is ok.
283
	type BlockWeights = RuntimeBlockWeights;
284
	/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.
285
	type BlockLength = BlockLength;
286
	/// Runtime version.
287
	type Version = Version;
288
	type PalletInfo = PalletInfo;
289
	type AccountData = pallet_balances::AccountData<Balance>;
290
	type OnNewAccount = ();
291
	type OnKilledAccount = ();
292
	type DbWeight = moonbeam_weights::db::rocksdb::constants::RocksDbWeight;
293
	type BaseCallFilter = MaintenanceMode;
294
	type SystemWeightInfo = moonbeam_weights::frame_system::WeightInfo<Runtime>;
295
	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
296
	type SS58Prefix = ConstU16<1284>;
297
	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
298
	type MaxConsumers = frame_support::traits::ConstU32<16>;
299
	type SingleBlockMigrations = ();
300
	type MultiBlockMigrator = MultiBlockMigrations;
301
	type PreInherents = ();
302
	type PostInherents = ();
303
	type PostTransactions = ();
304
	type ExtensionsWeightInfo = moonbeam_weights::frame_system_extensions::WeightInfo<Runtime>;
305
}
306

            
307
impl pallet_utility::Config for Runtime {
308
	type RuntimeEvent = RuntimeEvent;
309
	type RuntimeCall = RuntimeCall;
310
	type PalletsOrigin = OriginCaller;
311
	type WeightInfo = moonbeam_weights::pallet_utility::WeightInfo<Runtime>;
312
}
313

            
314
impl pallet_timestamp::Config for Runtime {
315
	/// A timestamp: milliseconds since the unix epoch.
316
	type Moment = u64;
317
	type OnTimestampSet = ();
318
	type MinimumPeriod = ConstU64<3000>;
319
	type WeightInfo = moonbeam_weights::pallet_timestamp::WeightInfo<Runtime>;
320
}
321

            
322
#[cfg(not(feature = "runtime-benchmarks"))]
323
parameter_types! {
324
	pub const ExistentialDeposit: Balance = 0;
325
}
326

            
327
#[cfg(feature = "runtime-benchmarks")]
328
parameter_types! {
329
	pub const ExistentialDeposit: Balance = 1;
330
}
331

            
332
impl pallet_balances::Config for Runtime {
333
	type MaxReserves = ConstU32<50>;
334
	type ReserveIdentifier = [u8; 4];
335
	type MaxLocks = ConstU32<50>;
336
	/// The type for recording an account's balance.
337
	type Balance = Balance;
338
	/// The ubiquitous event type.
339
	type RuntimeEvent = RuntimeEvent;
340
	type DustRemoval = ();
341
	type ExistentialDeposit = ExistentialDeposit;
342
	type AccountStore = System;
343
	type FreezeIdentifier = ();
344
	type MaxFreezes = ConstU32<0>;
345
	type RuntimeHoldReason = RuntimeHoldReason;
346
	type RuntimeFreezeReason = RuntimeFreezeReason;
347
	type WeightInfo = moonbeam_weights::pallet_balances::WeightInfo<Runtime>;
348
	type DoneSlashHandler = ();
349
}
350

            
351
pub struct LengthToFee;
352
impl WeightToFeePolynomial for LengthToFee {
353
	type Balance = Balance;
354

            
355
66
	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
356
66
		smallvec![
357
			WeightToFeeCoefficient {
358
				degree: 1,
359
				coeff_frac: Perbill::zero(),
360
				coeff_integer: currency::TRANSACTION_BYTE_FEE,
361
				negative: false,
362
			},
363
			WeightToFeeCoefficient {
364
				degree: 3,
365
				coeff_frac: Perbill::zero(),
366
				coeff_integer: 1 * currency::SUPPLY_FACTOR,
367
				negative: false,
368
			},
369
		]
370
66
	}
371
}
372

            
373
impl pallet_transaction_payment::Config for Runtime {
374
	type RuntimeEvent = RuntimeEvent;
375
	type OnChargeTransaction = FungibleAdapter<
376
		Balances,
377
		DealWithSubstrateFeesAndTip<
378
			Runtime,
379
			dynamic_params::runtime_config::FeesTreasuryProportion,
380
		>,
381
	>;
382
	type OperationalFeeMultiplier = ConstU8<5>;
383
	type WeightToFee = ConstantMultiplier<Balance, ConstU128<{ currency::WEIGHT_FEE }>>;
384
	type LengthToFee = LengthToFee;
385
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime>;
386
	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
387
}
388

            
389
impl pallet_evm_chain_id::Config for Runtime {}
390

            
391
/// Current approximation of the gas/s consumption considering
392
/// EVM execution over compiled WASM (on 4.4Ghz CPU).
393
/// Given the 2000ms Weight, from which 75% only are used for transactions,
394
/// the total EVM execution gas limit is: GAS_PER_SECOND * 2 * 0.75 ~= 60_000_000.
395
pub const GAS_PER_SECOND: u64 = 40_000_000;
396

            
397
/// Approximate ratio of the amount of Weight per Gas.
398
/// u64 works for approximations because Weight is a very small unit compared to gas.
399
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
400

            
401
/// The highest amount of new storage that can be created in a block (160KB).
402
/// Originally 40KB, then multiplied by 4 when the block deadline was increased from 500ms to 2000ms.
403
/// Reference: https://github.com/moonbeam-foundation/moonbeam/blob/master/MBIPS/MBIP-5.md#specification
404
pub const BLOCK_STORAGE_LIMIT: u64 = 160 * 1024;
405

            
406
parameter_types! {
407
	pub BlockGasLimit: U256
408
		= U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
409
	/// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less
410
	/// than this will decrease the weight and more will increase.
411
	pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(35);
412
	/// The adjustment variable of the runtime. Higher values will cause `TargetBlockFullness` to
413
	/// change the fees more rapidly. This low value causes changes to occur slowly over time.
414
	pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(4, 1_000);
415
	/// Minimum amount of the multiplier. This value cannot be too low. A test case should ensure
416
	/// that combined with `AdjustmentVariable`, we can recover from the minimum.
417
	/// See `multiplier_can_grow_from_zero` in integration_tests.rs.
418
	/// This value is currently only used by pallet-transaction-payment as an assertion that the
419
	/// next multiplier is always > min value.
420
	pub MinimumMultiplier: Multiplier = Multiplier::from(1u128);
421
	/// Maximum multiplier. We pick a value that is expensive but not impossibly so; it should act
422
	/// as a safety net.
423
	pub MaximumMultiplier: Multiplier = Multiplier::from(100_000u128);
424
	pub PrecompilesValue: MoonbeamPrecompiles<Runtime> = MoonbeamPrecompiles::<_>::new();
425
	pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
426
	/// The amount of gas per pov. A ratio of 8 if we convert ref_time to gas and we compare
427
	/// it with the pov_size for a block. E.g.
428
	/// ceil(
429
	///     (max_extrinsic.ref_time() / max_extrinsic.proof_size()) / WEIGHT_PER_GAS
430
	/// )
431
	/// We should re-check `xcm_config::Erc20XcmBridgeTransferGasLimit` when changing this value
432
	pub const GasLimitPovSizeRatio: u64 = 8;
433
	/// The amount of gas per storage (in bytes): BLOCK_GAS_LIMIT / BLOCK_STORAGE_LIMIT
434
	/// The current definition of BLOCK_STORAGE_LIMIT is 160 KB, resulting in a value of 366.
435
	pub GasLimitStorageGrowthRatio: u64 = 366;
436
}
437

            
438
pub struct TransactionPaymentAsGasPrice;
439
impl FeeCalculator for TransactionPaymentAsGasPrice {
440
372
	fn min_gas_price() -> (U256, Weight) {
441
372
		// note: transaction-payment differs from EIP-1559 in that its tip and length fees are not
442
372
		//       scaled by the multiplier, which means its multiplier will be overstated when
443
372
		//       applied to an ethereum transaction
444
372
		// note: transaction-payment uses both a congestion modifier (next_fee_multiplier, which is
445
372
		//       updated once per block in on_finalize) and a 'WeightToFee' implementation. Our
446
372
		//       runtime implements this as a 'ConstantModifier', so we can get away with a simple
447
372
		//       multiplication here.
448
372
		// It is imperative that `saturating_mul_int` be performed as late as possible in the
449
372
		// expression since it involves fixed point multiplication with a division by a fixed
450
372
		// divisor. This leads to truncation and subsequent precision loss if performed too early.
451
372
		// This can lead to min_gas_price being same across blocks even if the multiplier changes.
452
372
		// There's still some precision loss when the final `gas_price` (used_gas * min_gas_price)
453
372
		// is computed in frontier, but that's currently unavoidable.
454
372
		let min_gas_price = TransactionPayment::next_fee_multiplier()
455
372
			.saturating_mul_int((currency::WEIGHT_FEE).saturating_mul(WEIGHT_PER_GAS as u128));
456
372
		(
457
372
			min_gas_price.into(),
458
372
			<Runtime as frame_system::Config>::DbWeight::get().reads(1),
459
372
		)
460
372
	}
461
}
462

            
463
/// Parameterized slow adjusting fee updated based on
464
/// https://w3f-research.readthedocs.io/en/latest/polkadot/overview/2-token-economics.html#-2.-slow-adjusting-mechanism // editorconfig-checker-disable-line
465
///
466
/// The adjustment algorithm boils down to:
467
///
468
/// diff = (previous_block_weight - target) / maximum_block_weight
469
/// next_multiplier = prev_multiplier * (1 + (v * diff) + ((v * diff)^2 / 2))
470
/// assert(next_multiplier > min)
471
///     where: v is AdjustmentVariable
472
///            target is TargetBlockFullness
473
///            min is MinimumMultiplier
474
pub type SlowAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
475
	R,
476
	TargetBlockFullness,
477
	AdjustmentVariable,
478
	MinimumMultiplier,
479
	MaximumMultiplier,
480
>;
481

            
482
use frame_support::traits::FindAuthor;
483
//TODO It feels like this shold be able to work for any T: H160, but I tried for
484
// embarassingly long and couldn't figure that out.
485

            
486
/// The author inherent provides a AccountId20, but pallet evm needs an H160.
487
/// This simple adapter makes the conversion.
488
pub struct FindAuthorAdapter<Inner>(sp_std::marker::PhantomData<Inner>);
489

            
490
impl<Inner> FindAuthor<H160> for FindAuthorAdapter<Inner>
491
where
492
	Inner: FindAuthor<AccountId20>,
493
{
494
16413
	fn find_author<'a, I>(digests: I) -> Option<H160>
495
16413
	where
496
16413
		I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
497
16413
	{
498
16413
		Inner::find_author(digests).map(Into::into)
499
16413
	}
500
}
501

            
502
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
503

            
504
impl pallet_evm::Config for Runtime {
505
	type FeeCalculator = TransactionPaymentAsGasPrice;
506
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
507
	type WeightPerGas = WeightPerGas;
508
	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
509
	type CallOrigin = EnsureAddressRoot<AccountId>;
510
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
511
	type AddressMapping = IdentityAddressMapping;
512
	type Currency = Balances;
513
	type RuntimeEvent = RuntimeEvent;
514
	type Runner = pallet_evm::runner::stack::Runner<Self>;
515
	type PrecompilesType = MoonbeamPrecompiles<Self>;
516
	type PrecompilesValue = PrecompilesValue;
517
	type ChainId = EthereumChainId;
518
	type OnChargeTransaction = OnChargeEVMTransaction<
519
		DealWithEthereumBaseFees<Runtime, dynamic_params::runtime_config::FeesTreasuryProportion>,
520
		DealWithEthereumPriorityFees<Runtime>,
521
	>;
522
	type BlockGasLimit = BlockGasLimit;
523
	type FindAuthor = FindAuthorAdapter<AuthorInherent>;
524
	type OnCreate = ();
525
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
526
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
527
	type Timestamp = RelayTimestamp;
528
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
529
	type WeightInfo = moonbeam_weights::pallet_evm::WeightInfo<Runtime>;
530
}
531

            
532
parameter_types! {
533
	pub MaxServiceWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
534
}
535

            
536
impl pallet_scheduler::Config for Runtime {
537
	type RuntimeEvent = RuntimeEvent;
538
	type RuntimeOrigin = RuntimeOrigin;
539
	type PalletsOrigin = OriginCaller;
540
	type RuntimeCall = RuntimeCall;
541
	type MaximumWeight = MaxServiceWeight;
542
	type ScheduleOrigin = EnsureRoot<AccountId>;
543
	type MaxScheduledPerBlock = ConstU32<50>;
544
	type WeightInfo = moonbeam_weights::pallet_scheduler::WeightInfo<Runtime>;
545
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
546
	type Preimages = Preimage;
547
}
548

            
549
parameter_types! {
550
	pub const PreimageBaseDeposit: Balance = 5 * currency::GLMR * currency::SUPPLY_FACTOR ;
551
	pub const PreimageByteDeposit: Balance = currency::STORAGE_BYTE_FEE;
552
	pub const PreimageHoldReason: RuntimeHoldReason =
553
		RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
554
}
555

            
556
impl pallet_preimage::Config for Runtime {
557
	type WeightInfo = moonbeam_weights::pallet_preimage::WeightInfo<Runtime>;
558
	type RuntimeEvent = RuntimeEvent;
559
	type Currency = Balances;
560
	type ManagerOrigin = EnsureRoot<AccountId>;
561
	type Consideration = HoldConsideration<
562
		AccountId,
563
		Balances,
564
		PreimageHoldReason,
565
		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
566
	>;
567
}
568

            
569
parameter_types! {
570
	pub const ProposalBond: Permill = Permill::from_percent(5);
571
	pub const TreasuryId: PalletId = PalletId(*b"py/trsry");
572
	pub TreasuryAccount: AccountId = Treasury::account_id();
573
	pub const MaxSpendBalance: crate::Balance = crate::Balance::max_value();
574
}
575

            
576
type RootOrTreasuryCouncilOrigin = EitherOfDiverse<
577
	EnsureRoot<AccountId>,
578
	pallet_collective::EnsureProportionMoreThan<AccountId, TreasuryCouncilInstance, 1, 2>,
579
>;
580

            
581
impl pallet_treasury::Config for Runtime {
582
	type PalletId = TreasuryId;
583
	type Currency = Balances;
584
	// More than half of the council is required (or root) to reject a proposal
585
	type RejectOrigin = RootOrTreasuryCouncilOrigin;
586
	type RuntimeEvent = RuntimeEvent;
587
	type SpendPeriod = ConstU32<{ 6 * DAYS }>;
588
	type Burn = ();
589
	type BurnDestination = ();
590
	type MaxApprovals = ConstU32<100>;
591
	type WeightInfo = moonbeam_weights::pallet_treasury::WeightInfo<Runtime>;
592
	type SpendFunds = ();
593
	type SpendOrigin =
594
		frame_system::EnsureWithSuccess<RootOrTreasuryCouncilOrigin, AccountId, MaxSpendBalance>;
595
	type AssetKind = NativeOrWithId<AssetId>;
596
	type Beneficiary = AccountId;
597
	type BeneficiaryLookup = IdentityLookup<AccountId>;
598
	type Paymaster = MultiAssetPaymaster<Runtime, TreasuryAccount, Balances>;
599
	type BalanceConverter = AssetRateConverter<Runtime, Balances>;
600
	type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
601
	#[cfg(feature = "runtime-benchmarks")]
602
	type BenchmarkHelper = BenchmarkHelper;
603
	type BlockNumberProvider = System;
604
}
605

            
606
parameter_types! {
607
	pub const MaxSubAccounts: u32 = 100;
608
	pub const MaxAdditionalFields: u32 = 100;
609
	pub const MaxRegistrars: u32 = 20;
610
	pub const PendingUsernameExpiration: u32 = 7 * DAYS;
611
	pub const MaxSuffixLength: u32 = 7;
612
	pub const MaxUsernameLength: u32 = 32;
613
}
614

            
615
type IdentityForceOrigin =
616
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
617
type IdentityRegistrarOrigin =
618
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
619

            
620
impl pallet_identity::Config for Runtime {
621
	type RuntimeEvent = RuntimeEvent;
622
	type Currency = Balances;
623
	// Add one item in storage and take 258 bytes
624
	type BasicDeposit = ConstU128<{ currency::deposit(1, 258) }>;
625
	// Does not add any item to the storage but takes 1 bytes
626
	type ByteDeposit = ConstU128<{ currency::deposit(0, 1) }>;
627
	// Add one item in storage and take 53 bytes
628
	type SubAccountDeposit = ConstU128<{ currency::deposit(1, 53) }>;
629
	type MaxSubAccounts = MaxSubAccounts;
630
	type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
631
	type MaxRegistrars = MaxRegistrars;
632
	type Slashed = Treasury;
633
	type ForceOrigin = IdentityForceOrigin;
634
	type RegistrarOrigin = IdentityRegistrarOrigin;
635
	type OffchainSignature = Signature;
636
	type SigningPublicKey = <Signature as sp_runtime::traits::Verify>::Signer;
637
	type UsernameAuthorityOrigin = EnsureRoot<AccountId>;
638
	type PendingUsernameExpiration = PendingUsernameExpiration;
639
	type MaxSuffixLength = MaxSuffixLength;
640
	type MaxUsernameLength = MaxUsernameLength;
641
	type WeightInfo = moonbeam_weights::pallet_identity::WeightInfo<Runtime>;
642
	type UsernameDeposit = ConstU128<{ currency::deposit(0, MaxUsernameLength::get()) }>;
643
	type UsernameGracePeriod = ConstU32<{ 30 * DAYS }>;
644
}
645

            
646
pub struct TransactionConverter;
647

            
648
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
649
21
	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
650
21
		UncheckedExtrinsic::new_bare(
651
21
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
652
21
		)
653
21
	}
654
}
655

            
656
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
657
	fn convert_transaction(
658
		&self,
659
		transaction: pallet_ethereum::Transaction,
660
	) -> opaque::UncheckedExtrinsic {
661
		let extrinsic = UncheckedExtrinsic::new_bare(
662
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
663
		);
664
		let encoded = extrinsic.encode();
665
		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
666
			.expect("Encoded extrinsic is always valid")
667
	}
668
}
669

            
670
parameter_types! {
671
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
672
}
673

            
674
impl pallet_ethereum::Config for Runtime {
675
	type RuntimeEvent = RuntimeEvent;
676
	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
677
	type PostLogContent = PostBlockAndTxnHashes;
678
	type ExtraDataLength = ConstU32<30>;
679
}
680

            
681
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
682
/// into the relay chain.
683
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
684
/// How many parachain blocks are processed by the relay chain per parent. Limits the
685
/// number of blocks authored per slot.
686
const BLOCK_PROCESSING_VELOCITY: u32 = 1;
687

            
688
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
689
	Runtime,
690
	BLOCK_PROCESSING_VELOCITY,
691
	UNINCLUDED_SEGMENT_CAPACITY,
692
>;
693

            
694
impl cumulus_pallet_parachain_system::Config for Runtime {
695
	type RuntimeEvent = RuntimeEvent;
696
	type OnSystemEvent = ();
697
	type SelfParaId = ParachainInfo;
698
	type ReservedDmpWeight = ReservedDmpWeight;
699
	type OutboundXcmpMessageSource = XcmpQueue;
700
	type XcmpMessageHandler = XcmpQueue;
701
	type ReservedXcmpWeight = ReservedXcmpWeight;
702
	type CheckAssociatedRelayNumber = EmergencyParaXcm;
703
	type ConsensusHook = ConsensusHookWrapperForRelayTimestamp<Runtime, ConsensusHook>;
704
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
705
	type WeightInfo = moonbeam_weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
706
	type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
707
}
708

            
709
pub struct EthereumXcmEnsureProxy;
710
impl xcm_primitives::EnsureProxy<AccountId> for EthereumXcmEnsureProxy {
711
	fn ensure_ok(delegator: AccountId, delegatee: AccountId) -> Result<(), &'static str> {
712
		// The EVM implicitely contains an Any proxy, so we only allow for "Any" proxies
713
		let def: pallet_proxy::ProxyDefinition<AccountId, ProxyType, BlockNumber> =
714
			pallet_proxy::Pallet::<Runtime>::find_proxy(
715
				&delegator,
716
				&delegatee,
717
				Some(ProxyType::Any),
718
			)
719
			.map_err(|_| "proxy error: expected `ProxyType::Any`")?;
720
		// We only allow to use it for delay zero proxies, as the call will immediatly be executed
721
		ensure!(def.delay.is_zero(), "proxy delay is Non-zero`");
722
		Ok(())
723
	}
724
}
725

            
726
impl pallet_ethereum_xcm::Config for Runtime {
727
	type RuntimeEvent = RuntimeEvent;
728
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
729
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
730
	type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
731
	type ReservedXcmpWeight = ReservedXcmpWeight;
732
	type EnsureProxy = EthereumXcmEnsureProxy;
733
	type ControllerOrigin = EnsureRoot<AccountId>;
734
	type ForceOrigin = EnsureRoot<AccountId>;
735
}
736

            
737
parameter_types! {
738
	// Reserved weight is 1/4 of MAXIMUM_BLOCK_WEIGHT
739
	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
740
	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
741
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
742
}
743

            
744
impl parachain_info::Config for Runtime {}
745

            
746
pub struct OnNewRound;
747
impl pallet_parachain_staking::OnNewRound for OnNewRound {
748
24
	fn on_new_round(round_index: pallet_parachain_staking::RoundIndex) -> Weight {
749
24
		MoonbeamOrbiters::on_new_round(round_index)
750
24
	}
751
}
752
pub struct PayoutCollatorOrOrbiterReward;
753
impl pallet_parachain_staking::PayoutCollatorReward<Runtime> for PayoutCollatorOrOrbiterReward {
754
12
	fn payout_collator_reward(
755
12
		for_round: pallet_parachain_staking::RoundIndex,
756
12
		collator_id: AccountId,
757
12
		amount: Balance,
758
12
	) -> Weight {
759
12
		let extra_weight =
760
12
			if MoonbeamOrbiters::is_collator_pool_with_active_orbiter(for_round, collator_id) {
761
				MoonbeamOrbiters::distribute_rewards(for_round, collator_id, amount)
762
			} else {
763
12
				ParachainStaking::mint_collator_reward(for_round, collator_id, amount)
764
			};
765

            
766
12
		<Runtime as frame_system::Config>::DbWeight::get()
767
12
			.reads(1)
768
12
			.saturating_add(extra_weight)
769
12
	}
770
}
771

            
772
pub struct OnInactiveCollator;
773
impl pallet_parachain_staking::OnInactiveCollator<Runtime> for OnInactiveCollator {
774
	fn on_inactive_collator(
775
		collator_id: AccountId,
776
		round: pallet_parachain_staking::RoundIndex,
777
	) -> Result<Weight, DispatchErrorWithPostInfo<PostDispatchInfo>> {
778
		let extra_weight = if !MoonbeamOrbiters::is_collator_pool_with_active_orbiter(
779
			round,
780
			collator_id.clone(),
781
		) {
782
			ParachainStaking::go_offline_inner(collator_id)?;
783
			<Runtime as pallet_parachain_staking::Config>::WeightInfo::go_offline(
784
				pallet_parachain_staking::MAX_CANDIDATES,
785
			)
786
		} else {
787
			Weight::zero()
788
		};
789

            
790
		Ok(<Runtime as frame_system::Config>::DbWeight::get()
791
			.reads(1)
792
			.saturating_add(extra_weight))
793
	}
794
}
795
type MonetaryGovernanceOrigin =
796
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
797

            
798
pub struct RelayChainSlotProvider;
799
impl Get<Slot> for RelayChainSlotProvider {
800
24
	fn get() -> Slot {
801
24
		let slot_info = pallet_async_backing::pallet::Pallet::<Runtime>::slot_info();
802
24
		slot_info.unwrap_or_default().0
803
24
	}
804
}
805

            
806
impl pallet_parachain_staking::Config for Runtime {
807
	type RuntimeEvent = RuntimeEvent;
808
	type Currency = Balances;
809
	type MonetaryGovernanceOrigin = MonetaryGovernanceOrigin;
810
	/// Minimum round length is 2 minutes (10 * 12 second block times)
811
	type MinBlocksPerRound = ConstU32<10>;
812
	/// If a collator doesn't produce any block on this number of rounds, it is notified as inactive
813
	type MaxOfflineRounds = ConstU32<1>;
814
	/// Rounds before the collator leaving the candidates request can be executed
815
	type LeaveCandidatesDelay = ConstU32<{ 4 * 7 }>;
816
	/// Rounds before the candidate bond increase/decrease can be executed
817
	type CandidateBondLessDelay = ConstU32<{ 4 * 7 }>;
818
	/// Rounds before the delegator exit can be executed
819
	type LeaveDelegatorsDelay = ConstU32<{ 4 * 7 }>;
820
	/// Rounds before the delegator revocation can be executed
821
	type RevokeDelegationDelay = ConstU32<{ 4 * 7 }>;
822
	/// Rounds before the delegator bond increase/decrease can be executed
823
	type DelegationBondLessDelay = ConstU32<{ 4 * 7 }>;
824
	/// Rounds before the reward is paid
825
	type RewardPaymentDelay = ConstU32<2>;
826
	/// Minimum collators selected per round, default at genesis and minimum forever after
827
	type MinSelectedCandidates = ConstU32<8>;
828
	/// Maximum top delegations per candidate
829
	type MaxTopDelegationsPerCandidate = ConstU32<300>;
830
	/// Maximum bottom delegations per candidate
831
	type MaxBottomDelegationsPerCandidate = ConstU32<50>;
832
	/// Maximum delegations per delegator
833
	type MaxDelegationsPerDelegator = ConstU32<100>;
834
	/// Minimum stake required to be reserved to be a candidate
835
	type MinCandidateStk = ConstU128<{ 5_000 * currency::GLMR * currency::SUPPLY_FACTOR }>;
836
	/// Minimum stake required to be reserved to be a delegator
837
	type MinDelegation = ConstU128<{ 500 * currency::MILLIGLMR * currency::SUPPLY_FACTOR }>;
838
	type BlockAuthor = AuthorInherent;
839
	type OnCollatorPayout = ();
840
	type PayoutCollatorReward = PayoutCollatorOrOrbiterReward;
841
	type OnInactiveCollator = OnInactiveCollator;
842
	type OnNewRound = OnNewRound;
843
	type SlotProvider = RelayChainSlotProvider;
844
	type WeightInfo = moonbeam_weights::pallet_parachain_staking::WeightInfo<Runtime>;
845
	type MaxCandidates = ConstU32<200>;
846
	type SlotDuration = ConstU64<6_000>;
847
	type BlockTime = ConstU64<6_000>;
848
}
849

            
850
impl pallet_author_inherent::Config for Runtime {
851
	type SlotBeacon = RelaychainDataProvider<Self>;
852
	type AccountLookup = MoonbeamOrbiters;
853
	type CanAuthor = AuthorFilter;
854
	type AuthorId = AccountId;
855
	type WeightInfo = moonbeam_weights::pallet_author_inherent::WeightInfo<Runtime>;
856
}
857

            
858
impl pallet_author_slot_filter::Config for Runtime {
859
	type RuntimeEvent = RuntimeEvent;
860
	type RandomnessSource = Randomness;
861
	type PotentialAuthors = ParachainStaking;
862
	type WeightInfo = moonbeam_weights::pallet_author_slot_filter::WeightInfo<Runtime>;
863
}
864

            
865
impl pallet_async_backing::Config for Runtime {
866
	type AllowMultipleBlocksPerSlot = ConstBool<true>;
867
	type GetAndVerifySlot = pallet_async_backing::RelaySlot;
868
	type ExpectedBlockTime = ConstU64<6000>;
869
}
870

            
871
parameter_types! {
872
	pub const InitializationPayment: Perbill = Perbill::from_percent(30);
873
	pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100);
874
	pub const SignatureNetworkIdentifier:  &'static [u8] = b"moonbeam-";
875
}
876

            
877
impl pallet_crowdloan_rewards::Config for Runtime {
878
	type RuntimeEvent = RuntimeEvent;
879
	type Initialized = ConstBool<false>;
880
	type InitializationPayment = InitializationPayment;
881
	type MaxInitContributors = ConstU32<500>;
882
	type MinimumReward = ConstU128<0>;
883
	type RewardCurrency = Balances;
884
	type RelayChainAccountId = [u8; 32];
885
	type RewardAddressAssociateOrigin = EnsureSigned<Self::AccountId>;
886
	type RewardAddressChangeOrigin = EnsureSigned<Self::AccountId>;
887
	type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold;
888
	type SignatureNetworkIdentifier = SignatureNetworkIdentifier;
889
	type VestingBlockNumber = relay_chain::BlockNumber;
890
	type VestingBlockProvider = RelaychainDataProvider<Self>;
891
	type WeightInfo = moonbeam_weights::pallet_crowdloan_rewards::WeightInfo<Runtime>;
892
}
893

            
894
// This is a simple session key manager. It should probably either work with, or be replaced
895
// entirely by pallet sessions
896
impl pallet_author_mapping::Config for Runtime {
897
	type RuntimeEvent = RuntimeEvent;
898
	type DepositCurrency = Balances;
899
	type DepositAmount = ConstU128<{ 100 * currency::GLMR * currency::SUPPLY_FACTOR }>;
900
	type Keys = session_keys_primitives::VrfId;
901
	type WeightInfo = moonbeam_weights::pallet_author_mapping::WeightInfo<Runtime>;
902
}
903

            
904
/// The type used to represent the kinds of proxying allowed.
905
#[derive(
906
	Copy,
907
	Clone,
908
	Eq,
909
	PartialEq,
910
	Ord,
911
	PartialOrd,
912
	Encode,
913
	Decode,
914
	Debug,
915
6
	MaxEncodedLen,
916
48
	TypeInfo,
917
	Serialize,
918
	Deserialize,
919
)]
920
pub enum ProxyType {
921
	/// All calls can be proxied. This is the trivial/most permissive filter.
922
	Any = 0,
923
	/// Only extrinsics that do not transfer funds.
924
	NonTransfer = 1,
925
	/// Only extrinsics related to governance (democracy and collectives).
926
	Governance = 2,
927
	/// Only extrinsics related to staking.
928
	Staking = 3,
929
	/// Allow to veto an announced proxy call.
930
	CancelProxy = 4,
931
	/// Allow extrinsic related to Balances.
932
	Balances = 5,
933
	/// Allow extrinsic related to AuthorMapping.
934
	AuthorMapping = 6,
935
	/// Allow extrinsic related to IdentityJudgement.
936
	IdentityJudgement = 7,
937
}
938

            
939
impl Default for ProxyType {
940
	fn default() -> Self {
941
		Self::Any
942
	}
943
}
944

            
945
fn is_governance_precompile(precompile_name: &precompiles::PrecompileName) -> bool {
946
	matches!(
947
		precompile_name,
948
		PrecompileName::ConvictionVotingPrecompile
949
			| PrecompileName::PreimagePrecompile
950
			| PrecompileName::ReferendaPrecompile
951
			| PrecompileName::OpenTechCommitteeInstance
952
			| PrecompileName::TreasuryCouncilInstance
953
	)
954
}
955

            
956
// Be careful: Each time this filter is modified, the substrate filter must also be modified
957
// consistently.
958
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
959
	fn is_evm_proxy_call_allowed(
960
		&self,
961
		call: &pallet_evm_precompile_proxy::EvmSubCall,
962
		recipient_has_code: bool,
963
		gas: u64,
964
	) -> precompile_utils::EvmResult<bool> {
965
		Ok(match self {
966
			ProxyType::Any => {
967
				match PrecompileName::from_address(call.to.0) {
968
					// Any precompile that can execute a subcall should be forbidden here,
969
					// to ensure that unauthorized smart contract can't be called
970
					// indirectly.
971
					// To be safe, we only allow the precompiles we need.
972
					Some(
973
						PrecompileName::AuthorMappingPrecompile
974
						| PrecompileName::ParachainStakingPrecompile,
975
					) => true,
976
					Some(ref precompile) if is_governance_precompile(precompile) => true,
977
					// All non-whitelisted precompiles are forbidden
978
					Some(_) => false,
979
					// Allow evm transfer to "simple" account (no code nor precompile)
980
					// For the moment, no smart contract other than precompiles is allowed.
981
					// In the future, we may create a dynamic whitelist to authorize some audited
982
					// smart contracts through governance.
983
					None => {
984
						// If the address is not recognized, allow only evm transfer to "simple"
985
						// accounts (no code nor precompile).
986
						// Note: Checking the presence of the code is not enough because some
987
						// precompiles have no code.
988
						!recipient_has_code
989
							&& !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
990
								call.to.0, gas,
991
							)?
992
					}
993
				}
994
			}
995
			ProxyType::NonTransfer => {
996
				call.value == U256::zero()
997
					&& match PrecompileName::from_address(call.to.0) {
998
						Some(
999
							PrecompileName::AuthorMappingPrecompile
							| PrecompileName::ParachainStakingPrecompile,
						) => true,
						Some(ref precompile) if is_governance_precompile(precompile) => true,
						_ => false,
					}
			}
			ProxyType::Governance => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(ref precompile) if is_governance_precompile(precompile)
					)
			}
			ProxyType::Staking => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(
							PrecompileName::AuthorMappingPrecompile
								| PrecompileName::ParachainStakingPrecompile
						)
					)
			}
			// The proxy precompile does not contain method cancel_proxy
			ProxyType::CancelProxy => false,
			ProxyType::Balances => {
				// Allow only "simple" accounts as recipient (no code nor precompile).
				// Note: Checking the presence of the code is not enough because some precompiles
				// have no code.
				!recipient_has_code
					&& !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
						call.to.0, gas,
					)?
			}
			ProxyType::AuthorMapping => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(PrecompileName::AuthorMappingPrecompile)
					)
			}
			// There is no identity precompile
			ProxyType::IdentityJudgement => false,
		})
	}
}
// Be careful: Each time this filter is modified, the EVM filter must also be modified consistently.
impl InstanceFilter<RuntimeCall> for ProxyType {
	fn filter(&self, c: &RuntimeCall) -> bool {
		match self {
			ProxyType::Any => true,
			ProxyType::NonTransfer => match c {
				RuntimeCall::Identity(
					pallet_identity::Call::add_sub { .. } | pallet_identity::Call::set_subs { .. },
				) => false,
				call => {
					matches!(
						call,
						RuntimeCall::System(..)
							| RuntimeCall::ParachainSystem(..)
							| RuntimeCall::Timestamp(..)
							| RuntimeCall::ParachainStaking(..)
							| RuntimeCall::Referenda(..)
							| RuntimeCall::Preimage(..)
							| RuntimeCall::ConvictionVoting(..)
							| RuntimeCall::TreasuryCouncilCollective(..)
							| RuntimeCall::OpenTechCommitteeCollective(..)
							| RuntimeCall::Utility(..)
							| RuntimeCall::Proxy(..)
							| RuntimeCall::Identity(..)
							| RuntimeCall::AuthorMapping(..)
							| RuntimeCall::CrowdloanRewards(
								pallet_crowdloan_rewards::Call::claim { .. }
							)
					)
				}
			},
			ProxyType::Governance => matches!(
				c,
				RuntimeCall::Referenda(..)
					| RuntimeCall::Preimage(..)
					| RuntimeCall::ConvictionVoting(..)
					| RuntimeCall::TreasuryCouncilCollective(..)
					| RuntimeCall::OpenTechCommitteeCollective(..)
					| RuntimeCall::Utility(..)
			),
			ProxyType::Staking => matches!(
				c,
				RuntimeCall::ParachainStaking(..)
					| RuntimeCall::Utility(..)
					| RuntimeCall::AuthorMapping(..)
					| RuntimeCall::MoonbeamOrbiters(..)
			),
			ProxyType::CancelProxy => matches!(
				c,
				RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
			),
			ProxyType::Balances => {
				matches!(c, RuntimeCall::Balances(..) | RuntimeCall::Utility(..))
			}
			ProxyType::AuthorMapping => matches!(c, RuntimeCall::AuthorMapping(..)),
			ProxyType::IdentityJudgement => matches!(
				c,
				RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
					| RuntimeCall::Utility(..)
			),
		}
	}
	fn is_superset(&self, o: &Self) -> bool {
		match (self, o) {
			(x, y) if x == y => true,
			(ProxyType::Any, _) => true,
			(_, ProxyType::Any) => false,
			_ => false,
		}
	}
}
impl pallet_proxy::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeCall = RuntimeCall;
	type Currency = Balances;
	type ProxyType = ProxyType;
	// One storage item; key size 32, value size 8
	type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
	// Additional storage item size of 21 bytes (20 bytes AccountId + 1 byte sizeof(ProxyType)).
	type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 21) }>;
	type MaxProxies = ConstU32<32>;
	type WeightInfo = moonbeam_weights::pallet_proxy::WeightInfo<Runtime>;
	type MaxPending = ConstU32<32>;
	type CallHasher = BlakeTwo256;
	type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
	// Additional storage item size of 56 bytes:
	// - 20 bytes AccountId
	// - 32 bytes Hasher (Blake2256)
	// - 4 bytes BlockNumber (u32)
	type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 56) }>;
}
impl pallet_migrations::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type MigrationsList = (
		moonbeam_runtime_common::migrations::CommonMigrations<Runtime>,
		migrations::MoonbeamMigrations,
	);
	type XcmExecutionManager = XcmExecutionManager;
}
pub type ForeignAssetMigratorOrigin = EitherOfDiverse<
	EnsureRoot<AccountId>,
	EitherOfDiverse<
		pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
		EitherOf<
			governance::custom_origins::GeneralAdmin,
			governance::custom_origins::FastGeneralAdmin,
		>,
	>,
>;
impl pallet_moonbeam_lazy_migrations::Config for Runtime {
	type ForeignAssetMigratorOrigin = ForeignAssetMigratorOrigin;
	type WeightInfo = moonbeam_weights::pallet_moonbeam_lazy_migrations::WeightInfo<Runtime>;
}
/// Maintenance mode Call filter
pub struct MaintenanceFilter;
impl Contains<RuntimeCall> for MaintenanceFilter {
	fn contains(c: &RuntimeCall) -> bool {
		match c {
			RuntimeCall::Assets(_) => false,
			RuntimeCall::Balances(_) => false,
			RuntimeCall::CrowdloanRewards(_) => false,
			RuntimeCall::Ethereum(_) => false,
			RuntimeCall::EVM(_) => false,
			RuntimeCall::Identity(_) => false,
			RuntimeCall::ParachainStaking(_) => false,
			RuntimeCall::MoonbeamOrbiters(_) => false,
			RuntimeCall::PolkadotXcm(_) => false,
			RuntimeCall::Treasury(_) => false,
			RuntimeCall::XcmTransactor(_) => false,
			RuntimeCall::EthereumXcm(_) => false,
			_ => true,
		}
	}
}
/// Normal Call Filter
/// We dont allow to create nor mint assets, this for now is disabled
/// We only allow transfers. For now creation of assets will go through
/// asset-manager, while minting/burning only happens through xcm messages
/// This can change in the future
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
234
	fn contains(c: &RuntimeCall) -> bool {
234
		match c {
18
			RuntimeCall::Assets(method) => match method {
6
				pallet_assets::Call::transfer { .. } => true,
				pallet_assets::Call::transfer_keep_alive { .. } => true,
6
				pallet_assets::Call::approve_transfer { .. } => true,
6
				pallet_assets::Call::transfer_approved { .. } => true,
				pallet_assets::Call::cancel_approval { .. } => true,
				pallet_assets::Call::destroy_accounts { .. } => true,
				pallet_assets::Call::destroy_approvals { .. } => true,
				pallet_assets::Call::finish_destroy { .. } => true,
				_ => false,
			},
			// We just want to enable this in case of live chains, since the default version
			// is populated at genesis
24
			RuntimeCall::PolkadotXcm(method) => match method {
				pallet_xcm::Call::force_default_xcm_version { .. } => true,
18
				pallet_xcm::Call::transfer_assets { .. } => true,
				pallet_xcm::Call::transfer_assets_using_type_and_then { .. } => true,
6
				_ => false,
			},
			// We filter anonymous proxy as they make "reserve" inconsistent
			// See: https://github.com/paritytech/substrate/blob/37cca710eed3dadd4ed5364c7686608f5175cce1/frame/proxy/src/lib.rs#L270 // editorconfig-checker-disable-line
			RuntimeCall::Proxy(method) => match method {
				pallet_proxy::Call::create_pure { .. } => false,
				pallet_proxy::Call::kill_pure { .. } => false,
				pallet_proxy::Call::proxy { real, .. } => {
					!pallet_evm::AccountCodes::<Runtime>::contains_key(H160::from(*real))
				}
				_ => true,
			},
			// Filtering the EVM prevents possible re-entrancy from the precompiles which could
			// lead to unexpected scenarios.
			// See https://github.com/PureStake/sr-moonbeam/issues/30
			// Note: It is also assumed that EVM calls are only allowed through `Origin::Root` so
			// this can be seen as an additional security
			RuntimeCall::EVM(_) => false,
192
			_ => true,
		}
234
	}
}
pub struct XcmExecutionManager;
impl moonkit_xcm_primitives::PauseXcmExecution for XcmExecutionManager {
	fn suspend_xcm_execution() -> DispatchResult {
		XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
	}
	fn resume_xcm_execution() -> DispatchResult {
		XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
	}
}
impl pallet_maintenance_mode::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type NormalCallFilter = NormalFilter;
	type MaintenanceCallFilter = MaintenanceFilter;
	type MaintenanceOrigin =
		pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>;
	type XcmExecutionManager = XcmExecutionManager;
}
impl pallet_proxy_genesis_companion::Config for Runtime {
	type ProxyType = ProxyType;
}
parameter_types! {
	pub OrbiterReserveIdentifier: [u8; 4] = [b'o', b'r', b'b', b'i'];
}
type AddCollatorOrigin =
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
type DelCollatorOrigin =
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
impl pallet_moonbeam_orbiters::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type AccountLookup = AuthorMapping;
	type AddCollatorOrigin = AddCollatorOrigin;
	type Currency = Balances;
	type DelCollatorOrigin = DelCollatorOrigin;
	/// Maximum number of orbiters per collator
	type MaxPoolSize = ConstU32<8>;
	/// Maximum number of round to keep on storage
	type MaxRoundArchive = ConstU32<4>;
	type OrbiterReserveIdentifier = OrbiterReserveIdentifier;
	type RotatePeriod = ConstU32<1>;
	/// Round index type.
	type RoundIndex = pallet_parachain_staking::RoundIndex;
	type WeightInfo = moonbeam_weights::pallet_moonbeam_orbiters::WeightInfo<Runtime>;
}
/// Only callable after `set_validation_data` is called which forms this proof the same way
fn relay_chain_state_proof<Runtime>() -> RelayChainStateProof
where
	Runtime: cumulus_pallet_parachain_system::Config,
{
	let relay_storage_root = ValidationData::<Runtime>::get()
		.expect("set in `set_validation_data`")
		.relay_parent_storage_root;
	let relay_chain_state =
		RelayStateProof::<Runtime>::get().expect("set in `set_validation_data`");
	RelayChainStateProof::new(ParachainInfo::get(), relay_storage_root, relay_chain_state)
		.expect("Invalid relay chain state proof, already constructed in `set_validation_data`")
}
pub struct BabeDataGetter<Runtime>(sp_std::marker::PhantomData<Runtime>);
impl<Runtime> pallet_randomness::GetBabeData<u64, Option<Hash>> for BabeDataGetter<Runtime>
where
	Runtime: cumulus_pallet_parachain_system::Config,
{
	// Tolerate panic here because only ever called in inherent (so can be omitted)
	fn get_epoch_index() -> u64 {
		if cfg!(feature = "runtime-benchmarks") {
			// storage reads as per actual reads
			let _relay_storage_root = ValidationData::<Runtime>::get();
			let _relay_chain_state = RelayStateProof::<Runtime>::get();
			const BENCHMARKING_NEW_EPOCH: u64 = 10u64;
			return BENCHMARKING_NEW_EPOCH;
		}
		relay_chain_state_proof::<Runtime>()
			.read_optional_entry(relay_chain::well_known_keys::EPOCH_INDEX)
			.ok()
			.flatten()
			.expect("expected to be able to read epoch index from relay chain state proof")
	}
	fn get_epoch_randomness() -> Option<Hash> {
		if cfg!(feature = "runtime-benchmarks") {
			// storage reads as per actual reads
			let _relay_storage_root = ValidationData::<Runtime>::get();
			let _relay_chain_state = RelayStateProof::<Runtime>::get();
			let benchmarking_babe_output = Hash::default();
			return Some(benchmarking_babe_output);
		}
		relay_chain_state_proof::<Runtime>()
			.read_optional_entry(relay_chain::well_known_keys::ONE_EPOCH_AGO_RANDOMNESS)
			.ok()
			.flatten()
	}
}
impl pallet_randomness::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type AddressMapping = sp_runtime::traits::ConvertInto;
	type Currency = Balances;
	type BabeDataGetter = BabeDataGetter<Runtime>;
	type VrfKeyLookup = AuthorMapping;
	type Deposit = runtime_params::PalletRandomnessDepositU128;
	type MaxRandomWords = ConstU8<100>;
	type MinBlockDelay = ConstU32<2>;
	type MaxBlockDelay = ConstU32<2_000>;
	type BlockExpirationDelay = ConstU32<10_000>;
	type EpochExpirationDelay = ConstU64<10_000>;
	type WeightInfo = moonbeam_weights::pallet_randomness::WeightInfo<Runtime>;
}
impl pallet_root_testing::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
}
parameter_types! {
	// One storage item; key size is 32 + 20; value is size 4+4+16+20 bytes = 44 bytes.
	pub const DepositBase: Balance = currency::deposit(1, 96);
	// Additional storage item size of 20 bytes.
	pub const DepositFactor: Balance = currency::deposit(0, 20);
	pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeCall = RuntimeCall;
	type Currency = Balances;
	type DepositBase = DepositBase;
	type DepositFactor = DepositFactor;
	type MaxSignatories = MaxSignatories;
	type WeightInfo = moonbeam_weights::pallet_multisig::WeightInfo<Runtime>;
}
impl pallet_relay_storage_roots::Config for Runtime {
	type MaxStorageRoots = ConstU32<30>;
	type RelaychainStateProvider = cumulus_pallet_parachain_system::RelaychainDataProvider<Self>;
	type WeightInfo = moonbeam_weights::pallet_relay_storage_roots::WeightInfo<Runtime>;
}
impl pallet_precompile_benchmarks::Config for Runtime {
	type WeightInfo = moonbeam_weights::pallet_precompile_benchmarks::WeightInfo<Runtime>;
}
impl pallet_parameters::Config for Runtime {
	type AdminOrigin = EnsureRoot<AccountId>;
	type RuntimeEvent = RuntimeEvent;
	type RuntimeParameters = RuntimeParameters;
	type WeightInfo = moonbeam_weights::pallet_parameters::WeightInfo<Runtime>;
}
impl pallet_multiblock_migrations::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	// TODO fully replace pallet_migrations with multiblock migrations.
	#[cfg(not(feature = "runtime-benchmarks"))]
	type Migrations = pallet_identity::migration::v2::LazyMigrationV1ToV2<Runtime>;
	// Benchmarks need mocked migrations to guarantee that they succeed.
	#[cfg(feature = "runtime-benchmarks")]
	type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
	type CursorMaxLen = ConstU32<65_536>;
	type IdentifierMaxLen = ConstU32<256>;
	type MigrationStatusHandler = ();
	type FailedMigrationHandler = MaintenanceMode;
	type MaxServiceWeight = MaxServiceWeight;
	type WeightInfo = weights::pallet_multiblock_migrations::WeightInfo<Runtime>;
}
1176201
construct_runtime! {
8714
	pub enum Runtime
8714
	{
8714
		// System support stuff.
8714
		System: frame_system::{Pallet, Call, Storage, Config<T>, Event<T>} = 0,
8714
		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>} = 1,
8714
		// Previously 2: pallet_randomness_collective_flip
8714
		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 3,
8714
		ParachainInfo: parachain_info::{Pallet, Storage, Config<T>} = 4,
8714
		RootTesting: pallet_root_testing::{Pallet, Call, Storage, Event<T>} = 5,
8714

            
8714
		// Monetary stuff.
8714
		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 10,
8714
		TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Config<T>, Event<T>} = 11,
8714

            
8714
		// Consensus support.
8714
		ParachainStaking: pallet_parachain_staking::{Pallet, Call, Storage, Event<T>, Config<T>} = 20,
8714
		AuthorInherent: pallet_author_inherent::{Pallet, Call, Storage, Inherent} = 21,
8714
		AuthorFilter: pallet_author_slot_filter::{Pallet, Call, Storage, Event, Config<T>} = 22,
8714
		AuthorMapping: pallet_author_mapping::{Pallet, Call, Config<T>, Storage, Event<T>} = 23,
8714
		MoonbeamOrbiters: pallet_moonbeam_orbiters::{Pallet, Call, Storage, Event<T>} = 24,
8714
		AsyncBacking: pallet_async_backing::{Pallet, Storage} = 25,
8714

            
8714
		// Handy utilities.
8714
		Utility: pallet_utility::{Pallet, Call, Event} = 30,
8714
		Proxy: pallet_proxy::{Pallet, Call, Storage, Event<T>} = 31,
8714
		MaintenanceMode: pallet_maintenance_mode::{Pallet, Call, Config<T>, Storage, Event} = 32,
8714
		Identity: pallet_identity::{Pallet, Call, Storage, Event<T>} = 33,
8714
		Migrations: pallet_migrations::{Pallet, Storage, Config<T>, Event<T>} = 34,
8714
		ProxyGenesisCompanion: pallet_proxy_genesis_companion::{Pallet, Config<T>} = 35,
8714
		Multisig: pallet_multisig::{Pallet, Call, Storage, Event<T>} = 36,
8714
		MoonbeamLazyMigrations: pallet_moonbeam_lazy_migrations::{Pallet, Call, Storage} = 37,
8714
		Parameters: pallet_parameters = 38,
8714

            
8714
		// Has been permanently removed for safety reasons.
8714
		// Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>} = 40,
8714

            
8714
		// Ethereum compatibility.
8714
		EthereumChainId: pallet_evm_chain_id::{Pallet, Storage, Config<T>} = 50,
8714
		EVM: pallet_evm::{Pallet, Config<T>, Call, Storage, Event<T>} = 51,
8714
		Ethereum: pallet_ethereum::{Pallet, Call, Storage, Event, Origin, Config<T>} = 52,
8714

            
8714
		// Governance stuff.
8714
		Scheduler: pallet_scheduler::{Pallet, Storage, Event<T>, Call} = 60,
8714
		// Democracy: 61,
8714
		Preimage: pallet_preimage::{Pallet, Call, Storage, Event<T>, HoldReason} = 62,
8714
		ConvictionVoting: pallet_conviction_voting::{Pallet, Call, Storage, Event<T>} = 63,
8714
		Referenda: pallet_referenda::{Pallet, Call, Storage, Event<T>} = 64,
8714
		Origins: governance::custom_origins::{Origin} = 65,
8714
		Whitelist: pallet_whitelist::{Pallet, Call, Storage, Event<T>} = 66,
8714

            
8714
		// Council stuff.
8714
		// CouncilCollective: 70
8714
		// TechCommitteeCollective: 71
8714
		TreasuryCouncilCollective:
8714
			pallet_collective::<Instance3>::{Pallet, Call, Storage, Event<T>, Origin<T>, Config<T>} = 72,
8714
		OpenTechCommitteeCollective:
8714
			pallet_collective::<Instance4>::{Pallet, Call, Storage, Event<T>, Origin<T>, Config<T>} = 73,
8714

            
8714
		// Treasury stuff.
8714
		Treasury: pallet_treasury::{Pallet, Storage, Config<T>, Event<T>, Call} = 80,
8714

            
8714
		// Crowdloan stuff.
8714
		CrowdloanRewards: pallet_crowdloan_rewards::{Pallet, Call, Config<T>, Storage, Event<T>} = 90,
8714

            
8714
		// XCM
8714
		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 100,
8714
		CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 101,
8714
		// Previously 102: DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>}
8714
		PolkadotXcm: pallet_xcm::{Pallet, Storage, Call, Event<T>, Origin, Config<T>} = 103,
8714
		Assets: pallet_assets::{Pallet, Call, Storage, Event<T>} = 104,
8714
		AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event<T>} = 105,
8714
		// Previously 106: XTokens
8714
		XcmTransactor: pallet_xcm_transactor::{Pallet, Call, Storage, Event<T>} = 107,
8714
		// Previously 108: pallet_assets::<Instance1>
8714
		EthereumXcm: pallet_ethereum_xcm::{Pallet, Call, Storage, Origin, Event<T>} = 109,
8714
		Erc20XcmBridge: pallet_erc20_xcm_bridge::{Pallet} = 110,
8714
		MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 111,
8714
		EvmForeignAssets: pallet_moonbeam_foreign_assets::{Pallet, Call, Storage, Event<T>} = 114,
8714
		XcmWeightTrader: pallet_xcm_weight_trader::{Pallet, Call, Storage, Event<T>} = 115,
8714
		EmergencyParaXcm: pallet_emergency_para_xcm::{Pallet, Call, Storage, Event} = 116,
8714
		MultiBlockMigrations: pallet_multiblock_migrations = 117,
8714

            
8714
		// Utils
8714
		RelayStorageRoots: pallet_relay_storage_roots::{Pallet, Storage} = 112,
8714

            
8714
		// TODO should not be included in production
8714
		PrecompileBenchmarks: pallet_precompile_benchmarks::{Pallet} = 113,
8714

            
8714
		// Randomness
8714
		Randomness: pallet_randomness::{Pallet, Call, Storage, Event<T>, Inherent} = 120,
8714
	}
1177852
}
#[cfg(feature = "runtime-benchmarks")]
use moonbeam_runtime_common::benchmarking::BenchmarkHelper;
use moonbeam_runtime_common::deal_with_fees::{
	DealWithEthereumBaseFees, DealWithEthereumPriorityFees, DealWithSubstrateFeesAndTip,
};
#[cfg(feature = "runtime-benchmarks")]
mod benches {
	frame_support::parameter_types! {
		pub const MaxBalance: crate::Balance = crate::Balance::max_value();
	}
	frame_benchmarking::define_benchmarks!(
		[frame_system, SystemBench::<Runtime>]
		[frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
		[pallet_utility, Utility]
		[pallet_timestamp, Timestamp]
		[pallet_balances, Balances]
		[pallet_evm, EVM]
		[pallet_assets, Assets]
		[pallet_parachain_staking, ParachainStaking]
		[pallet_scheduler, Scheduler]
		[pallet_treasury, Treasury]
		[pallet_author_inherent, AuthorInherent]
		[pallet_author_slot_filter, AuthorFilter]
		[pallet_crowdloan_rewards, CrowdloanRewards]
		[pallet_author_mapping, AuthorMapping]
		[pallet_proxy, Proxy]
		[pallet_transaction_payment, PalletTransactionPaymentBenchmark::<Runtime>]
		[pallet_identity, Identity]
		[cumulus_pallet_parachain_system, ParachainSystem]
		[cumulus_pallet_xcmp_queue, XcmpQueue]
		[pallet_message_queue, MessageQueue]
		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
		[pallet_asset_manager, AssetManager]
		[pallet_xcm_transactor, XcmTransactor]
		[pallet_moonbeam_foreign_assets, EvmForeignAssets]
		[pallet_moonbeam_orbiters, MoonbeamOrbiters]
		[pallet_randomness, Randomness]
		[pallet_conviction_voting, ConvictionVoting]
		[pallet_referenda, Referenda]
		[pallet_preimage, Preimage]
		[pallet_whitelist, Whitelist]
		[pallet_multisig, Multisig]
		[pallet_multiblock_migrations, MultiBlockMigrations]
		[pallet_moonbeam_lazy_migrations, MoonbeamLazyMigrations]
		[pallet_relay_storage_roots, RelayStorageRoots]
		[pallet_precompile_benchmarks, PrecompileBenchmarks]
		[pallet_parameters, Parameters]
		[pallet_xcm_weight_trader, XcmWeightTrader]
		[pallet_collective, TreasuryCouncilCollective]
		[pallet_collective, OpenTechCommitteeCollective]
	);
}
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
	frame_system::CheckNonZeroSender<Runtime>,
	frame_system::CheckSpecVersion<Runtime>,
	frame_system::CheckTxVersion<Runtime>,
	frame_system::CheckGenesis<Runtime>,
	frame_system::CheckEra<Runtime>,
	frame_system::CheckNonce<Runtime>,
	frame_system::CheckWeight<Runtime>,
	pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
	cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic =
	fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
/// Executive: handles dispatch to the various pallets.
pub type Executive = frame_executive::Executive<
	Runtime,
	Block,
	frame_system::ChainContext<Runtime>,
	Runtime,
	AllPalletsWithSystem,
>;
// All of our runtimes share most of their Runtime API implementations.
// We use a macro to implement this common part and add runtime-specific additional implementations.
// This macro expands to :
// ```
// impl_runtime_apis! {
//     // All impl blocks shared between all runtimes.
//
//     // Specific impls provided to the `impl_runtime_apis_plus_common!` macro.
// }
// ```
moonbeam_runtime_common::impl_runtime_apis_plus_common! {
	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
		fn validate_transaction(
			source: TransactionSource,
			xt: <Block as BlockT>::Extrinsic,
			block_hash: <Block as BlockT>::Hash,
		) -> TransactionValidity {
			// Filtered calls should not enter the tx pool as they'll fail if inserted.
			// If this call is not allowed, we return early.
			if !<Runtime as frame_system::Config>::BaseCallFilter::contains(&xt.0.function) {
				return InvalidTransaction::Call.into();
			}
			// This runtime uses Substrate's pallet transaction payment. This
			// makes the chain feel like a standard Substrate chain when submitting
			// frame transactions and using Substrate ecosystem tools. It has the downside that
			// transaction are not prioritized by gas_price. The following code reprioritizes
			// transactions to overcome this.
			//
			// A more elegant, ethereum-first solution is
			// a pallet that replaces pallet transaction payment, and allows users
			// to directly specify a gas price rather than computing an effective one.
			// #HopefullySomeday
			// First we pass the transactions to the standard FRAME executive. This calculates all the
			// necessary tags, longevity and other properties that we will leave unchanged.
			// This also assigns some priority that we don't care about and will overwrite next.
			let mut intermediate_valid = Executive::validate_transaction(source, xt.clone(), block_hash)?;
			let dispatch_info = xt.get_dispatch_info();
			// If this is a pallet ethereum transaction, then its priority is already set
			// according to gas price from pallet ethereum. If it is any other kind of transaction,
			// we modify its priority.
			Ok(match &xt.0.function {
				RuntimeCall::Ethereum(transact { .. }) => intermediate_valid,
				_ if dispatch_info.class != DispatchClass::Normal => intermediate_valid,
				_ => {
					let tip = match &xt.0.preamble {
						Preamble::Bare(_) => 0,
						Preamble::Signed(_, _, signed_extra) => {
							// Yuck, this depends on the index of ChargeTransactionPayment in SignedExtra
							// Get the 7th item from the tuple
							let charge_transaction_payment = &signed_extra.7;
							charge_transaction_payment.tip()
						},
						Preamble::General(_, _) => 0,
					};
					// Calculate the fee that will be taken by pallet transaction payment
					let fee: u64 = TransactionPayment::compute_fee(
						xt.encode().len() as u32,
						&dispatch_info,
						tip,
					).saturated_into();
					// Calculate how much gas this effectively uses according to the existing mapping
					let effective_gas =
						<Runtime as pallet_evm::Config>::GasWeightMapping::weight_to_gas(
							dispatch_info.total_weight()
						);
					// Here we calculate an ethereum-style effective gas price using the
					// current fee of the transaction. Because the weight -> gas conversion is
					// lossy, we have to handle the case where a very low weight maps to zero gas.
					let effective_gas_price = if effective_gas > 0 {
						fee / effective_gas
					} else {
						// If the effective gas was zero, we just act like it was 1.
						fee
					};
					// Overwrite the original prioritization with this ethereum one
					intermediate_valid.priority = effective_gas_price;
					intermediate_valid
				}
			})
		}
	}
	impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
		fn can_build_upon(
			included_hash: <Block as BlockT>::Hash,
			slot: async_backing_primitives::Slot,
		) -> bool {
			ConsensusHook::can_build_upon(included_hash, slot)
		}
	}
}
#[allow(dead_code)]
struct CheckInherents;
// Parity has decided to depreciate this trait, but does not offer a satisfactory replacement,
// see issue: https://github.com/paritytech/polkadot-sdk/issues/2841
#[allow(deprecated)]
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
	fn check_inherents(
		block: &Block,
		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
	) -> sp_inherents::CheckInherentsResult {
		let relay_chain_slot = relay_state_proof
			.read_slot()
			.expect("Could not read the relay chain slot from the proof");
		let inherent_data =
			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
				relay_chain_slot,
				sp_std::time::Duration::from_secs(6),
			)
			.create_inherent_data()
			.expect("Could not create the timestamp inherent data");
		inherent_data.check_extrinsics(block)
	}
}
// Nimbus's Executive wrapper allows relay validators to verify the seal digest
cumulus_pallet_parachain_system::register_validate_block!(
	Runtime = Runtime,
	BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
	CheckInherents = CheckInherents,
);
moonbeam_runtime_common::impl_self_contained_call!();
// Shorthand for a Get field of a pallet Config.
#[macro_export]
macro_rules! get {
	($pallet:ident, $name:ident, $type:ty) => {
		<<$crate::Runtime as $pallet::Config>::$name as $crate::Get<$type>>::get()
	};
}
#[cfg(test)]
mod tests {
	use super::{currency::*, *};
	#[test]
	// Helps us to identify a Pallet Call in case it exceeds the 1kb limit.
	// Hint: this should be a rare case. If that happens, one or more of the dispatchable arguments
	// need to be Boxed.
1
	fn call_max_size() {
		const CALL_ALIGN: u32 = 1024;
1
		assert!(std::mem::size_of::<pallet_evm_chain_id::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(std::mem::size_of::<pallet_evm::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(std::mem::size_of::<pallet_ethereum::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(
1
			std::mem::size_of::<pallet_parachain_staking::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(
1
			std::mem::size_of::<pallet_author_inherent::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(
1
			std::mem::size_of::<pallet_author_slot_filter::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(
1
			std::mem::size_of::<pallet_crowdloan_rewards::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(std::mem::size_of::<pallet_author_mapping::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(
1
			std::mem::size_of::<pallet_maintenance_mode::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(std::mem::size_of::<pallet_migrations::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(
1
			std::mem::size_of::<pallet_moonbeam_lazy_migrations::Call<Runtime>>()
1
				<= CALL_ALIGN as usize
1
		);
1
		assert!(
1
			std::mem::size_of::<pallet_proxy_genesis_companion::Call<Runtime>>()
1
				<= CALL_ALIGN as usize
1
		);
1
	}
	#[test]
1
	fn currency_constants_are_correct() {
1
		assert_eq!(SUPPLY_FACTOR, 100);
		// txn fees
1
		assert_eq!(TRANSACTION_BYTE_FEE, Balance::from(100 * GIGAWEI));
1
		assert_eq!(
1
			get!(pallet_transaction_payment, OperationalFeeMultiplier, u8),
1
			5_u8
1
		);
1
		assert_eq!(STORAGE_BYTE_FEE, Balance::from(10 * MILLIGLMR));
		// pallet_identity deposits
1
		assert_eq!(
1
			get!(pallet_identity, BasicDeposit, u128),
1
			Balance::from(10 * GLMR + 2580 * MILLIGLMR)
1
		);
1
		assert_eq!(
1
			get!(pallet_identity, ByteDeposit, u128),
1
			Balance::from(10 * MILLIGLMR)
1
		);
1
		assert_eq!(
1
			get!(pallet_identity, SubAccountDeposit, u128),
1
			Balance::from(10 * GLMR + 530 * MILLIGLMR)
1
		);
		// staking minimums
1
		assert_eq!(
1
			get!(pallet_parachain_staking, MinCandidateStk, u128),
1
			Balance::from(500_000 * GLMR)
1
		);
1
		assert_eq!(
1
			get!(pallet_parachain_staking, MinDelegation, u128),
1
			Balance::from(50 * GLMR)
1
		);
		// crowdloan min reward
1
		assert_eq!(
1
			get!(pallet_crowdloan_rewards, MinimumReward, u128),
1
			Balance::from(0u128)
1
		);
		// deposit for AuthorMapping
1
		assert_eq!(
1
			get!(pallet_author_mapping, DepositAmount, u128),
1
			Balance::from(10 * KILOGLMR)
1
		);
		// proxy deposits
1
		assert_eq!(
1
			get!(pallet_proxy, ProxyDepositBase, u128),
1
			Balance::from(10 * GLMR + 80 * MILLIGLMR)
1
		);
1
		assert_eq!(
1
			get!(pallet_proxy, ProxyDepositFactor, u128),
1
			Balance::from(210 * MILLIGLMR)
1
		);
1
		assert_eq!(
1
			get!(pallet_proxy, AnnouncementDepositBase, u128),
1
			Balance::from(10 * GLMR + 80 * MILLIGLMR)
1
		);
1
		assert_eq!(
1
			get!(pallet_proxy, AnnouncementDepositFactor, u128),
1
			Balance::from(560 * MILLIGLMR)
1
		);
1
	}
	#[test]
1
	fn max_offline_rounds_lower_or_eq_than_reward_payment_delay() {
1
		assert!(
1
			get!(pallet_parachain_staking, MaxOfflineRounds, u32)
1
				<= get!(pallet_parachain_staking, RewardPaymentDelay, u32)
1
		);
1
	}
	#[test]
	// Required migration is
	// pallet_parachain_staking::migrations::IncreaseMaxTopDelegationsPerCandidate
	// Purpose of this test is to remind of required migration if constant is ever changed
1
	fn updating_maximum_delegators_per_candidate_requires_configuring_required_migration() {
1
		assert_eq!(
1
			get!(pallet_parachain_staking, MaxTopDelegationsPerCandidate, u32),
1
			300
1
		);
1
		assert_eq!(
1
			get!(
1
				pallet_parachain_staking,
1
				MaxBottomDelegationsPerCandidate,
1
				u32
1
			),
1
			50
1
		);
1
	}
	#[test]
1
	fn configured_base_extrinsic_weight_is_evm_compatible() {
1
		let min_ethereum_transaction_weight = WeightPerGas::get() * 21_000;
1
		let base_extrinsic = <Runtime as frame_system::Config>::BlockWeights::get()
1
			.get(frame_support::dispatch::DispatchClass::Normal)
1
			.base_extrinsic;
1
		assert!(base_extrinsic.ref_time() <= min_ethereum_transaction_weight.ref_time());
1
	}
	#[test]
1
	fn test_storage_growth_ratio_is_correct() {
1
		// This is the highest amount of new storage that can be created in a block 160 KB
1
		let block_storage_limit = 160 * 1024;
1
		let expected_storage_growth_ratio = BlockGasLimit::get()
1
			.low_u64()
1
			.saturating_div(block_storage_limit);
1
		let actual_storage_growth_ratio =
1
			<Runtime as pallet_evm::Config>::GasLimitStorageGrowthRatio::get();
1
		assert_eq!(
			expected_storage_growth_ratio, actual_storage_growth_ratio,
			"Storage growth ratio is not correct"
		);
1
	}
}