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
use account::AccountId20;
32
use cumulus_pallet_parachain_system::{
33
	RelayChainStateProof, RelayStateProof, RelaychainDataProvider, ValidationData,
34
};
35
use fp_rpc::TransactionStatus;
36

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

            
103
use runtime_params::*;
104

            
105
#[cfg(feature = "std")]
106
use sp_version::NativeVersion;
107
use sp_version::RuntimeVersion;
108

            
109
use nimbus_primitives::CanAuthor;
110

            
111
mod migrations;
112
mod precompiles;
113
pub use precompiles::{
114
	MoonbeamPrecompiles, PrecompileName, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
115
};
116

            
117
#[cfg(any(feature = "std", test))]
118
pub use sp_runtime::BuildStorage;
119

            
120
pub type Precompiles = MoonbeamPrecompiles<Runtime>;
121

            
122
pub mod asset_config;
123
#[cfg(not(feature = "disable-genesis-builder"))]
124
pub mod genesis_config_preset;
125
pub mod governance;
126
pub mod runtime_params;
127
mod weights;
128
pub mod xcm_config;
129

            
130
use governance::councils::*;
131
pub(crate) use weights as moonbeam_weights;
132

            
133
/// GLMR, the native token, uses 18 decimals of precision.
134
pub mod currency {
135
	use super::Balance;
136

            
137
	// Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
138
	pub const SUPPLY_FACTOR: Balance = 100;
139

            
140
	pub const WEI: Balance = 1;
141
	pub const KILOWEI: Balance = 1_000;
142
	pub const MEGAWEI: Balance = 1_000_000;
143
	pub const GIGAWEI: Balance = 1_000_000_000;
144
	pub const MICROGLMR: Balance = 1_000_000_000_000;
145
	pub const MILLIGLMR: Balance = 1_000_000_000_000_000;
146
	pub const GLMR: Balance = 1_000_000_000_000_000_000;
147
	pub const KILOGLMR: Balance = 1_000_000_000_000_000_000_000;
148

            
149
	pub const TRANSACTION_BYTE_FEE: Balance = 1 * GIGAWEI * SUPPLY_FACTOR;
150
	pub const STORAGE_BYTE_FEE: Balance = 100 * MICROGLMR * SUPPLY_FACTOR;
151
	pub const WEIGHT_FEE: Balance = 50 * KILOWEI * SUPPLY_FACTOR / 4;
152

            
153
24
	pub const fn deposit(items: u32, bytes: u32) -> Balance {
154
24
		items as Balance * 100 * MILLIGLMR * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
155
24
	}
156
}
157

            
158
/// Maximum PoV size we support right now.
159
// Reference: https://github.com/polkadot-fellows/runtimes/pull/553
160
pub const MAX_POV_SIZE: u32 = 10 * 1024 * 1024;
161

            
162
/// Maximum weight per block
163
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
164
	WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
165
	MAX_POV_SIZE as u64,
166
);
167

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

            
181
	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
182
	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
183

            
184
	impl_opaque_keys! {
185
		pub struct SessionKeys {
186
			pub nimbus: AuthorInherent,
187
			pub vrf: session_keys_primitives::VrfSessionKey,
188
		}
189
	}
