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 Moonriver Runtime.
18
//!
19
//! Primary features of this runtime include:
20
//! * Ethereum compatibility
21
//! * Moonriver tokenomics
22

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

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

            
31
extern crate alloc;
32

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

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

            
117
use runtime_params::*;
118

            
119
use smallvec::smallvec;
120
#[cfg(feature = "std")]
121
use sp_version::NativeVersion;
122
use sp_version::RuntimeVersion;
123

            
124
use nimbus_primitives::CanAuthor;
125

            
126
pub use precompiles::{
127
	MoonriverPrecompiles, PrecompileName, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
128
};
129

            
130
#[cfg(any(feature = "std", test))]
131
pub use sp_runtime::BuildStorage;
132

            
133
pub type Precompiles = MoonriverPrecompiles<Runtime>;
134

            
135
pub mod asset_config;
136
#[cfg(not(feature = "disable-genesis-builder"))]
137
pub mod genesis_config_preset;
138
pub mod governance;
139
pub mod runtime_params;
140
pub mod xcm_config;
141

            
142
mod migrations;
143
mod precompiles;
144
mod weights;
145

            
146
pub(crate) use weights as moonriver_weights;
147

            
148
pub use governance::councils::*;
149

            
150
/// MOVR, the native token, uses 18 decimals of precision.
151
pub mod currency {
152
	use super::Balance;
153

            
154
	// Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
155
	pub const SUPPLY_FACTOR: Balance = 1;
156

            
157
	pub const WEI: Balance = 1;
158
	pub const KILOWEI: Balance = 1_000;
159
	pub const MEGAWEI: Balance = 1_000_000;
160
	pub const GIGAWEI: Balance = 1_000_000_000;
161
	pub const MICROMOVR: Balance = 1_000_000_000_000;
162
	pub const MILLIMOVR: Balance = 1_000_000_000_000_000;
163
	pub const MOVR: Balance = 1_000_000_000_000_000_000;
164
	pub const KILOMOVR: Balance = 1_000_000_000_000_000_000_000;
165

            
166
	pub const TRANSACTION_BYTE_FEE: Balance = 1 * GIGAWEI * SUPPLY_FACTOR;
167
	pub const STORAGE_BYTE_FEE: Balance = 100 * MICROMOVR * SUPPLY_FACTOR;
168
	pub const WEIGHT_FEE: Balance = 50 * KILOWEI * SUPPLY_FACTOR / 4;
169

            
170
28
	pub const fn deposit(items: u32, bytes: u32) -> Balance {
171
28
		items as Balance * 1 * MOVR * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
172
28
	}
173
}
174

            
175
/// Maximum PoV size we support right now.
176
// Kusama relay already supports 10Mb maximum PoV
177
// Reference: https://github.com/polkadot-fellows/runtimes/pull/553
178
pub const MAX_POV_SIZE: u32 = 10 * 1024 * 1024;
179

            
180
/// Maximum weight per block
181
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
182
	WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
183
	MAX_POV_SIZE as u64,
184
);
185

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

            
198
	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
199
	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
200

            
201
	impl_opaque_keys! {
202
		pub struct SessionKeys {
203
			pub nimbus: AuthorInherent,
204
			pub vrf: session_keys_primitives::VrfSessionKey,
205
		}
206
	}
