1
// Copyright 2019-2022 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, EitherOfDiverse,
51
		EqualPrivilegeOnly, InstanceFilter, LinearStoragePrice, OnFinalize, OnUnbalanced,
52
	},
53
	weights::{
54
		constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, Weight, WeightToFeeCoefficient,
55
		WeightToFeeCoefficients, WeightToFeePolynomial,
56
	},
57
	PalletId,
58
};
59
use frame_system::{EnsureRoot, EnsureSigned};
60
pub use moonbeam_core_primitives::{
61
	AccountId, AccountIndex, Address, AssetId, Balance, BlockNumber, DigestItem, Hash, Header,
62
	Index, Signature,
63
};
64
use moonbeam_rpc_primitives_txpool::TxPoolResponse;
65
use moonbeam_runtime_common::timestamp::{ConsensusHookWrapperForRelayTimestamp, RelayTimestamp};
66
pub use pallet_author_slot_filter::EligibilityValue;
67
use pallet_ethereum::Call::transact;
68
use pallet_ethereum::{PostLogContent, Transaction as EthereumTransaction};
69
use pallet_evm::{
70
	Account as EVMAccount, EVMFungibleAdapter, EnsureAddressNever, EnsureAddressRoot,
71
	FeeCalculator, FrameSystemAccountProvider, GasWeightMapping, IdentityAddressMapping,
72
	OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner,
73
};
74
pub use pallet_parachain_staking::{weights::WeightInfo, InflationInfo, Range};
75
use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment};
76
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
77
use scale_info::TypeInfo;
78
use serde::{Deserialize, Serialize};
79
use smallvec::smallvec;
80
use sp_api::impl_runtime_apis;
81
use sp_consensus_slots::Slot;
82
use sp_core::{OpaqueMetadata, H160, H256, U256};
83
use sp_runtime::{
84
	create_runtime_str, generic, impl_opaque_keys,
85
	traits::{
86
		BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, IdentityLookup,
87
		PostDispatchInfoOf, UniqueSaturatedInto, Zero,
88
	},
89
	transaction_validity::{
90
		InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
91
	},
92
	ApplyExtrinsicResult, DispatchErrorWithPostInfo, FixedPointNumber, Perbill, Permill,
93
	Perquintill, SaturatedConversion,
94
};
95
use sp_std::{convert::TryFrom, prelude::*};
96
use xcm::{VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm};
97
use xcm_runtime_apis::{
98
	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
99
	fees::Error as XcmPaymentApiError,
100
};
101

            
102
use runtime_params::*;
103

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

            
108
use nimbus_primitives::CanAuthor;
109

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

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

            
119
pub type Precompiles = MoonbeamPrecompiles<Runtime>;
120

            
121
pub mod asset_config;
122
pub mod governance;
123
pub mod runtime_params;
124
mod weights;
125
pub mod xcm_config;
126

            
127
use governance::councils::*;
128
pub(crate) use weights as moonbeam_weights;
129

            
130
/// GLMR, the native token, uses 18 decimals of precision.
131
pub mod currency {
132
	use super::Balance;
133

            
134
	// Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
135
	pub const SUPPLY_FACTOR: Balance = 100;
136

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

            
146
	pub const TRANSACTION_BYTE_FEE: Balance = 1 * GIGAWEI * SUPPLY_FACTOR;
147
	pub const STORAGE_BYTE_FEE: Balance = 100 * MICROGLMR * SUPPLY_FACTOR;
148
	pub const WEIGHT_FEE: Balance = 50 * KILOWEI * SUPPLY_FACTOR / 4;
149

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

            
155
/// Maximum weight per block
156
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, u64::MAX)
157
	.saturating_mul(2)
158
	.set_proof_size(relay_chain::MAX_POV_SIZE as u64);
159

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

            
173
	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
174
	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
175

            
176
	impl_opaque_keys! {
177
		pub struct SessionKeys {
178
			pub nimbus: AuthorInherent,
179
			pub vrf: session_keys_primitives::VrfSessionKey,
180
		}
181
	}