190
}
191

            
192
/// This runtime version.
193
/// The spec_version is composed of 2x2 digits. The first 2 digits represent major changes
194
/// that can't be skipped, such as data migration upgrades. The last 2 digits represent minor
195
/// changes which can be skipped.
196
#[sp_version::runtime_version]
197
pub const VERSION: RuntimeVersion = RuntimeVersion {
198
	spec_name: create_runtime_str!("moonbeam"),
199
	impl_name: create_runtime_str!("moonbeam"),
200
	authoring_version: 3,
201
	spec_version: 3700,
202
	impl_version: 0,
203
	apis: RUNTIME_API_VERSIONS,
204
	transaction_version: 3,
205
	state_version: 1,
206
};
207

            
208
/// The version information used to identify this runtime when compiled natively.
209
#[cfg(feature = "std")]
210
pub fn native_version() -> NativeVersion {
211
	NativeVersion {
212
		runtime_version: VERSION,
213
		can_author_with: Default::default(),
214
	}
215
}
216

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

            
225
pub struct RuntimeBlockWeights;
226
impl Get<frame_system::limits::BlockWeights> for RuntimeBlockWeights {
227
360840
	fn get() -> frame_system::limits::BlockWeights {
228
360840
		frame_system::limits::BlockWeights::builder()
229
360840
			.for_class(DispatchClass::Normal, |weights| {
230
360840
				weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT;
231
360840
				weights.max_total = NORMAL_WEIGHT.into();
232
360840
			})
233
360840
			.for_class(DispatchClass::Operational, |weights| {
234
360840
				weights.max_total = MAXIMUM_BLOCK_WEIGHT.into();
235
360840
				weights.reserved = (MAXIMUM_BLOCK_WEIGHT - NORMAL_WEIGHT).into();
236
360840
			})
237
360840
			.avg_block_initialization(Perbill::from_percent(10))
238
360840
			.build()
239
360840
			.expect("Provided BlockWeight definitions are valid, qed")
240
360840
	}
241
}
242

            
243
parameter_types! {
244
	pub const Version: RuntimeVersion = VERSION;
245
	/// We allow for 5 MB blocks.
246
	pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
247
		::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
248
}
249

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

            
297
impl pallet_utility::Config for Runtime {
298
	type RuntimeEvent = RuntimeEvent;
299
	type RuntimeCall = RuntimeCall;
300
	type PalletsOrigin = OriginCaller;
301
	type WeightInfo = moonbeam_weights::pallet_utility::WeightInfo<Runtime>;
302
}
303

            
304
impl pallet_timestamp::Config for Runtime {
305
	/// A timestamp: milliseconds since the unix epoch.
306
	type Moment = u64;
307
	type OnTimestampSet = ();
308
	type MinimumPeriod = ConstU64<3000>;
309
	type WeightInfo = moonbeam_weights::pallet_timestamp::WeightInfo<Runtime>;
310
}
311

            
312
#[cfg(not(feature = "runtime-benchmarks"))]
313
parameter_types! {
314
	pub const ExistentialDeposit: Balance = 0;
315
}
316

            
317
#[cfg(feature = "runtime-benchmarks")]
318
parameter_types! {
319
	pub const ExistentialDeposit: Balance = 1;
320
}
321

            
322
impl pallet_balances::Config for Runtime {
323
	type MaxReserves = ConstU32<50>;
324
	type ReserveIdentifier = [u8; 4];
325
	type MaxLocks = ConstU32<50>;
326
	/// The type for recording an account's balance.
327
	type Balance = Balance;
328
	/// The ubiquitous event type.
329
	type RuntimeEvent = RuntimeEvent;
330
	type DustRemoval = ();
331
	type ExistentialDeposit = ExistentialDeposit;
332
	type AccountStore = System;
333
	type FreezeIdentifier = ();
334
	type MaxFreezes = ConstU32<0>;
335
	type RuntimeHoldReason = RuntimeHoldReason;
336
	type RuntimeFreezeReason = RuntimeFreezeReason;
337
	type WeightInfo = moonbeam_weights::pallet_balances::WeightInfo<Runtime>;
338
}
339

            
340
pub struct LengthToFee;
341
impl WeightToFeePolynomial for LengthToFee {
342
	type Balance = Balance;
343

            
344
66
	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
345
66
		smallvec![
346
			WeightToFeeCoefficient {
347
				degree: 1,
348
66
				coeff_frac: Perbill::zero(),
349
				coeff_integer: currency::TRANSACTION_BYTE_FEE,
350
				negative: false,
351
			},
352
			WeightToFeeCoefficient {
353
				degree: 3,
354
66
				coeff_frac: Perbill::zero(),
355
66
				coeff_integer: 1 * currency::SUPPLY_FACTOR,
356
				negative: false,
357
			},
358
		]
359
66
	}
360
}
361

            
362
impl pallet_transaction_payment::Config for Runtime {
363
	type RuntimeEvent = RuntimeEvent;
364
	type OnChargeTransaction = FungibleAdapter<
365
		Balances,
366
		DealWithSubstrateFeesAndTip<
367
			Runtime,
368
			dynamic_params::runtime_config::FeesTreasuryProportion,
369
		>,
370
	>;
371
	type OperationalFeeMultiplier = ConstU8<5>;
372
	type WeightToFee = ConstantMultiplier<Balance, ConstU128<{ currency::WEIGHT_FEE }>>;
373
	type LengthToFee = LengthToFee;
374
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime>;
375
}
376

            
377
impl pallet_evm_chain_id::Config for Runtime {}
378

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

            
385
/// Approximate ratio of the amount of Weight per Gas.
386
/// u64 works for approximations because Weight is a very small unit compared to gas.
387
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
388

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

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

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

            
451
/// Parameterized slow adjusting fee updated based on
452
/// https://w3f-research.readthedocs.io/en/latest/polkadot/overview/2-token-economics.html#-2.-slow-adjusting-mechanism // editorconfig-checker-disable-line
453
///
454
/// The adjustment algorithm boils down to:
455
///
456
/// diff = (previous_block_weight - target) / maximum_block_weight
457
/// next_multiplier = prev_multiplier * (1 + (v * diff) + ((v * diff)^2 / 2))
458
/// assert(next_multiplier > min)
459
///     where: v is AdjustmentVariable
460
///            target is TargetBlockFullness
461
///            min is MinimumMultiplier
462
pub type SlowAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
463
	R,
464
	TargetBlockFullness,
465
	AdjustmentVariable,
466
	MinimumMultiplier,
467
	MaximumMultiplier,
468
>;
469

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

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

            
478
impl<Inner> FindAuthor<H160> for FindAuthorAdapter<Inner>
479
where
480
	Inner: FindAuthor<AccountId20>,