207
}
208

            
209
/// This runtime version.
210
/// The spec_version is composed of 2x2 digits. The first 2 digits represent major changes
211
/// that can't be skipped, such as data migration upgrades. The last 2 digits represent minor
212
/// changes which can be skipped.
213
#[sp_version::runtime_version]
214
pub const VERSION: RuntimeVersion = RuntimeVersion {
215
	spec_name: Cow::Borrowed("moonriver"),
216
	impl_name: Cow::Borrowed("moonriver"),
217
	authoring_version: 3,
218
	spec_version: 3800,
219
	impl_version: 0,
220
	apis: RUNTIME_API_VERSIONS,
221
	transaction_version: 3,
222
	system_version: 1,
223
};
224

            
225
/// The version information used to identify this runtime when compiled natively.
226
#[cfg(feature = "std")]
227
pub fn native_version() -> NativeVersion {
228
	NativeVersion {
229
		runtime_version: VERSION,
230
		can_author_with: Default::default(),
231
	}
232
}
233

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

            
242
pub struct RuntimeBlockWeights;
243
impl Get<frame_system::limits::BlockWeights> for RuntimeBlockWeights {
244
421156
	fn get() -> frame_system::limits::BlockWeights {
245
421156
		frame_system::limits::BlockWeights::builder()
246
421156
			.for_class(DispatchClass::Normal, |weights| {
247
421156
				weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT;
248
421156
				weights.max_total = NORMAL_WEIGHT.into();
249
421156
			})
250
421156
			.for_class(DispatchClass::Operational, |weights| {
251
421156
				weights.max_total = MAXIMUM_BLOCK_WEIGHT.into();
252
421156
				weights.reserved = (MAXIMUM_BLOCK_WEIGHT - NORMAL_WEIGHT).into();
253
421156
			})
254
421156
			.avg_block_initialization(Perbill::from_percent(10))
255
421156
			.build()
256
421156
			.expect("Provided BlockWeight definitions are valid, qed")
257
421156
	}
258
}
259

            
260
parameter_types! {
261
	pub const Version: RuntimeVersion = VERSION;
262
	/// We allow for 5 MB blocks.
263
	pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
264
		::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
265
}
266

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

            
315
impl pallet_utility::Config for Runtime {
316
	type RuntimeEvent = RuntimeEvent;
317
	type RuntimeCall = RuntimeCall;
318
	type PalletsOrigin = OriginCaller;
319
	type WeightInfo = moonriver_weights::pallet_utility::WeightInfo<Runtime>;
320
}
321

            
322
impl pallet_timestamp::Config for Runtime {
323
	/// A timestamp: milliseconds since the unix epoch.
324
	type Moment = u64;
325
	type OnTimestampSet = ();
326
	type MinimumPeriod = ConstU64<3000>;
327
	type WeightInfo = moonriver_weights::pallet_timestamp::WeightInfo<Runtime>;
328
}
329

            
330
#[cfg(not(feature = "runtime-benchmarks"))]
331
parameter_types! {
332
	pub const ExistentialDeposit: Balance = 0;
333
}
334

            
335
#[cfg(feature = "runtime-benchmarks")]
336
parameter_types! {
337
	pub const ExistentialDeposit: Balance = 1;
338
}
339

            
340
impl pallet_balances::Config for Runtime {
341
	type MaxReserves = ConstU32<50>;
342
	type ReserveIdentifier = [u8; 4];
343
	type MaxLocks = ConstU32<50>;
344
	/// The type for recording an account's balance.
345
	type Balance = Balance;
346
	/// The ubiquitous event type.
347
	type RuntimeEvent = RuntimeEvent;
348
	type DustRemoval = ();
349
	type ExistentialDeposit = ExistentialDeposit;
350
	type AccountStore = System;
351
	type FreezeIdentifier = ();
352
	type MaxFreezes = ConstU32<0>;
353
	type RuntimeHoldReason = RuntimeHoldReason;
354
	type RuntimeFreezeReason = RuntimeFreezeReason;
355
	type WeightInfo = moonriver_weights::pallet_balances::WeightInfo<Runtime>;
356
	type DoneSlashHandler = ();
357
}
358

            
359
pub struct LengthToFee;
360
impl WeightToFeePolynomial for LengthToFee {
361
	type Balance = Balance;
362

            
363
77
	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
364
77
		smallvec![
365
			WeightToFeeCoefficient {
366
				degree: 1,
367
				coeff_frac: Perbill::zero(),
368
				coeff_integer: currency::TRANSACTION_BYTE_FEE,
369
				negative: false,
370
			},
371
			WeightToFeeCoefficient {
372
				degree: 3,
373
				coeff_frac: Perbill::zero(),
374
				coeff_integer: 1 * currency::SUPPLY_FACTOR,
375
				negative: false,
376
			},
377
		]
378
77
	}