182
}
183

            
184
/// This runtime version.
185
/// The spec_version is composed of 2x2 digits. The first 2 digits represent major changes
186
/// that can't be skipped, such as data migration upgrades. The last 2 digits represent minor
187
/// changes which can be skipped.
188
#[sp_version::runtime_version]
189
pub const VERSION: RuntimeVersion = RuntimeVersion {
190
	spec_name: create_runtime_str!("moonbeam"),
191
	impl_name: create_runtime_str!("moonbeam"),
192
	authoring_version: 3,
193
	spec_version: 3500,
194
	impl_version: 0,
195
	apis: RUNTIME_API_VERSIONS,
196
	transaction_version: 3,
197
	state_version: 1,
198
};
199

            
200
/// The version information used to identify this runtime when compiled natively.
201
#[cfg(feature = "std")]
202
pub fn native_version() -> NativeVersion {
203
	NativeVersion {
204
		runtime_version: VERSION,
205
		can_author_with: Default::default(),
206
	}
207
}
208

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

            
217
pub struct RuntimeBlockWeights;
218
impl Get<frame_system::limits::BlockWeights> for RuntimeBlockWeights {
219
360780
	fn get() -> frame_system::limits::BlockWeights {
220
360780
		frame_system::limits::BlockWeights::builder()
221
360780
			.for_class(DispatchClass::Normal, |weights| {
222
360780
				weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT;
223
360780
				weights.max_total = NORMAL_WEIGHT.into();
224
360780
			})
225
360780
			.for_class(DispatchClass::Operational, |weights| {
226
360780
				weights.max_total = MAXIMUM_BLOCK_WEIGHT.into();
227
360780
				weights.reserved = (MAXIMUM_BLOCK_WEIGHT - NORMAL_WEIGHT).into();
228
360780
			})
229
360780
			.avg_block_initialization(Perbill::from_percent(10))
230
360780
			.build()
231
360780
			.expect("Provided BlockWeight definitions are valid, qed")
232
360780
	}
233
}
234

            
235
parameter_types! {
236
	pub const Version: RuntimeVersion = VERSION;
237
	/// We allow for 5 MB blocks.
238
	pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
239
		::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
240
}
241

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

            
289
impl pallet_utility::Config for Runtime {
290
	type RuntimeEvent = RuntimeEvent;
291
	type RuntimeCall = RuntimeCall;
292
	type PalletsOrigin = OriginCaller;
293
	type WeightInfo = moonbeam_weights::pallet_utility::WeightInfo<Runtime>;
294
}
295

            
296
impl pallet_timestamp::Config for Runtime {
297
	/// A timestamp: milliseconds since the unix epoch.
298
	type Moment = u64;
299
	type OnTimestampSet = ();
300
	type MinimumPeriod = ConstU64<3000>;
301
	type WeightInfo = moonbeam_weights::pallet_timestamp::WeightInfo<Runtime>;
302
}
303

            
304
#[cfg(not(feature = "runtime-benchmarks"))]
305
parameter_types! {
306
	pub const ExistentialDeposit: Balance = 0;
307
}
308

            
309
#[cfg(feature = "runtime-benchmarks")]
310
parameter_types! {
311
	pub const ExistentialDeposit: Balance = 1;
312
}
313

            
314
impl pallet_balances::Config for Runtime {
315
	type MaxReserves = ConstU32<50>;
316
	type ReserveIdentifier = [u8; 4];
317
	type MaxLocks = ConstU32<50>;
318
	/// The type for recording an account's balance.
319
	type Balance = Balance;
320
	/// The ubiquitous event type.
321
	type RuntimeEvent = RuntimeEvent;
322
	type DustRemoval = ();
323
	type ExistentialDeposit = ExistentialDeposit;
324
	type AccountStore = System;
325
	type FreezeIdentifier = ();
326
	type MaxFreezes = ConstU32<0>;
327
	type RuntimeHoldReason = RuntimeHoldReason;
328
	type RuntimeFreezeReason = RuntimeFreezeReason;
329
	type WeightInfo = moonbeam_weights::pallet_balances::WeightInfo<Runtime>;
330
}
331

            
332
pub struct LengthToFee;
333
impl WeightToFeePolynomial for LengthToFee {
334
	type Balance = Balance;
335

            
336
66
	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
337
66
		smallvec![
338
			WeightToFeeCoefficient {
339
				degree: 1,
340
66
				coeff_frac: Perbill::zero(),
341
				coeff_integer: currency::TRANSACTION_BYTE_FEE,
342
				negative: false,
343
			},
344
			WeightToFeeCoefficient {
345
				degree: 3,
346
66
				coeff_frac: Perbill::zero(),
347
66
				coeff_integer: 1 * currency::SUPPLY_FACTOR,
348
				negative: false,
349
			},
350
		]
351
66
	}