481
{
482
16382
	fn find_author<'a, I>(digests: I) -> Option<H160>
483
16382
	where
484
16382
		I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
485
16382
	{
486
16382
		Inner::find_author(digests).map(Into::into)
487
16382
	}
488
}
489

            
490
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
491

            
492
impl pallet_evm::Config for Runtime {
493
	type FeeCalculator = TransactionPaymentAsGasPrice;
494
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
495
	type WeightPerGas = WeightPerGas;
496
	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
497
	type CallOrigin = EnsureAddressRoot<AccountId>;
498
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
499
	type AddressMapping = IdentityAddressMapping;
500
	type Currency = Balances;
501
	type RuntimeEvent = RuntimeEvent;
502
	type Runner = pallet_evm::runner::stack::Runner<Self>;
503
	type PrecompilesType = MoonbeamPrecompiles<Self>;
504
	type PrecompilesValue = PrecompilesValue;
505
	type ChainId = EthereumChainId;
506
	type OnChargeTransaction = OnChargeEVMTransaction<
507
		DealWithEthereumBaseFees<Runtime, dynamic_params::runtime_config::FeesTreasuryProportion>,
508
		DealWithEthereumPriorityFees<Runtime>,
509
	>;
510
	type BlockGasLimit = BlockGasLimit;
511
	type FindAuthor = FindAuthorAdapter<AuthorInherent>;
512
	type OnCreate = ();
513
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
514
	type SuicideQuickClearLimit = ConstU32<0>;
515
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
516
	type Timestamp = RelayTimestamp;
517
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
518
	type WeightInfo = moonbeam_weights::pallet_evm::WeightInfo<Runtime>;
519
}
520

            
521
parameter_types! {
522
	pub MaximumSchedulerWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
523
}
524

            
525
impl pallet_scheduler::Config for Runtime {
526
	type RuntimeEvent = RuntimeEvent;
527
	type RuntimeOrigin = RuntimeOrigin;
528
	type PalletsOrigin = OriginCaller;
529
	type RuntimeCall = RuntimeCall;
530
	type MaximumWeight = MaximumSchedulerWeight;
531
	type ScheduleOrigin = EnsureRoot<AccountId>;
532
	type MaxScheduledPerBlock = ConstU32<50>;
533
	type WeightInfo = moonbeam_weights::pallet_scheduler::WeightInfo<Runtime>;
534
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
535
	type Preimages = Preimage;
536
}
537

            
538
parameter_types! {
539
	pub const PreimageBaseDeposit: Balance = 5 * currency::GLMR * currency::SUPPLY_FACTOR ;
540
	pub const PreimageByteDeposit: Balance = currency::STORAGE_BYTE_FEE;
541
	pub const PreimageHoldReason: RuntimeHoldReason =
542
		RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
543
}
544

            
545
impl pallet_preimage::Config for Runtime {
546
	type WeightInfo = moonbeam_weights::pallet_preimage::WeightInfo<Runtime>;
547
	type RuntimeEvent = RuntimeEvent;
548
	type Currency = Balances;
549
	type ManagerOrigin = EnsureRoot<AccountId>;
550
	type Consideration = HoldConsideration<
551
		AccountId,
552
		Balances,
553
		PreimageHoldReason,
554
		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
555
	>;
556
}
557

            
558
parameter_types! {
559
	pub const ProposalBond: Permill = Permill::from_percent(5);
560
	pub const TreasuryId: PalletId = PalletId(*b"py/trsry");
561
	pub TreasuryAccount: AccountId = Treasury::account_id();
562
	pub const MaxSpendBalance: crate::Balance = crate::Balance::max_value();
563
}
564

            
565
type RootOrTreasuryCouncilOrigin = EitherOfDiverse<
566
	EnsureRoot<AccountId>,
567
	pallet_collective::EnsureProportionMoreThan<AccountId, TreasuryCouncilInstance, 1, 2>,