379
}
380

            
381
impl pallet_transaction_payment::Config for Runtime {
382
	type RuntimeEvent = RuntimeEvent;
383
	type OnChargeTransaction = FungibleAdapter<
384
		Balances,
385
		DealWithSubstrateFeesAndTip<
386
			Runtime,
387
			dynamic_params::runtime_config::FeesTreasuryProportion,
388
		>,
389
	>;
390
	type OperationalFeeMultiplier = ConstU8<5>;
391
	type WeightToFee = ConstantMultiplier<Balance, ConstU128<{ currency::WEIGHT_FEE }>>;
392
	type LengthToFee = LengthToFee;
393
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime>;
394
	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
395
}
396

            
397
impl pallet_evm_chain_id::Config for Runtime {}
398

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

            
405
/// Approximate ratio of the amount of Weight per Gas.
406
/// u64 works for approximations because Weight is a very small unit compared to gas.
407
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
408

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

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

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

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

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

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

            
498
impl<Inner> FindAuthor<H160> for FindAuthorAdapter<Inner>
499
where
500
	Inner: FindAuthor<AccountId20>,
501
{
502
6831
	fn find_author<'a, I>(digests: I) -> Option<H160>
503
6831
	where
504
6831
		I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
505
6831
	{
506
6831
		Inner::find_author(digests).map(Into::into)
507
6831
	}
508
}
509

            
510
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
511

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

            
540
parameter_types! {
541
	pub MaxServiceWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
542
}
543

            
544
impl pallet_scheduler::Config for Runtime {
545
	type RuntimeEvent = RuntimeEvent;
546
	type RuntimeOrigin = RuntimeOrigin;
547
	type PalletsOrigin = OriginCaller;
548
	type RuntimeCall = RuntimeCall;
549
	type MaximumWeight = MaxServiceWeight;
550
	type ScheduleOrigin = EnsureRoot<AccountId>;
551
	type MaxScheduledPerBlock = ConstU32<50>;
552
	type WeightInfo = moonriver_weights::pallet_scheduler::WeightInfo<Runtime>;
553
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
554
	type Preimages = Preimage;
555
}
556

            
557
parameter_types! {
558
	pub const PreimageBaseDeposit: Balance = 5 * currency::MOVR * currency::SUPPLY_FACTOR ;
559
	pub const PreimageByteDeposit: Balance = currency::STORAGE_BYTE_FEE;
560
	pub const PreimageHoldReason: RuntimeHoldReason =
561
		RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
562
}
563

            
564
impl pallet_preimage::Config for Runtime {
565
	type WeightInfo = moonriver_weights::pallet_preimage::WeightInfo<Runtime>;
566
	type RuntimeEvent = RuntimeEvent;
567
	type Currency = Balances;
568
	type ManagerOrigin = EnsureRoot<AccountId>;
569
	type Consideration = HoldConsideration<
570
		AccountId,
571
		Balances,
572
		PreimageHoldReason,
573
		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
574
	>;
575
}
576

            
577
parameter_types! {
578
	pub const ProposalBond: Permill = Permill::from_percent(5);
579
	pub const TreasuryId: PalletId = PalletId(*b"py/trsry");
580
	pub TreasuryAccount: AccountId = Treasury::account_id();
581
	pub const MaxSpendBalance: crate::Balance = crate::Balance::max_value();
582
}
583

            
584
type RootOrTreasuryCouncilOrigin = EitherOfDiverse<
585
	EnsureRoot<AccountId>,
586
	pallet_collective::EnsureProportionMoreThan<AccountId, TreasuryCouncilInstance, 1, 2>,
587
>;
588

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

            
614
parameter_types! {
615
	pub const MaxSubAccounts: u32 = 100;
616
	pub const MaxAdditionalFields: u32 = 100;
617
	pub const MaxRegistrars: u32 = 20;
618
	pub const PendingUsernameExpiration: u32 = 7 * DAYS;
619
	pub const MaxSuffixLength: u32 = 7;
620
	pub const MaxUsernameLength: u32 = 32;
621
}
622

            
623
type IdentityForceOrigin =
624
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
625
type IdentityRegistrarOrigin =
626
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
627

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

            
654
pub struct TransactionConverter;
655

            
656
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
657
21
	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
658
21
		UncheckedExtrinsic::new_bare(
659
21
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
660
21
		)
661
21
	}
662
}
663

            
664
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
665
	fn convert_transaction(
666
		&self,
667
		transaction: pallet_ethereum::Transaction,
668
	) -> opaque::UncheckedExtrinsic {
669
		let extrinsic = UncheckedExtrinsic::new_bare(
670
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
671
		);
672
		let encoded = extrinsic.encode();
673
		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
674
			.expect("Encoded extrinsic is always valid")
675
	}