352
}
353

            
354
impl pallet_transaction_payment::Config for Runtime {
355
	type RuntimeEvent = RuntimeEvent;
356
	type OnChargeTransaction = FungibleAdapter<
357
		Balances,
358
		DealWithSubstrateFeesAndTip<
359
			Runtime,
360
			dynamic_params::runtime_config::FeesTreasuryProportion,
361
		>,
362
	>;
363
	type OperationalFeeMultiplier = ConstU8<5>;
364
	type WeightToFee = ConstantMultiplier<Balance, ConstU128<{ currency::WEIGHT_FEE }>>;
365
	type LengthToFee = LengthToFee;
366
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime>;
367
}
368

            
369
impl pallet_evm_chain_id::Config for Runtime {}
370

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

            
377
/// Approximate ratio of the amount of Weight per Gas.
378
/// u64 works for approximations because Weight is a very small unit compared to gas.
379
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
380

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

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

            
438
/// Parameterized slow adjusting fee updated based on
439
/// https://w3f-research.readthedocs.io/en/latest/polkadot/overview/2-token-economics.html#-2.-slow-adjusting-mechanism // editorconfig-checker-disable-line
440
///
441
/// The adjustment algorithm boils down to:
442
///
443
/// diff = (previous_block_weight - target) / maximum_block_weight
444
/// next_multiplier = prev_multiplier * (1 + (v * diff) + ((v * diff)^2 / 2))
445
/// assert(next_multiplier > min)
446
///     where: v is AdjustmentVariable
447
///            target is TargetBlockFullness
448
///            min is MinimumMultiplier
449
pub type SlowAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
450
	R,
451
	TargetBlockFullness,
452
	AdjustmentVariable,
453
	MinimumMultiplier,
454
	MaximumMultiplier,
455
>;
456

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

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

            
465
impl<Inner> FindAuthor<H160> for FindAuthorAdapter<Inner>
466
where
467
	Inner: FindAuthor<AccountId20>,