568
>;
569

            
570
impl pallet_treasury::Config for Runtime {
571
	type PalletId = TreasuryId;
572
	type Currency = Balances;
573
	// More than half of the council is required (or root) to reject a proposal
574
	type RejectOrigin = RootOrTreasuryCouncilOrigin;
575
	type RuntimeEvent = RuntimeEvent;
576
	type SpendPeriod = ConstU32<{ 6 * DAYS }>;
577
	type Burn = ();
578
	type BurnDestination = ();
579
	type MaxApprovals = ConstU32<100>;
580
	type WeightInfo = moonbeam_weights::pallet_treasury::WeightInfo<Runtime>;
581
	type SpendFunds = ();
582
	type SpendOrigin =
583
		frame_system::EnsureWithSuccess<RootOrTreasuryCouncilOrigin, AccountId, MaxSpendBalance>;
584
	type AssetKind = ();
585
	type Beneficiary = AccountId;
586
	type BeneficiaryLookup = IdentityLookup<AccountId>;
587
	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
588
	type BalanceConverter = UnityAssetBalanceConversion;
589
	type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
590
	#[cfg(feature = "runtime-benchmarks")]
591
	type BenchmarkHelper = BenchmarkHelper;
592
}
593

            
594
parameter_types! {
595
	pub const MaxSubAccounts: u32 = 100;
596
	pub const MaxAdditionalFields: u32 = 100;
597
	pub const MaxRegistrars: u32 = 20;
598
	pub const PendingUsernameExpiration: u32 = 7 * DAYS;
599
	pub const MaxSuffixLength: u32 = 7;
600
	pub const MaxUsernameLength: u32 = 32;
601
}
602

            
603
type IdentityForceOrigin =
604
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
605
type IdentityRegistrarOrigin =
606
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
607

            
608
impl pallet_identity::Config for Runtime {
609
	type RuntimeEvent = RuntimeEvent;
610
	type Currency = Balances;
611
	// Add one item in storage and take 258 bytes
612
	type BasicDeposit = ConstU128<{ currency::deposit(1, 258) }>;
613
	// Does not add any item to the storage but takes 1 bytes
614
	type ByteDeposit = ConstU128<{ currency::deposit(0, 1) }>;
615
	// Add one item in storage and take 53 bytes
616
	type SubAccountDeposit = ConstU128<{ currency::deposit(1, 53) }>;
617
	type MaxSubAccounts = MaxSubAccounts;
618
	type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
619
	type MaxRegistrars = MaxRegistrars;
620
	type Slashed = Treasury;
621
	type ForceOrigin = IdentityForceOrigin;
622
	type RegistrarOrigin = IdentityRegistrarOrigin;
623
	type OffchainSignature = Signature;
624
	type SigningPublicKey = <Signature as sp_runtime::traits::Verify>::Signer;
625
	type UsernameAuthorityOrigin = EnsureRoot<AccountId>;
626
	type PendingUsernameExpiration = PendingUsernameExpiration;
627
	type MaxSuffixLength = MaxSuffixLength;
628
	type MaxUsernameLength = MaxUsernameLength;
629
	type WeightInfo = moonbeam_weights::pallet_identity::WeightInfo<Runtime>;
630
}
631

            
632
pub struct TransactionConverter;
633

            
634
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
635
21
	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
636
21
		UncheckedExtrinsic::new_unsigned(
637
21
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
638
21
		)
639
21
	}
640
}
641

            
642
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
643
	fn convert_transaction(
644
		&self,
645
		transaction: pallet_ethereum::Transaction,
646
	) -> opaque::UncheckedExtrinsic {
647
		let extrinsic = UncheckedExtrinsic::new_unsigned(
648
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
649
		);
650
		let encoded = extrinsic.encode();
651
		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
652
			.expect("Encoded extrinsic is always valid")
653
	}
654
}
655

            
656
parameter_types! {
657
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
658
}
659

            
660
impl pallet_ethereum::Config for Runtime {
661
	type RuntimeEvent = RuntimeEvent;
662
	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
663
	type PostLogContent = PostBlockAndTxnHashes;
664
	type ExtraDataLength = ConstU32<30>;
665
}
666

            
667
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
668
/// into the relay chain.
669
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
670
/// How many parachain blocks are processed by the relay chain per parent. Limits the
671
/// number of blocks authored per slot.
672
const BLOCK_PROCESSING_VELOCITY: u32 = 1;
673

            
674
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
675
	Runtime,
676
	BLOCK_PROCESSING_VELOCITY,
677
	UNINCLUDED_SEGMENT_CAPACITY,
678
>;
679

            
680
impl cumulus_pallet_parachain_system::Config for Runtime {
681
	type RuntimeEvent = RuntimeEvent;
682
	type OnSystemEvent = ();
683
	type SelfParaId = ParachainInfo;
684
	type ReservedDmpWeight = ReservedDmpWeight;
685
	type OutboundXcmpMessageSource = XcmpQueue;
686
	type XcmpMessageHandler = XcmpQueue;
687
	type ReservedXcmpWeight = ReservedXcmpWeight;
688
	type CheckAssociatedRelayNumber = EmergencyParaXcm;
689
	type ConsensusHook = ConsensusHookWrapperForRelayTimestamp<Runtime, ConsensusHook>;
690
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
691
	type WeightInfo = moonbeam_weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
692
}
693

            
694
pub struct EthereumXcmEnsureProxy;
695
impl xcm_primitives::EnsureProxy<AccountId> for EthereumXcmEnsureProxy {
696
	fn ensure_ok(delegator: AccountId, delegatee: AccountId) -> Result<(), &'static str> {
697
		// The EVM implicitely contains an Any proxy, so we only allow for "Any" proxies
698
		let def: pallet_proxy::ProxyDefinition<AccountId, ProxyType, BlockNumber> =
699
			pallet_proxy::Pallet::<Runtime>::find_proxy(
700
				&delegator,
701
				&delegatee,
702
				Some(ProxyType::Any),
703
			)
704
			.map_err(|_| "proxy error: expected `ProxyType::Any`")?;
705
		// We only allow to use it for delay zero proxies, as the call will immediatly be executed
706
		ensure!(def.delay.is_zero(), "proxy delay is Non-zero`");
707
		Ok(())
708
	}