676
}
677

            
678
parameter_types! {
679
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
680
}
681

            
682
impl pallet_ethereum::Config for Runtime {
683
	type RuntimeEvent = RuntimeEvent;
684
	type StateRoot =
685
		pallet_ethereum::IntermediateStateRoot<<Runtime as frame_system::Config>::Version>;
686
	type PostLogContent = PostBlockAndTxnHashes;
687
	type ExtraDataLength = ConstU32<30>;
688
}
689

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

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

            
718
parameter_types! {
719
	// Reserved weight is 1/4 of MAXIMUM_BLOCK_WEIGHT
720
	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
721
	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
722
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
723
}
724

            
725
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
726
/// into the relay chain.
727
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
728
/// How many parachain blocks are processed by the relay chain per parent. Limits the
729
/// number of blocks authored per slot.
730
const BLOCK_PROCESSING_VELOCITY: u32 = 1;
731

            
732
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
733
	Runtime,
734
	BLOCK_PROCESSING_VELOCITY,
735
	UNINCLUDED_SEGMENT_CAPACITY,
736
>;
737

            
738
impl cumulus_pallet_parachain_system::Config for Runtime {
739
	type RuntimeEvent = RuntimeEvent;
740
	type OnSystemEvent = ();
741
	type SelfParaId = ParachainInfo;
742
	type ReservedDmpWeight = ReservedDmpWeight;
743
	type OutboundXcmpMessageSource = XcmpQueue;
744
	type XcmpMessageHandler = XcmpQueue;
745
	type ReservedXcmpWeight = ReservedXcmpWeight;
746
	type CheckAssociatedRelayNumber = EmergencyParaXcm;
747
	type ConsensusHook = ConsensusHookWrapperForRelayTimestamp<Runtime, ConsensusHook>;
748
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
749
	type WeightInfo = moonriver_weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
750
	type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
751
}
752

            
753
impl parachain_info::Config for Runtime {}
754

            
755
pub struct OnNewRound;
756
impl pallet_parachain_staking::OnNewRound for OnNewRound {
757
35
	fn on_new_round(round_index: pallet_parachain_staking::RoundIndex) -> Weight {
758
35
		MoonbeamOrbiters::on_new_round(round_index)
759
35
	}
760
}
761
pub struct PayoutCollatorOrOrbiterReward;
762
impl pallet_parachain_staking::PayoutCollatorReward<Runtime> for PayoutCollatorOrOrbiterReward {
763
14
	fn payout_collator_reward(
764
14
		for_round: pallet_parachain_staking::RoundIndex,
765
14
		collator_id: AccountId,
766
14
		amount: Balance,
767
14
	) -> Weight {
768
14
		let extra_weight =
769
14
			if MoonbeamOrbiters::is_collator_pool_with_active_orbiter(for_round, collator_id) {
770
				MoonbeamOrbiters::distribute_rewards(for_round, collator_id, amount)
771
			} else {
772
14
				ParachainStaking::mint_collator_reward(for_round, collator_id, amount)
773
			};
774

            
775
14
		<Runtime as frame_system::Config>::DbWeight::get()
776
14
			.reads(1)
777
14
			.saturating_add(extra_weight)
778
14
	}
779
}
780

            
781
pub struct OnInactiveCollator;
782
impl pallet_parachain_staking::OnInactiveCollator<Runtime> for OnInactiveCollator {
783
	fn on_inactive_collator(
784
		collator_id: AccountId,
785
		round: pallet_parachain_staking::RoundIndex,
786
	) -> Result<Weight, DispatchErrorWithPostInfo<PostDispatchInfo>> {
787
		let extra_weight = if !MoonbeamOrbiters::is_collator_pool_with_active_orbiter(
788
			round,
789
			collator_id.clone(),
790
		) {
791
			ParachainStaking::go_offline_inner(collator_id)?;
792
			<Runtime as pallet_parachain_staking::Config>::WeightInfo::go_offline(
793
				pallet_parachain_staking::MAX_CANDIDATES,
794
			)
795
		} else {
796
			Weight::zero()
797
		};
798

            
799
		Ok(<Runtime as frame_system::Config>::DbWeight::get()
800
			.reads(1)
801
			.saturating_add(extra_weight))
802
	}
803
}
804

            
805
type MonetaryGovernanceOrigin =
806
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
807

            
808
pub struct RelayChainSlotProvider;
809
impl Get<Slot> for RelayChainSlotProvider {
810
35
	fn get() -> Slot {
811
35
		let slot_info = pallet_async_backing::pallet::Pallet::<Runtime>::slot_info();
812
35
		slot_info.unwrap_or_default().0
813
35
	}
814
}
815

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

            
860
impl pallet_author_inherent::Config for Runtime {
861
	type SlotBeacon = RelaychainDataProvider<Self>;
862
	type AccountLookup = MoonbeamOrbiters;
863
	type CanAuthor = AuthorFilter;
864
	type AuthorId = AccountId;
865
	type WeightInfo = moonriver_weights::pallet_author_inherent::WeightInfo<Runtime>;
866
}
867

            
868
impl pallet_author_slot_filter::Config for Runtime {
869
	type RuntimeEvent = RuntimeEvent;
870
	type RandomnessSource = Randomness;
871
	type PotentialAuthors = ParachainStaking;
872
	type WeightInfo = moonriver_weights::pallet_author_slot_filter::WeightInfo<Runtime>;
873
}
874

            
875
impl pallet_async_backing::Config for Runtime {
876
	type AllowMultipleBlocksPerSlot = ConstBool<true>;
877
	type GetAndVerifySlot = pallet_async_backing::RelaySlot;
878
	type ExpectedBlockTime = ConstU64<6000>;
879
}
880

            
881
parameter_types! {
882
	pub const InitializationPayment: Perbill = Perbill::from_percent(30);
883
	pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100);