468
{
469
16375
	fn find_author<'a, I>(digests: I) -> Option<H160>
470
16375
	where
471
16375
		I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
472
16375
	{
473
16375
		Inner::find_author(digests).map(Into::into)
474
16375
	}
475
}
476

            
477
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
478

            
479
impl pallet_evm::Config for Runtime {
480
	type FeeCalculator = TransactionPaymentAsGasPrice;
481
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
482
	type WeightPerGas = WeightPerGas;
483
	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
484
	type CallOrigin = EnsureAddressRoot<AccountId>;
485
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
486
	type AddressMapping = IdentityAddressMapping;
487
	type Currency = Balances;
488
	type RuntimeEvent = RuntimeEvent;
489
	type Runner = pallet_evm::runner::stack::Runner<Self>;
490
	type PrecompilesType = MoonbeamPrecompiles<Self>;
491
	type PrecompilesValue = PrecompilesValue;
492
	type ChainId = EthereumChainId;
493
	type OnChargeTransaction = OnChargeEVMTransaction<
494
		DealWithEthereumBaseFees<Runtime, dynamic_params::runtime_config::FeesTreasuryProportion>,
495
		DealWithEthereumPriorityFees<Runtime>,
496
	>;
497
	type BlockGasLimit = BlockGasLimit;
498
	type FindAuthor = FindAuthorAdapter<AuthorInherent>;
499
	type OnCreate = ();
500
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
501
	type SuicideQuickClearLimit = ConstU32<0>;
502
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
503
	type Timestamp = RelayTimestamp;
504
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
505
	type WeightInfo = moonbeam_weights::pallet_evm::WeightInfo<Runtime>;
506
}
507

            
508
parameter_types! {
509
	pub MaximumSchedulerWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
510
}
511

            
512
impl pallet_scheduler::Config for Runtime {
513
	type RuntimeEvent = RuntimeEvent;
514
	type RuntimeOrigin = RuntimeOrigin;
515
	type PalletsOrigin = OriginCaller;
516
	type RuntimeCall = RuntimeCall;
517
	type MaximumWeight = MaximumSchedulerWeight;
518
	type ScheduleOrigin = EnsureRoot<AccountId>;
519
	type MaxScheduledPerBlock = ConstU32<50>;
520
	type WeightInfo = moonbeam_weights::pallet_scheduler::WeightInfo<Runtime>;
521
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
522
	type Preimages = Preimage;
523
}
524

            
525
parameter_types! {
526
	pub const PreimageBaseDeposit: Balance = 5 * currency::GLMR * currency::SUPPLY_FACTOR ;
527
	pub const PreimageByteDeposit: Balance = currency::STORAGE_BYTE_FEE;
528
	pub const PreimageHoldReason: RuntimeHoldReason =
529
		RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
530
}
531

            
532
impl pallet_preimage::Config for Runtime {
533
	type WeightInfo = moonbeam_weights::pallet_preimage::WeightInfo<Runtime>;
534
	type RuntimeEvent = RuntimeEvent;
535
	type Currency = Balances;
536
	type ManagerOrigin = EnsureRoot<AccountId>;
537
	type Consideration = HoldConsideration<
538
		AccountId,
539
		Balances,
540
		PreimageHoldReason,
541
		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
542
	>;
543
}
544

            
545
parameter_types! {
546
	pub const ProposalBond: Permill = Permill::from_percent(5);
547
	pub const TreasuryId: PalletId = PalletId(*b"py/trsry");
548
	pub TreasuryAccount: AccountId = Treasury::account_id();
549
	pub const MaxSpendBalance: crate::Balance = crate::Balance::max_value();
550
}
551

            
552
type RootOrTreasuryCouncilOrigin = EitherOfDiverse<
553
	EnsureRoot<AccountId>,
554
	pallet_collective::EnsureProportionMoreThan<AccountId, TreasuryCouncilInstance, 1, 2>,
555
>;
556

            
557
impl pallet_treasury::Config for Runtime {
558
	type PalletId = TreasuryId;
559
	type Currency = Balances;
560
	// More than half of the council is required (or root) to reject a proposal
561
	type RejectOrigin = RootOrTreasuryCouncilOrigin;
562
	type RuntimeEvent = RuntimeEvent;
563
	type SpendPeriod = ConstU32<{ 6 * DAYS }>;
564
	type Burn = ();
565
	type BurnDestination = ();
566
	type MaxApprovals = ConstU32<100>;
567
	type WeightInfo = moonbeam_weights::pallet_treasury::WeightInfo<Runtime>;
568
	type SpendFunds = ();
569
	type SpendOrigin =
570
		frame_system::EnsureWithSuccess<RootOrTreasuryCouncilOrigin, AccountId, MaxSpendBalance>;
571
	type AssetKind = ();
572
	type Beneficiary = AccountId;
573
	type BeneficiaryLookup = IdentityLookup<AccountId>;
574
	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
575
	type BalanceConverter = UnityAssetBalanceConversion;
576
	type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
577
	#[cfg(feature = "runtime-benchmarks")]
578
	type BenchmarkHelper = BenchmarkHelper;
579
}
580

            
581
parameter_types! {
582
	pub const MaxSubAccounts: u32 = 100;
583
	pub const MaxAdditionalFields: u32 = 100;
584
	pub const MaxRegistrars: u32 = 20;
585
	pub const PendingUsernameExpiration: u32 = 7 * DAYS;
586
	pub const MaxSuffixLength: u32 = 7;
587
	pub const MaxUsernameLength: u32 = 32;
588
}
589

            
590
type IdentityForceOrigin =
591
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
592
type IdentityRegistrarOrigin =
593
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
594

            
595
impl pallet_identity::Config for Runtime {
596
	type RuntimeEvent = RuntimeEvent;
597
	type Currency = Balances;
598
	// Add one item in storage and take 258 bytes
599
	type BasicDeposit = ConstU128<{ currency::deposit(1, 258) }>;
600
	// Does not add any item to the storage but takes 1 bytes
601
	type ByteDeposit = ConstU128<{ currency::deposit(0, 1) }>;
602
	// Add one item in storage and take 53 bytes
603
	type SubAccountDeposit = ConstU128<{ currency::deposit(1, 53) }>;
604
	type MaxSubAccounts = MaxSubAccounts;
605
	type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
606
	type MaxRegistrars = MaxRegistrars;
607
	type Slashed = Treasury;
608
	type ForceOrigin = IdentityForceOrigin;
609
	type RegistrarOrigin = IdentityRegistrarOrigin;
610
	type OffchainSignature = Signature;
611
	type SigningPublicKey = <Signature as sp_runtime::traits::Verify>::Signer;
612
	type UsernameAuthorityOrigin = EnsureRoot<AccountId>;
613
	type PendingUsernameExpiration = PendingUsernameExpiration;
614
	type MaxSuffixLength = MaxSuffixLength;
615
	type MaxUsernameLength = MaxUsernameLength;
616
	type WeightInfo = moonbeam_weights::pallet_identity::WeightInfo<Runtime>;
617
}
618

            
619
pub struct TransactionConverter;
620

            
621
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
622
21
	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