709
}
710

            
711
impl pallet_ethereum_xcm::Config for Runtime {
712
	type RuntimeEvent = RuntimeEvent;
713
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
714
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
715
	type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
716
	type ReservedXcmpWeight = ReservedXcmpWeight;
717
	type EnsureProxy = EthereumXcmEnsureProxy;
718
	type ControllerOrigin = EnsureRoot<AccountId>;
719
	type ForceOrigin = EnsureRoot<AccountId>;
720
}
721

            
722
parameter_types! {
723
	// Reserved weight is 1/4 of MAXIMUM_BLOCK_WEIGHT
724
	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
725
	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
726
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
727
}
728

            
729
impl parachain_info::Config for Runtime {}
730

            
731
pub struct OnNewRound;
732
impl pallet_parachain_staking::OnNewRound for OnNewRound {
733
24
	fn on_new_round(round_index: pallet_parachain_staking::RoundIndex) -> Weight {
734
24
		MoonbeamOrbiters::on_new_round(round_index)
735
24
	}
736
}
737
pub struct PayoutCollatorOrOrbiterReward;
738
impl pallet_parachain_staking::PayoutCollatorReward<Runtime> for PayoutCollatorOrOrbiterReward {
739
12
	fn payout_collator_reward(
740
12
		for_round: pallet_parachain_staking::RoundIndex,
741
12
		collator_id: AccountId,
742
12
		amount: Balance,
743
12
	) -> Weight {
744
12
		let extra_weight =
745
12
			if MoonbeamOrbiters::is_collator_pool_with_active_orbiter(for_round, collator_id) {
746
				MoonbeamOrbiters::distribute_rewards(for_round, collator_id, amount)
747
			} else {
748
12
				ParachainStaking::mint_collator_reward(for_round, collator_id, amount)
749
			};
750

            
751
12
		<Runtime as frame_system::Config>::DbWeight::get()
752
12
			.reads(1)
753
12
			.saturating_add(extra_weight)
754
12
	}
755
}
756

            
757
pub struct OnInactiveCollator;
758
impl pallet_parachain_staking::OnInactiveCollator<Runtime> for OnInactiveCollator {
759
	fn on_inactive_collator(
760
		collator_id: AccountId,
761
		round: pallet_parachain_staking::RoundIndex,
762
	) -> Result<Weight, DispatchErrorWithPostInfo<PostDispatchInfo>> {
763
		let extra_weight = if !MoonbeamOrbiters::is_collator_pool_with_active_orbiter(
764
			round,
765
			collator_id.clone(),
766
		) {
767
			ParachainStaking::go_offline_inner(collator_id)?;
768
			<Runtime as pallet_parachain_staking::Config>::WeightInfo::go_offline(
769
				pallet_parachain_staking::MAX_CANDIDATES,
770
			)
771
		} else {
772
			Weight::zero()
773
		};
774

            
775
		Ok(<Runtime as frame_system::Config>::DbWeight::get()
776
			.reads(1)
777
			.saturating_add(extra_weight))
778
	}
779
}
780
type MonetaryGovernanceOrigin =
781
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
782

            
783
pub struct RelayChainSlotProvider;
784
impl Get<Slot> for RelayChainSlotProvider {
785
24
	fn get() -> Slot {
786
24
		let slot_info = pallet_async_backing::pallet::Pallet::<Runtime>::slot_info();
787
24
		slot_info.unwrap_or_default().0
788
24
	}
789
}
790

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

            
835
impl pallet_author_inherent::Config for Runtime {
836
	type SlotBeacon = RelaychainDataProvider<Self>;
837
	type AccountLookup = MoonbeamOrbiters;
838
	type CanAuthor = AuthorFilter;
839
	type AuthorId = AccountId;
840
	type WeightInfo = moonbeam_weights::pallet_author_inherent::WeightInfo<Runtime>;
841
}
842

            
843
impl pallet_author_slot_filter::Config for Runtime {
844
	type RuntimeEvent = RuntimeEvent;
845
	type RandomnessSource = Randomness;
846
	type PotentialAuthors = ParachainStaking;
847
	type WeightInfo = moonbeam_weights::pallet_author_slot_filter::WeightInfo<Runtime>;
848
}
849

            
850
impl pallet_async_backing::Config for Runtime {
851
	type AllowMultipleBlocksPerSlot = ConstBool<true>;
852
	type GetAndVerifySlot = pallet_async_backing::RelaySlot;
853
	type ExpectedBlockTime = ConstU64<6000>;
854
}
855

            
856
parameter_types! {
857
	pub const InitializationPayment: Perbill = Perbill::from_percent(30);
858
	pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100);
859
	pub const SignatureNetworkIdentifier:  &'static [u8] = b"moonbeam-";