884
	pub const SignatureNetworkIdentifier:  &'static [u8] = b"moonriver-";
885

            
886
}
887

            
888
impl pallet_crowdloan_rewards::Config for Runtime {
889
	type RuntimeEvent = RuntimeEvent;
890
	type Initialized = ConstBool<false>;
891
	type InitializationPayment = InitializationPayment;
892
	type MaxInitContributors = ConstU32<500>;
893
	type MinimumReward = ConstU128<0>;
894
	type RewardCurrency = Balances;
895
	type RelayChainAccountId = [u8; 32];
896
	type RewardAddressAssociateOrigin = EnsureSigned<Self::AccountId>;
897
	type RewardAddressChangeOrigin = EnsureSigned<Self::AccountId>;
898
	type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold;
899
	type SignatureNetworkIdentifier = SignatureNetworkIdentifier;
900
	type VestingBlockNumber = relay_chain::BlockNumber;
901
	type VestingBlockProvider = RelaychainDataProvider<Self>;
902
	type WeightInfo = moonriver_weights::pallet_crowdloan_rewards::WeightInfo<Runtime>;
903
}
904

            
905
// This is a simple session key manager. It should probably either work with, or be replaced
906
// entirely by pallet sessions
907
impl pallet_author_mapping::Config for Runtime {
908
	type RuntimeEvent = RuntimeEvent;
909
	type DepositCurrency = Balances;
910
	type DepositAmount = ConstU128<{ 100 * currency::MOVR * currency::SUPPLY_FACTOR }>;
911
	type Keys = session_keys_primitives::VrfId;
912
	type WeightInfo = moonriver_weights::pallet_author_mapping::WeightInfo<Runtime>;
913
}
914

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

            
950
impl Default for ProxyType {
951
	fn default() -> Self {
952
		Self::Any
953
	}
954
}
955

            
956
fn is_governance_precompile(precompile_name: &precompiles::PrecompileName) -> bool {
957
	matches!(
958
		precompile_name,
959
		PrecompileName::TreasuryCouncilInstance
960
			| PrecompileName::PreimagePrecompile
961
			| PrecompileName::ReferendaPrecompile
962
			| PrecompileName::ConvictionVotingPrecompile
963
			| PrecompileName::OpenTechCommitteeInstance
964
	)
965
}
966

            
967
// Be careful: Each time this filter is modified, the substrate filter must also be modified
968
// consistently.
969
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
970
	fn is_evm_proxy_call_allowed(
971
		&self,
972
		call: &pallet_evm_precompile_proxy::EvmSubCall,
973
		recipient_has_code: bool,
974
		gas: u64,
975
	) -> precompile_utils::EvmResult<bool> {
976
		Ok(match self {
977
			ProxyType::Any => {
978
				match PrecompileName::from_address(call.to.0) {
979
					// Any precompile that can execute a subcall should be forbidden here,
980
					// to ensure that unauthorized smart contract can't be called
981
					// indirectly.
982
					// To be safe, we only allow the precompiles we need.
983
					Some(
984
						PrecompileName::AuthorMappingPrecompile
985
						| PrecompileName::ParachainStakingPrecompile,
986
					) => true,
987
					Some(ref precompile) if is_governance_precompile(precompile) => true,
988
					// All non-whitelisted precompiles are forbidden
989
					Some(_) => false,
990
					// Allow evm transfer to "simple" account (no code nor precompile)
991
					// For the moment, no smart contract other than precompiles is allowed.
992
					// In the future, we may create a dynamic whitelist to authorize some audited
993
					// smart contracts through governance.
994
					None => {
995
						// If the address is not recognized, allow only evm transfert to "simple"
996
						// accounts (no code nor precompile).
997
						// Note: Checking the presence of the code is not enough because some
998
						// precompiles have no code.
999
						!recipient_has_code
							&& !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
								call.to.0, gas,
							)?
					}
				}
			}
			ProxyType::NonTransfer => {
				call.value == U256::zero()
					&& match PrecompileName::from_address(call.to.0) {
						Some(
							PrecompileName::AuthorMappingPrecompile
							| PrecompileName::ParachainStakingPrecompile,
						) => true,
						Some(ref precompile) if is_governance_precompile(precompile) => true,
						_ => false,
					}
			}
			ProxyType::Governance => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(ref precompile) if is_governance_precompile(precompile)
					)
			}
			ProxyType::Staking => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(
							PrecompileName::AuthorMappingPrecompile
								| PrecompileName::ParachainStakingPrecompile
						)
					)
			}
			// The proxy precompile does not contain method cancel_proxy
			ProxyType::CancelProxy => false,
			ProxyType::Balances => {
				// Allow only "simple" accounts as recipient (no code nor precompile).
				// Note: Checking the presence of the code is not enough because some precompiles
				// have no code.
				!recipient_has_code
					&& !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
						call.to.0, gas,
					)?
			}
			ProxyType::AuthorMapping => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(PrecompileName::AuthorMappingPrecompile)
					)
			}
			// There is no identity precompile
			ProxyType::IdentityJudgement => false,
		})
	}
}
// Be careful: Each time this filter is modified, the EVM filter must also be modified consistently.
impl InstanceFilter<RuntimeCall> for ProxyType {
	fn filter(&self, c: &RuntimeCall) -> bool {
		match self {
			ProxyType::Any => true,
			ProxyType::NonTransfer => match c {
				RuntimeCall::Identity(
					pallet_identity::Call::add_sub { .. } | pallet_identity::Call::set_subs { .. },
				) => false,
				call => {
					matches!(
						call,
						RuntimeCall::System(..)
							| RuntimeCall::ParachainSystem(..)
							| RuntimeCall::Timestamp(..)
							| RuntimeCall::ParachainStaking(..)
							| RuntimeCall::Referenda(..)
							| RuntimeCall::Preimage(..)
							| RuntimeCall::ConvictionVoting(..)
							| RuntimeCall::TreasuryCouncilCollective(..)
							| RuntimeCall::OpenTechCommitteeCollective(..)
							| RuntimeCall::Utility(..)
							| RuntimeCall::Proxy(..)
							| RuntimeCall::Identity(..)
							| RuntimeCall::AuthorMapping(..)
							| RuntimeCall::CrowdloanRewards(
								pallet_crowdloan_rewards::Call::claim { .. }
							)
					)
				}
			},
			ProxyType::Governance => matches!(
				c,
				RuntimeCall::Referenda(..)
					| RuntimeCall::Preimage(..)
					| RuntimeCall::ConvictionVoting(..)
					| RuntimeCall::TreasuryCouncilCollective(..)
					| RuntimeCall::OpenTechCommitteeCollective(..)
					| RuntimeCall::Utility(..)
			),
			ProxyType::Staking => matches!(
				c,
				RuntimeCall::ParachainStaking(..)
					| RuntimeCall::Utility(..)
					| RuntimeCall::AuthorMapping(..)
					| RuntimeCall::MoonbeamOrbiters(..)
			),
			ProxyType::CancelProxy => matches!(
				c,
				RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
			),
			ProxyType::Balances => {
				matches!(c, RuntimeCall::Balances(..) | RuntimeCall::Utility(..))
			}
			ProxyType::AuthorMapping => matches!(c, RuntimeCall::AuthorMapping(..)),
			ProxyType::IdentityJudgement => matches!(
				c,
				RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
					| RuntimeCall::Utility(..)
			),
		}
	}
	fn is_superset(&self, o: &Self) -> bool {
		match (self, o) {
			(x, y) if x == y => true,
			(ProxyType::Any, _) => true,
			(_, ProxyType::Any) => false,
			_ => false,
		}
	}
}
impl pallet_proxy::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeCall = RuntimeCall;
	type Currency = Balances;
	type ProxyType = ProxyType;
	// One storage item; key size 32, value size 8
	type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
	// Additional storage item size of 21 bytes (20 bytes AccountId + 1 byte sizeof(ProxyType)).
	type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 21) }>;
	type MaxProxies = ConstU32<32>;
	type WeightInfo = moonriver_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::MoonriverMigrations,
	);
	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 = moonriver_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 {
266
	fn contains(c: &RuntimeCall) -> bool {
266
		match c {
21
			RuntimeCall::Assets(method) => match method {
7
				pallet_assets::Call::transfer { .. } => true,
				pallet_assets::Call::transfer_keep_alive { .. } => true,
7
				pallet_assets::Call::approve_transfer { .. } => true,
7
				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
28
			RuntimeCall::PolkadotXcm(method) => match method {
				pallet_xcm::Call::force_default_xcm_version { .. } => true,
21
				pallet_xcm::Call::transfer_assets { .. } => true,
				pallet_xcm::Call::transfer_assets_using_type_and_then { .. } => true,
7
				_ => 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,
217
			_ => true,
		}
266
	}
}
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<3>;
	/// Round index type.
	type RoundIndex = pallet_parachain_staking::RoundIndex;
	type WeightInfo = moonriver_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 = moonriver_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 = moonriver_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 = moonriver_weights::pallet_relay_storage_roots::WeightInfo<Runtime>;
}
impl pallet_precompile_benchmarks::Config for Runtime {
	type WeightInfo = moonriver_weights::pallet_precompile_benchmarks::WeightInfo<Runtime>;
}
impl pallet_parameters::Config for Runtime {
	type AdminOrigin = EnsureRoot<AccountId>;
	type RuntimeEvent = RuntimeEvent;
	type RuntimeParameters = RuntimeParameters;
	type WeightInfo = moonriver_weights::pallet_parameters::WeightInfo<Runtime>;
}
impl pallet_multiblock_migrations::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	// TODO fully replace pallet_migrations with multiblock migrations.
	#[cfg(not(feature = "runtime-benchmarks"))]
	type Migrations = pallet_identity::migration::v2::LazyMigrationV1ToV2<Runtime>;
	// Benchmarks need mocked migrations to guarantee that they succeed.
	#[cfg(feature = "runtime-benchmarks")]
	type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
	type CursorMaxLen = ConstU32<65_536>;
	type IdentifierMaxLen = ConstU32<256>;
	type MigrationStatusHandler = ();
	type FailedMigrationHandler = MaintenanceMode;
	type MaxServiceWeight = MaxServiceWeight;
	type WeightInfo = weights::pallet_multiblock_migrations::WeightInfo<Runtime>;
}
746264
construct_runtime! {
10186
	pub enum Runtime
10186
	{
10186
		// System support stuff.
10186
		System: frame_system::{Pallet, Call, Storage, Config<T>, Event<T>} = 0,
10186
		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>} = 1,
10186
		// Previously 2: pallet_randomness_collective_flip
10186
		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 3,
10186
		ParachainInfo: parachain_info::{Pallet, Storage, Config<T>} = 4,
10186
		RootTesting: pallet_root_testing::{Pallet, Call, Storage, Event<T>} = 5,
10186

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

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

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

            
10186
		// Sudo was previously index 40
10186

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

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

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

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

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

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

            
10186
		// Utils
10186
		RelayStorageRoots: pallet_relay_storage_roots::{Pallet, Storage} = 112,
10186
		PrecompileBenchmarks: pallet_precompile_benchmarks::{Pallet} = 113,
10186

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