623
21
		UncheckedExtrinsic::new_unsigned(
624
21
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
625
21
		)
626
21
	}
627
}
628

            
629
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
630
	fn convert_transaction(
631
		&self,
632
		transaction: pallet_ethereum::Transaction,
633
	) -> opaque::UncheckedExtrinsic {
634
		let extrinsic = UncheckedExtrinsic::new_unsigned(
635
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
636
		);
637
		let encoded = extrinsic.encode();
638
		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
639
			.expect("Encoded extrinsic is always valid")
640
	}
641
}
642

            
643
parameter_types! {
644
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
645
}
646

            
647
impl pallet_ethereum::Config for Runtime {
648
	type RuntimeEvent = RuntimeEvent;
649
	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
650
	type PostLogContent = PostBlockAndTxnHashes;
651
	type ExtraDataLength = ConstU32<30>;
652
}
653

            
654
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
655
/// into the relay chain.
656
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
657
/// How many parachain blocks are processed by the relay chain per parent. Limits the
658
/// number of blocks authored per slot.
659
const BLOCK_PROCESSING_VELOCITY: u32 = 1;
660

            
661
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
662
	Runtime,
663
	BLOCK_PROCESSING_VELOCITY,
664
	UNINCLUDED_SEGMENT_CAPACITY,
665
>;
666

            
667
impl cumulus_pallet_parachain_system::Config for Runtime {
668
	type RuntimeEvent = RuntimeEvent;
669
	type OnSystemEvent = ();
670
	type SelfParaId = ParachainInfo;
671
	type ReservedDmpWeight = ReservedDmpWeight;
672
	type OutboundXcmpMessageSource = XcmpQueue;
673
	type XcmpMessageHandler = XcmpQueue;
674
	type ReservedXcmpWeight = ReservedXcmpWeight;
675
	type CheckAssociatedRelayNumber = EmergencyParaXcm;
676
	type ConsensusHook = ConsensusHookWrapperForRelayTimestamp<Runtime, ConsensusHook>;
677
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
678
	type WeightInfo = moonbeam_weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
679
}
680

            
681
pub struct EthereumXcmEnsureProxy;
682
impl xcm_primitives::EnsureProxy<AccountId> for EthereumXcmEnsureProxy {
683
	fn ensure_ok(delegator: AccountId, delegatee: AccountId) -> Result<(), &'static str> {
684
		// The EVM implicitely contains an Any proxy, so we only allow for "Any" proxies
685
		let def: pallet_proxy::ProxyDefinition<AccountId, ProxyType, BlockNumber> =
686
			pallet_proxy::Pallet::<Runtime>::find_proxy(
687
				&delegator,
688
				&delegatee,
689
				Some(ProxyType::Any),
690
			)
691
			.map_err(|_| "proxy error: expected `ProxyType::Any`")?;
692
		// We only allow to use it for delay zero proxies, as the call will immediatly be executed
693
		ensure!(def.delay.is_zero(), "proxy delay is Non-zero`");
694
		Ok(())
695
	}