860
}
861

            
862
impl pallet_crowdloan_rewards::Config for Runtime {
863
	type RuntimeEvent = RuntimeEvent;
864
	type Initialized = ConstBool<false>;
865
	type InitializationPayment = InitializationPayment;
866
	type MaxInitContributors = ConstU32<500>;
867
	type MinimumReward = ConstU128<0>;
868
	type RewardCurrency = Balances;
869
	type RelayChainAccountId = [u8; 32];
870
	type RewardAddressAssociateOrigin = EnsureSigned<Self::AccountId>;
871
	type RewardAddressChangeOrigin = EnsureSigned<Self::AccountId>;
872
	type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold;
873
	type SignatureNetworkIdentifier = SignatureNetworkIdentifier;
874
	type VestingBlockNumber = relay_chain::BlockNumber;
875
	type VestingBlockProvider = RelaychainDataProvider<Self>;
876
	type WeightInfo = moonbeam_weights::pallet_crowdloan_rewards::WeightInfo<Runtime>;
877
}
878

            
879
// This is a simple session key manager. It should probably either work with, or be replaced
880
// entirely by pallet sessions
881
impl pallet_author_mapping::Config for Runtime {
882
	type RuntimeEvent = RuntimeEvent;
883
	type DepositCurrency = Balances;
884
	type DepositAmount = ConstU128<{ 100 * currency::GLMR * currency::SUPPLY_FACTOR }>;
885
	type Keys = session_keys_primitives::VrfId;
886
	type WeightInfo = moonbeam_weights::pallet_author_mapping::WeightInfo<Runtime>;
887
}
888

            
889
/// The type used to represent the kinds of proxying allowed.
890
#[derive(
891
	Copy,
892
	Clone,
893
	Eq,
894
	PartialEq,
895
	Ord,
896
	PartialOrd,
897
	Encode,
898
	Decode,
899
	Debug,
900
6
	MaxEncodedLen,
901
48
	TypeInfo,
902
	Serialize,
903
	Deserialize,