696
}
697

            
698
impl pallet_ethereum_xcm::Config for Runtime {
699
	type RuntimeEvent = RuntimeEvent;
700
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
701
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
702
	type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
703
	type ReservedXcmpWeight = ReservedXcmpWeight;
704
	type EnsureProxy = EthereumXcmEnsureProxy;
705
	type ControllerOrigin = EnsureRoot<AccountId>;
706
	type ForceOrigin = EnsureRoot<AccountId>;
707
}
708

            
709
parameter_types! {
710
	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
711
	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
712
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
713
}
714

            
715
impl parachain_info::Config for Runtime {}
716

            
717
pub struct OnNewRound;
718
impl pallet_parachain_staking::OnNewRound for OnNewRound {
719
24
	fn on_new_round(round_index: pallet_parachain_staking::RoundIndex) -> Weight {
720
24
		MoonbeamOrbiters::on_new_round(round_index)
721
24
	}
722
}
723
pub struct PayoutCollatorOrOrbiterReward;
724
impl pallet_parachain_staking::PayoutCollatorReward<Runtime> for PayoutCollatorOrOrbiterReward {
725
12
	fn payout_collator_reward(
726
12
		for_round: pallet_parachain_staking::RoundIndex,
727
12
		collator_id: AccountId,
728
12
		amount: Balance,
729
12
	) -> Weight {
730
12
		let extra_weight =
731
12
			if MoonbeamOrbiters::is_collator_pool_with_active_orbiter(for_round, collator_id) {
732
				MoonbeamOrbiters::distribute_rewards(for_round, collator_id, amount)
733
			} else {
734
12
				ParachainStaking::mint_collator_reward(for_round, collator_id, amount)
735
			};
736

            
737
12
		<Runtime as frame_system::Config>::DbWeight::get()
738
12
			.reads(1)
739
12
			.saturating_add(extra_weight)
740
12
	}
741
}
742

            
743
pub struct OnInactiveCollator;
744
impl pallet_parachain_staking::OnInactiveCollator<Runtime> for OnInactiveCollator {
745
	fn on_inactive_collator(
746
		collator_id: AccountId,
747
		round: pallet_parachain_staking::RoundIndex,
748
	) -> Result<Weight, DispatchErrorWithPostInfo<PostDispatchInfo>> {
749
		let extra_weight = if !MoonbeamOrbiters::is_collator_pool_with_active_orbiter(
750
			round,
751
			collator_id.clone(),
752
		) {
753
			ParachainStaking::go_offline_inner(collator_id)?;
754
			<Runtime as pallet_parachain_staking::Config>::WeightInfo::go_offline(
755
				pallet_parachain_staking::MAX_CANDIDATES,
756
			)
757
		} else {
758
			Weight::zero()
759
		};
760

            
761
		Ok(<Runtime as frame_system::Config>::DbWeight::get()
762
			.reads(1)
763
			.saturating_add(extra_weight))
764
	}
765
}
766
type MonetaryGovernanceOrigin =
767
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
768

            
769
pub struct RelayChainSlotProvider;
770
impl Get<Slot> for RelayChainSlotProvider {
771
24
	fn get() -> Slot {
772
24
		let slot_info = pallet_async_backing::pallet::Pallet::<Runtime>::slot_info();
773
24
		slot_info.unwrap_or_default().0
774
24
	}
775
}
776

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

            
821
impl pallet_author_inherent::Config for Runtime {
822
	type SlotBeacon = RelaychainDataProvider<Self>;
823
	type AccountLookup = MoonbeamOrbiters;
824
	type CanAuthor = AuthorFilter;
825
	type AuthorId = AccountId;
826
	type WeightInfo = moonbeam_weights::pallet_author_inherent::WeightInfo<Runtime>;
827
}
828

            
829
impl pallet_author_slot_filter::Config for Runtime {
830
	type RuntimeEvent = RuntimeEvent;
831
	type RandomnessSource = Randomness;
832
	type PotentialAuthors = ParachainStaking;
833
	type WeightInfo = moonbeam_weights::pallet_author_slot_filter::WeightInfo<Runtime>;
834
}
835

            
836
impl pallet_async_backing::Config for Runtime {
837
	type AllowMultipleBlocksPerSlot = ConstBool<true>;
838
	type GetAndVerifySlot = pallet_async_backing::RelaySlot;
839
	type ExpectedBlockTime = ConstU64<6000>;
840
}
841

            
842
parameter_types! {
843
	pub const InitializationPayment: Perbill = Perbill::from_percent(30);
844
	pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100);
845
	pub const SignatureNetworkIdentifier:  &'static [u8] = b"moonbeam-";
846
}
847

            
848
impl pallet_crowdloan_rewards::Config for Runtime {
849
	type RuntimeEvent = RuntimeEvent;
850
	type Initialized = ConstBool<false>;
851
	type InitializationPayment = InitializationPayment;
852
	type MaxInitContributors = ConstU32<500>;
853
	type MinimumReward = ConstU128<0>;
854
	type RewardCurrency = Balances;
855
	type RelayChainAccountId = [u8; 32];
856
	type RewardAddressAssociateOrigin = EnsureSigned<Self::AccountId>;
857
	type RewardAddressChangeOrigin = EnsureSigned<Self::AccountId>;
858
	type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold;
859
	type SignatureNetworkIdentifier = SignatureNetworkIdentifier;
860
	type VestingBlockNumber = relay_chain::BlockNumber;
861
	type VestingBlockProvider = RelaychainDataProvider<Self>;
862
	type WeightInfo = moonbeam_weights::pallet_crowdloan_rewards::WeightInfo<Runtime>;
863
}
864

            
865
// This is a simple session key manager. It should probably either work with, or be replaced
866
// entirely by pallet sessions
867
impl pallet_author_mapping::Config for Runtime {
868
	type RuntimeEvent = RuntimeEvent;
869
	type DepositCurrency = Balances;
870
	type DepositAmount = ConstU128<{ 100 * currency::GLMR * currency::SUPPLY_FACTOR }>;
871
	type Keys = session_keys_primitives::VrfId;
872
	type WeightInfo = moonbeam_weights::pallet_author_mapping::WeightInfo<Runtime>;
873
}
874

            
875
/// The type used to represent the kinds of proxying allowed.
876
#[derive(
877
	Copy,
878
	Clone,
879
	Eq,
880
	PartialEq,
881
	Ord,
882
	PartialOrd,
883
	Encode,
884
	Decode,
885
	Debug,
886
6
	MaxEncodedLen,
887
48
	TypeInfo,
888
	Serialize,
889
	Deserialize,