904
)]
905
pub enum ProxyType {
906
	/// All calls can be proxied. This is the trivial/most permissive filter.
907
	Any = 0,
908
	/// Only extrinsics that do not transfer funds.
909
	NonTransfer = 1,
910
	/// Only extrinsics related to governance (democracy and collectives).
911
	Governance = 2,
912
	/// Only extrinsics related to staking.
913
	Staking = 3,
914
	/// Allow to veto an announced proxy call.
915
	CancelProxy = 4,
916
	/// Allow extrinsic related to Balances.
917
	Balances = 5,
918
	/// Allow extrinsic related to AuthorMapping.
919
	AuthorMapping = 6,
920
	/// Allow extrinsic related to IdentityJudgement.
921
	IdentityJudgement = 7,
922
}
923

            
924
impl Default for ProxyType {
925
	fn default() -> Self {
926
		Self::Any
927
	}
928
}
929

            
930
fn is_governance_precompile(precompile_name: &precompiles::PrecompileName) -> bool {
931
	matches!(
932
		precompile_name,
933
		PrecompileName::ConvictionVotingPrecompile
934
			| PrecompileName::PreimagePrecompile
935
			| PrecompileName::ReferendaPrecompile
936
			| PrecompileName::OpenTechCommitteeInstance
937
			| PrecompileName::TreasuryCouncilInstance
938
	)
939
}
940

            
941
// Be careful: Each time this filter is modified, the substrate filter must also be modified
942
// consistently.
943
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
944
	fn is_evm_proxy_call_allowed(
945
		&self,
946
		call: &pallet_evm_precompile_proxy::EvmSubCall,
947
		recipient_has_code: bool,
948
		gas: u64,
949
	) -> precompile_utils::EvmResult<bool> {
950
		Ok(match self {
951
			ProxyType::Any => {
952
				match PrecompileName::from_address(call.to.0) {
953
					// Any precompile that can execute a subcall should be forbidden here,
954
					// to ensure that unauthorized smart contract can't be called
955
					// indirectly.
956
					// To be safe, we only allow the precompiles we need.
957
					Some(
958
						PrecompileName::AuthorMappingPrecompile
959
						| PrecompileName::ParachainStakingPrecompile,
960
					) => true,
961
					Some(ref precompile) if is_governance_precompile(precompile) => true,
962
					// All non-whitelisted precompiles are forbidden
963
					Some(_) => false,
964
					// Allow evm transfer to "simple" account (no code nor precompile)
965
					// For the moment, no smart contract other than precompiles is allowed.
966
					// In the future, we may create a dynamic whitelist to authorize some audited
967
					// smart contracts through governance.
968
					None => {
969
						// If the address is not recognized, allow only evm transfer to "simple"
970
						// accounts (no code nor precompile).
971
						// Note: Checking the presence of the code is not enough because some
972
						// precompiles have no code.
973
						!recipient_has_code
974
							&& !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
975
								call.to.0, gas,
976
							)?
977
					}
978
				}
979
			}
980
			ProxyType::NonTransfer => {
981
				call.value == U256::zero()
982
					&& match PrecompileName::from_address(call.to.0) {
983
						Some(
984
							PrecompileName::AuthorMappingPrecompile
985
							| PrecompileName::ParachainStakingPrecompile,
986
						) => true,
987
						Some(ref precompile) if is_governance_precompile(precompile) => true,
988
						_ => false,
989
					}
990
			}
991
			ProxyType::Governance => {
992
				call.value == U256::zero()
993
					&& matches!(
994
						PrecompileName::from_address(call.to.0),
995
						Some(ref precompile) if is_governance_precompile(precompile)
996
					)
997
			}
998
			ProxyType::Staking => {
999
				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 {
198
	fn contains(c: &RuntimeCall) -> bool {
198
		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,
156
			_ => true,
		}
198
	}
}
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>;
}
1222662
construct_runtime! {
	pub enum Runtime
	{
		// System support stuff.
		System: frame_system::{Pallet, Call, Storage, Config<T>, Event<T>} = 0,
		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>} = 1,
		// Previously 2: pallet_randomness_collective_flip
		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 3,
		ParachainInfo: parachain_info::{Pallet, Storage, Config<T>} = 4,
		RootTesting: pallet_root_testing::{Pallet, Call, Storage, Event<T>} = 5,
		// Monetary stuff.
		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 10,
		TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Config<T>, Event<T>} = 11,
		// Consensus support.
		ParachainStaking: pallet_parachain_staking::{Pallet, Call, Storage, Event<T>, Config<T>} = 20,
		AuthorInherent: pallet_author_inherent::{Pallet, Call, Storage, Inherent} = 21,
		AuthorFilter: pallet_author_slot_filter::{Pallet, Call, Storage, Event, Config<T>} = 22,
		AuthorMapping: pallet_author_mapping::{Pallet, Call, Config<T>, Storage, Event<T>} = 23,
		MoonbeamOrbiters: pallet_moonbeam_orbiters::{Pallet, Call, Storage, Event<T>} = 24,
		AsyncBacking: pallet_async_backing::{Pallet, Storage} = 25,
		// Handy utilities.
		Utility: pallet_utility::{Pallet, Call, Event} = 30,
		Proxy: pallet_proxy::{Pallet, Call, Storage, Event<T>} = 31,
		MaintenanceMode: pallet_maintenance_mode::{Pallet, Call, Config<T>, Storage, Event} = 32,
		Identity: pallet_identity::{Pallet, Call, Storage, Event<T>} = 33,
		Migrations: pallet_migrations::{Pallet, Storage, Config<T>, Event<T>} = 34,
		ProxyGenesisCompanion: pallet_proxy_genesis_companion::{Pallet, Config<T>} = 35,
		Multisig: pallet_multisig::{Pallet, Call, Storage, Event<T>} = 36,
		MoonbeamLazyMigrations: pallet_moonbeam_lazy_migrations::{Pallet, Call, Storage} = 37,
		Parameters: pallet_parameters = 38,
		// Has been permanently removed for safety reasons.
		// Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>} = 40,
		// Ethereum compatibility.
		EthereumChainId: pallet_evm_chain_id::{Pallet, Storage, Config<T>} = 50,
		EVM: pallet_evm::{Pallet, Config<T>, Call, Storage, Event<T>} = 51,
		Ethereum: pallet_ethereum::{Pallet, Call, Storage, Event, Origin, Config<T>} = 52,
		// Governance stuff.
		Scheduler: pallet_scheduler::{Pallet, Storage, Event<T>, Call} = 60,
		// Democracy: 61,
		Preimage: pallet_preimage::{Pallet, Call, Storage, Event<T>, HoldReason} = 62,
		ConvictionVoting: pallet_conviction_voting::{Pallet, Call, Storage, Event<T>} = 63,
		Referenda: pallet_referenda::{Pallet, Call, Storage, Event<T>} = 64,
		Origins: governance::custom_origins::{Origin} = 65,
		Whitelist: pallet_whitelist::{Pallet, Call, Storage, Event<T>} = 66,
		// Council stuff.
		// CouncilCollective: 70
		// TechCommitteeCollective: 71
		TreasuryCouncilCollective:
			pallet_collective::<Instance3>::{Pallet, Call, Storage, Event<T>, Origin<T>, Config<T>} = 72,
		OpenTechCommitteeCollective:
			pallet_collective::<Instance4>::{Pallet, Call, Storage, Event<T>, Origin<T>, Config<T>} = 73,
		// Treasury stuff.
		Treasury: pallet_treasury::{Pallet, Storage, Config<T>, Event<T>, Call} = 80,
		// Crowdloan stuff.
		CrowdloanRewards: pallet_crowdloan_rewards::{Pallet, Call, Config<T>, Storage, Event<T>} = 90,
		// XCM
		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 100,
		CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 101,
		// Previously 102: DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>}
		PolkadotXcm: pallet_xcm::{Pallet, Storage, Call, Event<T>, Origin, Config<T>} = 103,
		Assets: pallet_assets::{Pallet, Call, Storage, Event<T>} = 104,
		AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event<T>} = 105,
		// Previously 106: XTokens
		XcmTransactor: pallet_xcm_transactor::{Pallet, Call, Storage, Event<T>} = 107,
		// Previously 108: pallet_assets::<Instance1>
		EthereumXcm: pallet_ethereum_xcm::{Pallet, Call, Storage, Origin, Event<T>} = 109,
		Erc20XcmBridge: pallet_erc20_xcm_bridge::{Pallet} = 110,
		MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 111,
		EvmForeignAssets: pallet_moonbeam_foreign_assets::{Pallet, Call, Storage, Event<T>} = 114,
		XcmWeightTrader: pallet_xcm_weight_trader::{Pallet, Call, Storage, Event<T>} = 115,
		EmergencyParaXcm: pallet_emergency_para_xcm::{Pallet, Call, Storage, Event} = 116,
		// Utils
		RelayStorageRoots: pallet_relay_storage_roots::{Pallet, Storage} = 112,
		// TODO should not be included in production
		PrecompileBenchmarks: pallet_precompile_benchmarks::{Pallet} = 113,
		// Randomness
		Randomness: pallet_randomness::{Pallet, Call, Storage, Event<T>, Inherent} = 120,
	}