890
)]
891
pub enum ProxyType {
892
	/// All calls can be proxied. This is the trivial/most permissive filter.
893
	Any = 0,
894
	/// Only extrinsics that do not transfer funds.
895
	NonTransfer = 1,
896
	/// Only extrinsics related to governance (democracy and collectives).
897
	Governance = 2,
898
	/// Only extrinsics related to staking.
899
	Staking = 3,
900
	/// Allow to veto an announced proxy call.
901
	CancelProxy = 4,
902
	/// Allow extrinsic related to Balances.
903
	Balances = 5,
904
	/// Allow extrinsic related to AuthorMapping.
905
	AuthorMapping = 6,
906
	/// Allow extrinsic related to IdentityJudgement.
907
	IdentityJudgement = 7,
908
}
909

            
910
impl Default for ProxyType {
911
	fn default() -> Self {
912
		Self::Any
913
	}
914
}
915

            
916
fn is_governance_precompile(precompile_name: &precompiles::PrecompileName) -> bool {
917
	matches!(
918
		precompile_name,
919
		PrecompileName::ConvictionVotingPrecompile
920
			| PrecompileName::PreimagePrecompile
921
			| PrecompileName::ReferendaPrecompile
922
			| PrecompileName::OpenTechCommitteeInstance
923
			| PrecompileName::TreasuryCouncilInstance
924
	)
925
}
926

            
927
// Be careful: Each time this filter is modified, the substrate filter must also be modified
928
// consistently.
929
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
930
	fn is_evm_proxy_call_allowed(
931
		&self,
932
		call: &pallet_evm_precompile_proxy::EvmSubCall,
933
		recipient_has_code: bool,
934
		gas: u64,
935
	) -> precompile_utils::EvmResult<bool> {
936
		Ok(match self {
937
			ProxyType::Any => {
938
				match PrecompileName::from_address(call.to.0) {
939
					// Any precompile that can execute a subcall should be forbidden here,
940
					// to ensure that unauthorized smart contract can't be called
941
					// indirectly.
942
					// To be safe, we only allow the precompiles we need.
943
					Some(
944
						PrecompileName::AuthorMappingPrecompile
945
						| PrecompileName::ParachainStakingPrecompile,
946
					) => true,
947
					Some(ref precompile) if is_governance_precompile(precompile) => true,
948
					// All non-whitelisted precompiles are forbidden
949
					Some(_) => false,
950
					// Allow evm transfer to "simple" account (no code nor precompile)
951
					// For the moment, no smart contract other than precompiles is allowed.
952
					// In the future, we may create a dynamic whitelist to authorize some audited
953
					// smart contracts through governance.
954
					None => {
955
						// If the address is not recognized, allow only evm transfert to "simple"
956
						// accounts (no code nor precompile).
957
						// Note: Checking the presence of the code is not enough because some
958
						// precompiles have no code.
959
						!recipient_has_code
960
							&& precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
961
								call.to.0, gas,
962
							)?
963
					}
964
				}
965
			}
966
			ProxyType::NonTransfer => {
967
				call.value == U256::zero()
968
					&& match PrecompileName::from_address(call.to.0) {
969
						Some(
970
							PrecompileName::AuthorMappingPrecompile
971
							| PrecompileName::ParachainStakingPrecompile,
972
						) => true,
973
						Some(ref precompile) if is_governance_precompile(precompile) => true,
974
						_ => false,
975
					}
976
			}
977
			ProxyType::Governance => {
978
				call.value == U256::zero()
979
					&& matches!(
980
						PrecompileName::from_address(call.to.0),
981
						Some(ref precompile) if is_governance_precompile(precompile)
982
					)
983
			}
984
			ProxyType::Staking => {
985
				call.value == U256::zero()
986
					&& matches!(
987
						PrecompileName::from_address(call.to.0),
988
						Some(
989
							PrecompileName::AuthorMappingPrecompile
990
								| PrecompileName::ParachainStakingPrecompile
991
						)
992
					)
993
			}
994
			// The proxy precompile does not contain method cancel_proxy
995
			ProxyType::CancelProxy => false,
996
			ProxyType::Balances => {
997
				// Allow only "simple" accounts as recipient (no code nor precompile).
998
				// Note: Checking the presence of the code is not enough because some precompiles
999
				// 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 => {
				matches!(
					c,
					RuntimeCall::System(..)
						| RuntimeCall::ParachainSystem(..)
						| RuntimeCall::Timestamp(..)
						| RuntimeCall::ParachainStaking(..)
						| RuntimeCall::Referenda(..)
						| RuntimeCall::Preimage(..)
						| RuntimeCall::ConvictionVoting(..)
						| RuntimeCall::TreasuryCouncilCollective(..)
						| RuntimeCall::OpenTechCommitteeCollective(..)
						| RuntimeCall::Identity(..)
						| RuntimeCall::Utility(..)
						| RuntimeCall::Proxy(..) | 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>,
		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 {
186
	fn contains(c: &RuntimeCall) -> bool {
186
		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
18
			RuntimeCall::PolkadotXcm(method) => match method {
				pallet_xcm::Call::force_default_xcm_version { .. } => true,
12
				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,
150
			_ => true,
		}
186
	}
}
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>;
}
1189148
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,
	}
7062270
}
#[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!(
		[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]
	);
}
/// 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(2_000_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
	}
}