7892372
}
#[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 {
	// TODO: Temporary workaround before upgrading to latest polkadot-sdk - fix https://github.com/paritytech/polkadot-sdk/pull/6435
	#[allow(unused_imports)]
	use pallet_collective as pallet_collective_treasury_council;
	#[allow(unused_imports)]
	use pallet_collective as pallet_collective_open_tech_committee;
	frame_support::parameter_types! {
		pub const MaxBalance: crate::Balance = crate::Balance::max_value();
	}
	frame_benchmarking::define_benchmarks!(
		[frame_system, SystemBench::<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_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_moonbeam_lazy_migrations, MoonbeamLazyMigrations]
		[pallet_relay_storage_roots, RelayStorageRoots]
		[pallet_precompile_benchmarks, PrecompileBenchmarks]
		[pallet_parameters, Parameters]
		[pallet_xcm_weight_trader, XcmWeightTrader]
		[pallet_collective_treasury_council, TreasuryCouncilCollective]
		[pallet_collective_open_tech_committee, 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.
// }
// ```
48
moonbeam_runtime_common::impl_runtime_apis_plus_common! {
48
	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
48
		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) {
48
				return InvalidTransaction::Call.into();
48
			}
48

            
48
			// This runtime uses Substrate's pallet transaction payment. This
48
			// makes the chain feel like a standard Substrate chain when submitting
48
			// frame transactions and using Substrate ecosystem tools. It has the downside that
48
			// transaction are not prioritized by gas_price. The following code reprioritizes
48
			// transactions to overcome this.
48
			//
48
			// A more elegant, ethereum-first solution is
48
			// a pallet that replaces pallet transaction payment, and allows users
48
			// to directly specify a gas price rather than computing an effective one.
48
			// #HopefullySomeday
48

            
48
			// First we pass the transactions to the standard FRAME executive. This calculates all the
48
			// necessary tags, longevity and other properties that we will leave unchanged.
48
			// This also assigns some priority that we don't care about and will overwrite next.
48
			let mut intermediate_valid = Executive::validate_transaction(source, xt.clone(), block_hash)?;
48

            
48
			let dispatch_info = xt.get_dispatch_info();
48

            
48
			// If this is a pallet ethereum transaction, then its priority is already set
48
			// according to gas price from pallet ethereum. If it is any other kind of transaction,
48
			// we modify its priority.
48
			Ok(match &xt.0.function {
48
				RuntimeCall::Ethereum(transact { .. }) => intermediate_valid,
48
				_ if dispatch_info.class != DispatchClass::Normal => intermediate_valid,
48
				_ => {
48
					let tip = match xt.0.signature {
48
						None => 0,
48
						Some((_, _, ref signed_extra)) => {
							// Yuck, this depends on the index of charge transaction in Signed Extra
							let charge_transaction = &signed_extra.7;
							charge_transaction.tip()
48
						}
48
					};
48

            
48
					// Calculate the fee that will be taken by pallet transaction payment
48
					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.weight
						);
48

            
48
					// Here we calculate an ethereum-style effective gas price using the
48
					// current fee of the transaction. Because the weight -> gas conversion is
48
					// lossy, we have to handle the case where a very low weight maps to zero gas.
48
					let effective_gas_price = if effective_gas > 0 {
48
						fee / effective_gas
48
					} else {
48
						// If the effective gas was zero, we just act like it was 1.
48
						fee
48
					};
48

            
48
					// Overwrite the original prioritization with this ethereum one
48
					intermediate_valid.priority = effective_gas_price;
					intermediate_valid
48
				}
48
			})
48
		}
48
	}
48

            
48
	impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
48
		fn can_build_upon(
			included_hash: <Block as BlockT>::Hash,
			slot: async_backing_primitives::Slot,
		) -> bool {
			ConsensusHook::can_build_upon(included_hash, slot)
		}
48
	}
48
}
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() {
1
		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
	}
}