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
extern crate core;
33

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

            
41
// Re-export required by get! macro.
42
use bp_moonriver::bp_polkadot;
43
use cumulus_primitives_core::{relay_chain, AggregateMessageOrigin};
44
#[cfg(feature = "std")]
45
pub use fp_evm::GenesisAccount;
46
pub use frame_support::traits::Get;
47
use frame_support::{
48
	construct_runtime,
49
	dispatch::{DispatchClass, GetDispatchInfo, PostDispatchInfo},
50
	ensure,
51
	pallet_prelude::DispatchResult,
52
	parameter_types,
53
	traits::{
54
		fungible::{Balanced, Credit, HoldConsideration, Inspect, NativeOrWithId},
55
		ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, EitherOf,
56
		EitherOfDiverse, EqualPrivilegeOnly, InstanceFilter, LinearStoragePrice, OnFinalize,
57
		OnUnbalanced, VariantCountOf,
58
	},
59
	weights::{
60
		constants::WEIGHT_REF_TIME_PER_SECOND, Weight, WeightToFeeCoefficient,
61
		WeightToFeeCoefficients, WeightToFeePolynomial,
62
	},
63
	PalletId,
64
};
65
use frame_system::{EnsureRoot, EnsureSigned};
66
pub use moonbeam_core_primitives::{
67
	AccountId, AccountIndex, Address, AssetId, Balance, BlockNumber, DigestItem, Hash, Header,
68
	Index, Signature,
69
};
70
use moonbeam_rpc_primitives_txpool::TxPoolResponse;
71
use moonbeam_runtime_common::impl_asset_conversion::AssetRateConverter;
72
use moonbeam_runtime_common::{
73
	deal_with_fees::{
74
		DealWithEthereumBaseFees, DealWithEthereumPriorityFees, DealWithSubstrateFeesAndTip,
75
		ProofSizeToFee, RefTimeToFee, WeightToFee,
76
	},
77
	impl_multiasset_paymaster::MultiAssetPaymaster,
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 as codec;
90
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
91
use scale_info::TypeInfo;
92
use sp_api::impl_runtime_apis;
93
use sp_consensus_slots::Slot;
94
use sp_core::{OpaqueMetadata, H160, H256, U256};
95
use sp_runtime::generic::Preamble;
96
use sp_runtime::{
97
	generic, impl_opaque_keys,
98
	serde::{Deserialize, Serialize},
99
	traits::{
100
		BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, IdentityLookup,
101
		PostDispatchInfoOf, UniqueSaturatedInto, Zero,
102
	},
103
	transaction_validity::{
104
		InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
105
	},
106
	ApplyExtrinsicResult, DispatchErrorWithPostInfo, FixedPointNumber, Perbill, Permill,
107
	Perquintill, SaturatedConversion,
108
};
109
use sp_std::{convert::TryFrom, prelude::*};
110
use xcm::{
111
	Version as XcmVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
112
};
113
use xcm_runtime_apis::{
114
	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
115
	fees::Error as XcmPaymentApiError,
116
};
117

            
118
use runtime_params::*;
119

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

            
125
use nimbus_primitives::CanAuthor;
126

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

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

            
134
pub type Precompiles = MoonriverPrecompiles<Runtime>;
135

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

            
144
mod migrations;
145
mod precompiles;
146
mod weights;
147

            
148
pub(crate) use weights as moonriver_weights;
149
pub use weights::xcm as moonriver_xcm_weights;
150

            
151
pub use governance::councils::*;
152

            
153
/// MOVR, the native token, uses 18 decimals of precision.
154
pub mod currency {
155
	use super::Balance;
156

            
157
	// Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
158
	pub const SUPPLY_FACTOR: Balance = 1;
159

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

            
169
	pub const TRANSACTION_BYTE_FEE: Balance = 1 * GIGAWEI * SUPPLY_FACTOR;
170
	pub const STORAGE_BYTE_FEE: Balance = 100 * MICROMOVR * SUPPLY_FACTOR;
171
	pub const WEIGHT_FEE: Balance = 50 * KILOWEI * SUPPLY_FACTOR / 4;
172

            
173
14
	pub const fn deposit(items: u32, bytes: u32) -> Balance {
174
14
		items as Balance * 1 * MOVR * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
175
14
	}
176
}
177

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

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

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

            
201
	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
202
	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
203

            
204
	impl_opaque_keys! {
205
		pub struct SessionKeys {
206
			pub nimbus: AuthorInherent,
207
			pub vrf: session_keys_primitives::VrfSessionKey,
208
		}
209
	}
210
}
211

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

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

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

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

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

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

            
321
impl pallet_utility::Config for Runtime {
322
	type RuntimeEvent = RuntimeEvent;
323
	type RuntimeCall = RuntimeCall;
324
	type PalletsOrigin = OriginCaller;
325
	type WeightInfo = moonriver_weights::pallet_utility::WeightInfo<Runtime>;
326
}
327

            
328
impl pallet_timestamp::Config for Runtime {
329
	/// A timestamp: milliseconds since the unix epoch.
330
	type Moment = u64;
331
	type OnTimestampSet = ();
332
	type MinimumPeriod = ConstU64<{ RELAY_CHAIN_SLOT_DURATION_MILLIS as u64 / 2 }>;
333
	type WeightInfo = moonriver_weights::pallet_timestamp::WeightInfo<Runtime>;
334
}
335

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

            
341
#[cfg(feature = "runtime-benchmarks")]
342
parameter_types! {
343
	pub const ExistentialDeposit: Balance = 1;
344
}
345

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

            
365
pub struct LengthToFee;
366
impl WeightToFeePolynomial for LengthToFee {
367
	type Balance = Balance;
368

            
369
77
	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
370
77
		smallvec![
371
			WeightToFeeCoefficient {
372
				degree: 1,
373
				coeff_frac: Perbill::zero(),
374
				coeff_integer: currency::TRANSACTION_BYTE_FEE,
375
				negative: false,
376
			},
377
			WeightToFeeCoefficient {
378
				degree: 3,
379
				coeff_frac: Perbill::zero(),
380
				coeff_integer: 1 * currency::SUPPLY_FACTOR,
381
				negative: false,
382
			},
383
		]
384
77
	}
385
}
386

            
387
impl pallet_transaction_payment::Config for Runtime {
388
	type RuntimeEvent = RuntimeEvent;
389
	type OnChargeTransaction = FungibleAdapter<
390
		Balances,
391
		DealWithSubstrateFeesAndTip<
392
			Runtime,
393
			dynamic_params::runtime_config::FeesTreasuryProportion,
394
		>,
395
	>;
396
	type OperationalFeeMultiplier = ConstU8<5>;
397
	type WeightToFee = WeightToFee<
398
		RefTimeToFee<ConstU128<{ currency::WEIGHT_FEE }>>,
399
		ProofSizeToFee<
400
			ConstU128<
401
				{ currency::WEIGHT_FEE.saturating_mul(GasLimitPovSizeRatio::get() as Balance) },
402
			>,
403
		>,
404
	>;
405
	type LengthToFee = LengthToFee;
406
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime>;
407
	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
408
}
409

            
410
impl pallet_evm_chain_id::Config for Runtime {}
411

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

            
418
/// Approximate ratio of the amount of Weight per Gas.
419
/// u64 works for approximations because Weight is a very small unit compared to gas.
420
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
421

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

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

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

            
484
/// Parameterized slow adjusting fee updated based on
485
/// https://research.web3.foundation/Polkadot/overview/token-economics#2-slow-adjusting-mechanism // editorconfig-checker-disable-line
486
///
487
/// The adjustment algorithm boils down to:
488
///
489
/// diff = (previous_block_weight - target) / maximum_block_weight
490
/// next_multiplier = prev_multiplier * (1 + (v * diff) + ((v * diff)^2 / 2))
491
/// assert(next_multiplier > min)
492
///     where: v is AdjustmentVariable
493
///            target is TargetBlockFullness
494
///            min is MinimumMultiplier
495
pub type SlowAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
496
	R,
497
	TargetBlockFullness,
498
	AdjustmentVariable,
499
	MinimumMultiplier,
500
	MaximumMultiplier,
501
>;
502

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

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

            
511
impl<Inner> FindAuthor<H160> for FindAuthorAdapter<Inner>
512
where
513
	Inner: FindAuthor<AccountId20>,
514
{
515
299
	fn find_author<'a, I>(digests: I) -> Option<H160>
516
299
	where
517
299
		I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
518
	{
519
299
		Inner::find_author(digests).map(Into::into)
520
299
	}
521
}
522

            
523
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
524

            
525
impl pallet_evm::Config for Runtime {
526
	type FeeCalculator = TransactionPaymentAsGasPrice;
527
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
528
	type WeightPerGas = WeightPerGas;
529
	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
530
	type CallOrigin = EnsureAddressRoot<AccountId>;
531
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
532
	type AddressMapping = IdentityAddressMapping;
533
	type Currency = Balances;
534
	type Runner = pallet_evm::runner::stack::Runner<Self>;
535
	type PrecompilesType = MoonriverPrecompiles<Self>;
536
	type PrecompilesValue = PrecompilesValue;
537
	type ChainId = EthereumChainId;
538
	type OnChargeTransaction = OnChargeEVMTransaction<
539
		DealWithEthereumBaseFees<Runtime, dynamic_params::runtime_config::FeesTreasuryProportion>,
540
		DealWithEthereumPriorityFees<Runtime>,
541
	>;
542
	type BlockGasLimit = BlockGasLimit;
543
	type FindAuthor = FindAuthorAdapter<AuthorInherent>;
544
	type OnCreate = ();
545
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
546
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
547
	type Timestamp = Timestamp;
548
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
549
	type WeightInfo = moonriver_weights::pallet_evm::WeightInfo<Runtime>;
550
	type CreateOriginFilter = ();
551
	type CreateInnerOriginFilter = ();
552
}
553

            
554
parameter_types! {
555
	pub MaxServiceWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
556
}
557

            
558
impl pallet_scheduler::Config for Runtime {
559
	type RuntimeEvent = RuntimeEvent;
560
	type RuntimeOrigin = RuntimeOrigin;
561
	type PalletsOrigin = OriginCaller;
562
	type RuntimeCall = RuntimeCall;
563
	type MaximumWeight = MaxServiceWeight;
564
	type ScheduleOrigin = EnsureRoot<AccountId>;
565
	type MaxScheduledPerBlock = ConstU32<50>;
566
	type WeightInfo = moonriver_weights::pallet_scheduler::WeightInfo<Runtime>;
567
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
568
	type Preimages = Preimage;
569
	type BlockNumberProvider = System;
570
}
571

            
572
parameter_types! {
573
	pub const PreimageBaseDeposit: Balance = 5 * currency::MOVR * currency::SUPPLY_FACTOR ;
574
	pub const PreimageByteDeposit: Balance = currency::STORAGE_BYTE_FEE;
575
	pub const PreimageHoldReason: RuntimeHoldReason =
576
		RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
577
}
578

            
579
impl pallet_preimage::Config for Runtime {
580
	type WeightInfo = moonriver_weights::pallet_preimage::WeightInfo<Runtime>;
581
	type RuntimeEvent = RuntimeEvent;
582
	type Currency = Balances;
583
	type ManagerOrigin = EnsureRoot<AccountId>;
584
	type Consideration = HoldConsideration<
585
		AccountId,
586
		Balances,
587
		PreimageHoldReason,
588
		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
589
	>;
590
}
591

            
592
parameter_types! {
593
	pub const ProposalBond: Permill = Permill::from_percent(5);
594
	pub const TreasuryId: PalletId = PalletId(*b"py/trsry");
595
	pub TreasuryAccount: AccountId = Treasury::account_id();
596
	pub const MaxSpendBalance: crate::Balance = crate::Balance::max_value();
597
}
598

            
599
type RootOrTreasuryCouncilOrigin = EitherOfDiverse<
600
	EnsureRoot<AccountId>,
601
	pallet_collective::EnsureProportionMoreThan<AccountId, TreasuryCouncilInstance, 1, 2>,
602
>;
603

            
604
impl pallet_treasury::Config for Runtime {
605
	type PalletId = TreasuryId;
606
	type Currency = Balances;
607
	// More than half of the council is required (or root) to reject a proposal
608
	type RejectOrigin = RootOrTreasuryCouncilOrigin;
609
	type RuntimeEvent = RuntimeEvent;
610
	type SpendPeriod = ConstU32<{ 6 * DAYS }>;
611
	type Burn = ();
612
	type BurnDestination = ();
613
	type MaxApprovals = ConstU32<100>;
614
	type WeightInfo = moonriver_weights::pallet_treasury::WeightInfo<Runtime>;
615
	type SpendFunds = ();
616
	type SpendOrigin =
617
		frame_system::EnsureWithSuccess<RootOrTreasuryCouncilOrigin, AccountId, MaxSpendBalance>;
618
	type AssetKind = NativeOrWithId<AssetId>;
619
	type Beneficiary = AccountId;
620
	type BeneficiaryLookup = IdentityLookup<AccountId>;
621
	type Paymaster = MultiAssetPaymaster<Runtime, TreasuryAccount, Balances>;
622
	type BalanceConverter = AssetRateConverter<Runtime, Balances>;
623
	type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
624
	#[cfg(feature = "runtime-benchmarks")]
625
	type BenchmarkHelper = BenchmarkHelper<Runtime>;
626
	type BlockNumberProvider = System;
627
}
628

            
629
parameter_types! {
630
	pub const MaxSubAccounts: u32 = 100;
631
	pub const MaxAdditionalFields: u32 = 100;
632
	pub const MaxRegistrars: u32 = 20;
633
	pub const PendingUsernameExpiration: u32 = 7 * DAYS;
634
	pub const MaxSuffixLength: u32 = 7;
635
	pub const MaxUsernameLength: u32 = 32;
636
}
637

            
638
type IdentityForceOrigin =
639
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
640
type IdentityRegistrarOrigin =
641
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
642

            
643
impl pallet_identity::Config for Runtime {
644
	type RuntimeEvent = RuntimeEvent;
645
	type Currency = Balances;
646
	// Add one item in storage and take 258 bytes
647
	type BasicDeposit = ConstU128<{ currency::deposit(1, 258) }>;
648
	// Does not add any item to the storage but takes 1 bytes
649
	type ByteDeposit = ConstU128<{ currency::deposit(0, 1) }>;
650
	// Add one item in storage and take 53 bytes
651
	type SubAccountDeposit = ConstU128<{ currency::deposit(1, 53) }>;
652
	type MaxSubAccounts = MaxSubAccounts;
653
	type IdentityInformation = pallet_identity::legacy::IdentityInfo<MaxAdditionalFields>;
654
	type MaxRegistrars = MaxRegistrars;
655
	type Slashed = Treasury;
656
	type ForceOrigin = IdentityForceOrigin;
657
	type RegistrarOrigin = IdentityRegistrarOrigin;
658
	type OffchainSignature = Signature;
659
	type SigningPublicKey = <Signature as sp_runtime::traits::Verify>::Signer;
660
	type UsernameAuthorityOrigin = EnsureRoot<AccountId>;
661
	type PendingUsernameExpiration = PendingUsernameExpiration;
662
	type MaxSuffixLength = MaxSuffixLength;
663
	type MaxUsernameLength = MaxUsernameLength;
664
	type WeightInfo = moonriver_weights::pallet_identity::WeightInfo<Runtime>;
665
	type UsernameDeposit = ConstU128<{ currency::deposit(0, MaxUsernameLength::get()) }>;
666
	type UsernameGracePeriod = ConstU32<{ 30 * DAYS }>;
667
	#[cfg(feature = "runtime-benchmarks")]
668
	type BenchmarkHelper = BenchmarkHelper<Runtime>;
669
}
670

            
671
pub struct TransactionConverter;
672

            
673
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
674
21
	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
675
21
		UncheckedExtrinsic::new_bare(
676
21
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
677
		)
678
21
	}
679
}
680

            
681
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
682
	fn convert_transaction(
683
		&self,
684
		transaction: pallet_ethereum::Transaction,
685
	) -> opaque::UncheckedExtrinsic {
686
		let extrinsic = UncheckedExtrinsic::new_bare(
687
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
688
		);
689
		let encoded = extrinsic.encode();
690
		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
691
			.expect("Encoded extrinsic is always valid")
692
	}
693
}
694

            
695
parameter_types! {
696
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
697
}
698

            
699
impl pallet_ethereum::Config for Runtime {
700
	type StateRoot =
701
		pallet_ethereum::IntermediateStateRoot<<Runtime as frame_system::Config>::Version>;
702
	type PostLogContent = PostBlockAndTxnHashes;
703
	type ExtraDataLength = ConstU32<30>;
704
}
705

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

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

            
733
parameter_types! {
734
	// Reserved weight is 1/4 of MAXIMUM_BLOCK_WEIGHT
735
	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
736
	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
737
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
738
}
739

            
740
/// Relay chain slot duration, in milliseconds.
741
const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
742
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
743
/// into the relay chain.
744
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
745
/// Build with an offset of 1 behind the relay chain.
746
const RELAY_PARENT_OFFSET: u32 = 1;
747
/// How many parachain blocks are processed by the relay chain per parent. Limits the
748
/// number of blocks authored per slot.
749
const BLOCK_PROCESSING_VELOCITY: u32 = 1;
750

            
751
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
752
	Runtime,
753
	RELAY_CHAIN_SLOT_DURATION_MILLIS,
754
	BLOCK_PROCESSING_VELOCITY,
755
	UNINCLUDED_SEGMENT_CAPACITY,
756
>;
757

            
758
impl cumulus_pallet_parachain_system::Config for Runtime {
759
	type RuntimeEvent = RuntimeEvent;
760
	type OnSystemEvent = ();
761
	type SelfParaId = ParachainInfo;
762
	type ReservedDmpWeight = ReservedDmpWeight;
763
	type OutboundXcmpMessageSource = XcmpQueue;
764
	type XcmpMessageHandler = XcmpQueue;
765
	type ReservedXcmpWeight = ReservedXcmpWeight;
766
	type CheckAssociatedRelayNumber = EmergencyParaXcm;
767
	type ConsensusHook = ConsensusHook;
768
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
769
	type WeightInfo = moonriver_weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
770
	type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
771
	type RelayParentOffset = ConstU32<0>;
772
}
773

            
774
impl parachain_info::Config for Runtime {}
775

            
776
pub struct OnNewRound;
777
impl pallet_parachain_staking::OnNewRound for OnNewRound {
778
35
	fn on_new_round(round_index: pallet_parachain_staking::RoundIndex) -> Weight {
779
35
		MoonbeamOrbiters::on_new_round(round_index)
780
35
	}
781
}
782
pub struct PayoutCollatorOrOrbiterReward;
783
impl pallet_parachain_staking::PayoutCollatorReward<Runtime> for PayoutCollatorOrOrbiterReward {
784
14
	fn payout_collator_reward(
785
14
		for_round: pallet_parachain_staking::RoundIndex,
786
14
		collator_id: AccountId,
787
14
		amount: Balance,
788
14
	) -> Weight {
789
14
		let extra_weight =
790
14
			if MoonbeamOrbiters::is_collator_pool_with_active_orbiter(for_round, collator_id) {
791
				MoonbeamOrbiters::distribute_rewards(for_round, collator_id, amount)
792
			} else {
793
14
				ParachainStaking::mint_collator_reward(for_round, collator_id, amount)
794
			};
795

            
796
14
		<Runtime as frame_system::Config>::DbWeight::get()
797
14
			.reads(1)
798
14
			.saturating_add(extra_weight)
799
14
	}
800
}
801

            
802
pub struct OnInactiveCollator;
803
impl pallet_parachain_staking::OnInactiveCollator<Runtime> for OnInactiveCollator {
804
	fn on_inactive_collator(
805
		collator_id: AccountId,
806
		round: pallet_parachain_staking::RoundIndex,
807
	) -> Result<Weight, DispatchErrorWithPostInfo<PostDispatchInfo>> {
808
		let extra_weight = if !MoonbeamOrbiters::is_collator_pool_with_active_orbiter(
809
			round,
810
			collator_id.clone(),
811
		) {
812
			ParachainStaking::go_offline_inner(collator_id)?;
813
			<Runtime as pallet_parachain_staking::Config>::WeightInfo::go_offline(
814
				pallet_parachain_staking::MAX_CANDIDATES,
815
			)
816
		} else {
817
			Weight::zero()
818
		};
819

            
820
		Ok(<Runtime as frame_system::Config>::DbWeight::get()
821
			.reads(1)
822
			.saturating_add(extra_weight))
823
	}
824
}
825

            
826
type MonetaryGovernanceOrigin =
827
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
828

            
829
pub struct RelayChainSlotProvider;
830
impl Get<Slot> for RelayChainSlotProvider {
831
35
	fn get() -> Slot {
832
35
		let slot_info = pallet_async_backing::pallet::Pallet::<Runtime>::slot_info();
833
35
		slot_info.unwrap_or_default().0
834
35
	}
835
}
836

            
837
impl pallet_parachain_staking::Config for Runtime {
838
	type Currency = Balances;
839
	type RuntimeFreezeReason = RuntimeFreezeReason;
840
	type MonetaryGovernanceOrigin = MonetaryGovernanceOrigin;
841
	/// Minimum round length is 2 minutes (10 * 12 second block times)
842
	type MinBlocksPerRound = ConstU32<10>;
843
	/// If a collator doesn't produce any block on this number of rounds, it is notified as inactive
844
	type MaxOfflineRounds = ConstU32<2>;
845
	/// Rounds before the collator leaving the candidates request can be executed
846
	type LeaveCandidatesDelay = ConstU32<24>;
847
	/// Rounds before the candidate bond increase/decrease can be executed
848
	type CandidateBondLessDelay = ConstU32<24>;
849
	/// Rounds before the delegator exit can be executed
850
	type LeaveDelegatorsDelay = ConstU32<24>;
851
	/// Rounds before the delegator revocation can be executed
852
	type RevokeDelegationDelay = ConstU32<24>;
853
	/// Rounds before the delegator bond increase/decrease can be executed
854
	type DelegationBondLessDelay = ConstU32<24>;
855
	/// Rounds before the reward is paid
856
	type RewardPaymentDelay = ConstU32<2>;
857
	/// Minimum collators selected per round, default at genesis and minimum forever after
858
	type MinSelectedCandidates = ConstU32<8>;
859
	/// Maximum top delegations per candidate
860
	type MaxTopDelegationsPerCandidate = ConstU32<300>;
861
	/// Maximum bottom delegations per candidate
862
	type MaxBottomDelegationsPerCandidate = ConstU32<50>;
863
	/// Maximum delegations per delegator
864
	type MaxDelegationsPerDelegator = ConstU32<100>;
865
	/// Maximum scheduled delegation requests per (collator, delegator)
866
	type MaxScheduledRequestsPerDelegator = ConstU32<50>;
867
	/// Minimum stake required to be reserved to be a candidate
868
	type MinCandidateStk = ConstU128<{ 500 * currency::MOVR * currency::SUPPLY_FACTOR }>;
869
	/// Minimum stake required to be reserved to be a delegator
870
	type MinDelegation = ConstU128<{ 5 * currency::MOVR * currency::SUPPLY_FACTOR }>;
871
	type BlockAuthor = AuthorInherent;
872
	type OnCollatorPayout = ();
873
	type PayoutCollatorReward = PayoutCollatorOrOrbiterReward;
874
	type OnInactiveCollator = OnInactiveCollator;
875
	type OnNewRound = OnNewRound;
876
	type SlotProvider = RelayChainSlotProvider;
877
	type WeightInfo = moonriver_weights::pallet_parachain_staking::WeightInfo<Runtime>;
878
	type MaxCandidates = ConstU32<200>;
879
	type SlotDuration = ConstU64<MILLISECS_PER_BLOCK>;
880
	type BlockTime = ConstU64<MILLISECS_PER_BLOCK>;
881
	type LinearInflationThreshold = ();
882
}
883

            
884
impl pallet_author_inherent::Config for Runtime {
885
	type SlotBeacon = RelaychainDataProvider<Self>;
886
	type AccountLookup = MoonbeamOrbiters;
887
	type CanAuthor = AuthorFilter;
888
	type AuthorId = AccountId;
889
	type WeightInfo = moonriver_weights::pallet_author_inherent::WeightInfo<Runtime>;
890
}
891

            
892
impl pallet_author_slot_filter::Config for Runtime {
893
	type RandomnessSource = Randomness;
894
	type PotentialAuthors = ParachainStaking;
895
	type WeightInfo = moonriver_weights::pallet_author_slot_filter::WeightInfo<Runtime>;
896
}
897

            
898
impl pallet_async_backing::Config for Runtime {
899
	type AllowMultipleBlocksPerSlot = ConstBool<true>;
900
	type GetAndVerifySlot = pallet_async_backing::RelaySlot;
901
	type SlotDuration = ConstU64<MILLISECS_PER_BLOCK>;
902
	type ExpectedBlockTime = ConstU64<MILLISECS_PER_BLOCK>;
903
}
904

            
905
parameter_types! {
906
	pub const InitializationPayment: Perbill = Perbill::from_percent(30);
907
	pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100);
908
	pub const SignatureNetworkIdentifier:  &'static [u8] = b"moonriver-";
909

            
910
}
911

            
912
impl pallet_crowdloan_rewards::Config for Runtime {
913
	type Initialized = ConstBool<false>;
914
	type InitializationPayment = InitializationPayment;
915
	type MaxInitContributors = ConstU32<500>;
916
	type MinimumReward = ConstU128<0>;
917
	type RewardCurrency = Balances;
918
	type RelayChainAccountId = [u8; 32];
919
	type RewardAddressAssociateOrigin = EnsureSigned<Self::AccountId>;
920
	type RewardAddressChangeOrigin = EnsureSigned<Self::AccountId>;
921
	type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold;
922
	type SignatureNetworkIdentifier = SignatureNetworkIdentifier;
923
	type VestingBlockNumber = relay_chain::BlockNumber;
924
	type VestingBlockProvider = RelaychainDataProvider<Self>;
925
	type WeightInfo = moonriver_weights::pallet_crowdloan_rewards::WeightInfo<Runtime>;
926
}
927

            
928
// This is a simple session key manager. It should probably either work with, or be replaced
929
// entirely by pallet sessions
930
impl pallet_author_mapping::Config for Runtime {
931
	type DepositCurrency = Balances;
932
	type DepositAmount = ConstU128<{ 100 * currency::MOVR * currency::SUPPLY_FACTOR }>;
933
	type Keys = session_keys_primitives::VrfId;
934
	type WeightInfo = moonriver_weights::pallet_author_mapping::WeightInfo<Runtime>;
935
}
936

            
937
/// The type used to represent the kinds of proxying allowed.
938
#[derive(
939
	Copy,
940
	Clone,
941
	Eq,
942
	PartialEq,
943
	Ord,
944
	PartialOrd,
945
	Encode,
946
	Decode,
947
	Debug,
948
	MaxEncodedLen,
949
	TypeInfo,
950
	Serialize,
951
	Deserialize,
952
	DecodeWithMemTracking,
953
)]
954
pub enum ProxyType {
955
	/// All calls can be proxied. This is the trivial/most permissive filter.
956
	Any = 0,
957
	/// Only extrinsics that do not transfer funds.
958
	NonTransfer = 1,
959
	/// Only extrinsics related to governance (democracy and collectives).
960
	Governance = 2,
961
	/// Only extrinsics related to staking.
962
	Staking = 3,
963
	/// Allow to veto an announced proxy call.
964
	CancelProxy = 4,
965
	/// Allow extrinsic related to Balances.
966
	Balances = 5,
967
	/// Allow extrinsic related to AuthorMapping.
968
	AuthorMapping = 6,
969
	/// Allow extrinsic related to IdentityJudgement.
970
	IdentityJudgement = 7,
971
}
972

            
973
impl Default for ProxyType {
974
	fn default() -> Self {
975
		Self::Any
976
	}
977
}
978

            
979
fn is_governance_precompile(precompile_name: &precompiles::PrecompileName) -> bool {
980
	matches!(
981
		precompile_name,
982
		PrecompileName::TreasuryCouncilInstance
983
			| PrecompileName::PreimagePrecompile
984
			| PrecompileName::ReferendaPrecompile
985
			| PrecompileName::ConvictionVotingPrecompile
986
			| PrecompileName::OpenTechCommitteeInstance
987
	)
988
}
989

            
990
// Be careful: Each time this filter is modified, the substrate filter must also be modified
991
// consistently.
992
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
993
	fn is_evm_proxy_call_allowed(
994
		&self,
995
		call: &pallet_evm_precompile_proxy::EvmSubCall,
996
		recipient_has_code: bool,
997
		gas: u64,
998
	) -> precompile_utils::EvmResult<bool> {
999
		Ok(match self {
			ProxyType::Any => {
				match PrecompileName::from_address(call.to.0) {
					// Any precompile that can execute a subcall should be forbidden here,
					// to ensure that unauthorized smart contract can't be called
					// indirectly.
					// To be safe, we only allow the precompiles we need.
					Some(
						PrecompileName::AuthorMappingPrecompile
						| PrecompileName::ParachainStakingPrecompile,
					) => true,
					Some(ref precompile) if is_governance_precompile(precompile) => true,
					// All non-whitelisted precompiles are forbidden
					Some(_) => false,
					// Allow evm transfer to "simple" account (no code nor precompile)
					// For the moment, no smart contract other than precompiles is allowed.
					// In the future, we may create a dynamic whitelist to authorize some audited
					// smart contracts through governance.
					None => {
						// If the address is not recognized, allow only evm transfert to "simple"
						// accounts (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::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) }>;
	type BlockNumberProvider = System;
}
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 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::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
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
301
	fn contains(c: &RuntimeCall) -> bool {
301
		match c {
7
			RuntimeCall::PolkadotXcm(method) => match method {
				// User Operations (Anyone can call these extrinsics)
				pallet_xcm::Call::send { .. }
				| pallet_xcm::Call::claim_assets { .. }
				| pallet_xcm::Call::transfer_assets { .. }
				| pallet_xcm::Call::transfer_assets_using_type_and_then { .. } => true,
				// Administrative operations (Only AdminOrigin can call these extrinsics)
				pallet_xcm::Call::force_xcm_version { .. }
				| pallet_xcm::Call::force_default_xcm_version { .. }
				| pallet_xcm::Call::force_subscribe_version_notify { .. }
				| pallet_xcm::Call::force_unsubscribe_version_notify { .. } => true,
				// Anything else is disallowed
7
				_ => false,
			},
14
			RuntimeCall::Proxy(method) => match method {
				pallet_proxy::Call::proxy { real, .. } => {
					!pallet_evm::AccountCodes::<Runtime>::contains_key(H160::from(*real))
				}
14
				_ => 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,
280
			_ => true,
		}
301
	}
}
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 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;
	type BlockNumberProvider = System;
}
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 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 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>;
	type BlockNumberProvider = System;
}
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>;
}
#[cfg(feature = "runtime-benchmarks")]
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 cumulus_pallet_weight_reclaim::Config for Runtime {
	type WeightInfo = moonriver_weights::cumulus_pallet_weight_reclaim::WeightInfo<Runtime>;
}
impl pallet_migrations::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	#[cfg(not(feature = "runtime-benchmarks"))]
	type Migrations = migrations::MultiBlockMigrationList<Runtime>;
	#[cfg(feature = "runtime-benchmarks")]
	type Migrations = pallet_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_migrations::WeightInfo<Runtime>;
}
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>, FreezeReason} = 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,
		// [Removed] 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,
		// Sudo was previously index 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, Storage, Event<T>} = 90,
		// XCM Stuff
		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,
		// [Removed] Assets: pallet_assets::{Pallet, Call, Storage, Event<T>} = 104,
		// Previously 105: AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event<T>}
		// 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>, Config<T>} = 114,
		XcmWeightTrader: pallet_xcm_weight_trader::{Pallet, Call, Storage, Event<T>, Config<T>} = 115,
		EmergencyParaXcm: pallet_emergency_para_xcm::{Pallet, Call, Storage, Event} = 116,
		MultiBlockMigrations: pallet_migrations = 117,
		WeightReclaim: cumulus_pallet_weight_reclaim = 118,
		// Utils
		RelayStorageRoots: pallet_relay_storage_roots::{Pallet, Storage} = 112,
		#[cfg(feature = "runtime-benchmarks")]
		PrecompileBenchmarks: pallet_precompile_benchmarks::{Pallet} = 113,
		// Randomness
		Randomness: pallet_randomness::{Pallet, Call, Storage, Event<T>, Inherent} = 120,
		// Bridge pallets (reserved indexes from 130 to 140)
		BridgePolkadotGrandpa: pallet_bridge_grandpa::<Instance1>::{Pallet, Call, Storage, Event<T>, Config<T>} = 130,
		BridgePolkadotParachains: pallet_bridge_parachains::<Instance1>::{Pallet, Call, Storage, Event<T>, Config<T>} = 131,
		BridgePolkadotMessages: pallet_bridge_messages::<Instance1>::{Pallet, Call, Storage, Event<T>, Config<T>} = 132,
		BridgeXcmOverMoonbeam: pallet_xcm_bridge::<Instance1>::{Pallet, Call, Storage, Event<T>, HoldReason, Config<T>} = 133
	}
655400
}
bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages! {
	RuntimeCall, AccountId,
	// Grandpa
	BridgePolkadotGrandpa,
	// Parachains
	BridgePolkadotParachains,
	// Messages
	BridgePolkadotMessages
}
#[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_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, TransactionPaymentBenchmark::<Runtime>]
		[pallet_identity, Identity]
		[cumulus_pallet_parachain_system, ParachainSystem]
		[cumulus_pallet_xcmp_queue, XcmpQueue]
		[pallet_message_queue, MessageQueue]
		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
		[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_migrations, MultiBlockMigrations]
		// Currently there are no extrinsics to benchmark for the Lazy Migrations pallet
		// [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]
		[pallet_bridge_grandpa, BridgePolkadotGrandpa]
		[pallet_bridge_parachains, pallet_bridge_parachains::benchmarking::Pallet::<Runtime, bridge_config::BridgeMoonbeamInstance>]
		[pallet_bridge_messages, pallet_bridge_messages::benchmarking::Pallet::<Runtime, bridge_config::WithPolkadotMessagesInstance>]
		[cumulus_pallet_weight_reclaim, WeightReclaim]
	);
}
/// 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 TransactionExtension to the basic transaction logic.
pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
	Runtime,
	(
		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>,
		BridgeRejectObsoleteHeadersAndMessages,
		frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
	),
>;
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic =
	fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension, 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 TxExtension
								// Get the 7th item from the tuple
								let charge_transaction_payment = &signed_extra.0.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)
			}
		}
		impl bp_polkadot::PolkadotFinalityApi<Block> for Runtime {
			fn best_finalized() -> Option<bp_runtime::HeaderId<bp_polkadot::Hash, bp_polkadot::BlockNumber>> {
				BridgePolkadotGrandpa::best_finalized()
			}
			fn free_headers_interval() -> Option<bp_polkadot::BlockNumber> {
				<Runtime as pallet_bridge_grandpa::Config<
					bridge_config::BridgeGrandpaPolkadotInstance
				>>::FreeHeadersInterval::get()
			}
			fn synced_headers_grandpa_info(
			) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_polkadot::Header>> {
				BridgePolkadotGrandpa::synced_headers_grandpa_info()
			}
		}
		impl bp_moonbeam::MoonbeamPolkadotFinalityApi<Block> for Runtime {
			fn best_finalized() -> Option<bp_runtime::HeaderId<bp_moonbeam::Hash, bp_moonbeam::BlockNumber>> {
				BridgePolkadotParachains::best_parachain_head_id::<
					bp_moonbeam::Moonbeam
				>().unwrap_or(None)
			}
			fn free_headers_interval() -> Option<bp_moonbeam::BlockNumber> {
				// "free interval" is not currently used for parachains
				None
			}
		}
		impl bp_moonbeam::ToMoonbeamPolkadotOutboundLaneApi<Block> for Runtime {
			fn message_details(
				lane: bp_moonbeam::LaneId,
				begin: bp_messages::MessageNonce,
				end: bp_messages::MessageNonce,
			) -> Vec<bp_messages::OutboundMessageDetails> {
				bridge_runtime_common::messages_api::outbound_message_details::<
					Runtime,
					bridge_config::WithPolkadotMessagesInstance,
				>(lane, begin, end)
			}
		}
		impl bp_moonbeam::FromMoonbeamPolkadotInboundLaneApi<Block> for Runtime {
			fn message_details(
				lane: bp_moonbeam::LaneId,
				messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
			) -> Vec<bp_messages::InboundMessageDetails> {
				bridge_runtime_common::messages_api::inbound_message_details::<
					Runtime,
					bridge_config::WithPolkadotMessagesInstance,
				>(lane, messages)
			}
		}
	}
	// Benchmark customizations
	{
		impl pallet_bridge_parachains::benchmarking::Config<bridge_config::BridgeMoonbeamInstance> for Runtime {
			fn parachains() -> Vec<bp_polkadot_core::parachains::ParaId> {
				use bp_runtime::Parachain;
				vec![bp_polkadot_core::parachains::ParaId(bp_moonbeam::Moonbeam::PARACHAIN_ID)]
			}
			fn prepare_parachain_heads_proof(
				parachains: &[bp_polkadot_core::parachains::ParaId],
				parachain_head_size: u32,
				proof_params: bp_runtime::UnverifiedStorageProofParams,
			) -> (
				bp_parachains::RelayBlockNumber,
				bp_parachains::RelayBlockHash,
				bp_polkadot_core::parachains::ParaHeadsProof,
				Vec<(bp_polkadot_core::parachains::ParaId, bp_polkadot_core::parachains::ParaHash)>,
			) {
				bridge_runtime_common::parachains_benchmarking::prepare_parachain_heads_proof::<Runtime, bridge_config::BridgeMoonbeamInstance>(
					parachains,
					parachain_head_size,
					proof_params,
				)
			}
		}
		use bridge_runtime_common::messages_benchmarking::{
			generate_xcm_builder_bridge_message_sample, prepare_message_delivery_proof_from_parachain,
			prepare_message_proof_from_parachain,
		};
		use pallet_bridge_messages::benchmarking::{
			Config as BridgeMessagesConfig, MessageDeliveryProofParams, MessageProofParams,
		};
		impl BridgeMessagesConfig<bridge_config::WithPolkadotMessagesInstance> for Runtime {
			fn is_relayer_rewarded(_relayer: &Self::AccountId) -> bool {
				// Currently, we do not reward relayers
				true
			}
			fn prepare_message_proof(
				params: MessageProofParams<
					pallet_bridge_messages::LaneIdOf<Runtime, bridge_config::WithPolkadotMessagesInstance>,
				>,
			) -> (
				bridge_config::benchmarking::FromMoonbeamMessagesProof<
					bridge_config::WithPolkadotMessagesInstance,
				>,
				Weight,
			) {
				use cumulus_primitives_core::XcmpMessageSource;
				assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
				ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
				PolkadotXcm::force_xcm_version(
					RuntimeOrigin::root(),
					Box::new(Location::new(1, Parachain(42))),
					cumulus_primitives_core::XCM_VERSION,
				)
				.map_err(|e| {
					log::error!(
						"Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}",
						RuntimeOrigin::root(),
						Location::new(1, Parachain(42)),
						cumulus_primitives_core::XCM_VERSION,
						e
					);
				})
				.expect("XcmVersion stored!");
				let universal_source = bridge_config::benchmarking::open_bridge_for_benchmarks::<
					Runtime,
					bridge_config::XcmOverPolkadotInstance,
					xcm_config::LocationToAccountId,
				>(params.lane, 42);
				prepare_message_proof_from_parachain::<
					Runtime,
					bridge_config::BridgeGrandpaPolkadotInstance,
					bridge_config::WithPolkadotMessagesInstance,
				>(params, generate_xcm_builder_bridge_message_sample(universal_source))
			}
			fn prepare_message_delivery_proof(
				params: MessageDeliveryProofParams<
					AccountId,
					pallet_bridge_messages::LaneIdOf<Runtime, bridge_config::WithPolkadotMessagesInstance>,
				>,
			) -> bridge_config::benchmarking::ToMoonbeamMessagesDeliveryProof<
				bridge_config::WithPolkadotMessagesInstance,
			> {
				let _ = bridge_config::benchmarking::open_bridge_for_benchmarks::<
					Runtime,
					bridge_config::XcmOverPolkadotInstance,
					xcm_config::LocationToAccountId,
				>(params.lane, 42);
				prepare_message_delivery_proof_from_parachain::<
					Runtime,
					bridge_config::BridgeGrandpaPolkadotInstance,
					bridge_config::WithPolkadotMessagesInstance,
				>(params)
			}
			fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool {
				// The message is not routed from Bridge Hub
				true
			}
		}
	}
);
// 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>,
);
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
		assert!(
1
			std::mem::size_of::<pallet_author_inherent::Call<Runtime>>() <= CALL_ALIGN as usize
		);
1
		assert!(
1
			std::mem::size_of::<pallet_author_slot_filter::Call<Runtime>>() <= CALL_ALIGN as usize
		);
1
		assert!(
1
			std::mem::size_of::<pallet_crowdloan_rewards::Call<Runtime>>() <= CALL_ALIGN as usize
		);
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
		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
		assert!(
1
			std::mem::size_of::<pallet_proxy_genesis_companion::Call<Runtime>>()
1
				<= CALL_ALIGN as usize
		);
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),
			5_u8
		);
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
		assert_eq!(
1
			get!(pallet_identity, ByteDeposit, u128),
1
			Balance::from(100 * MICROMOVR)
		);
1
		assert_eq!(
1
			get!(pallet_identity, SubAccountDeposit, u128),
1
			Balance::from(1 * MOVR + 5300 * MICROMOVR)
		);
		// staking minimums
1
		assert_eq!(
1
			get!(pallet_parachain_staking, MinCandidateStk, u128),
1
			Balance::from(500 * MOVR)
		);
1
		assert_eq!(
1
			get!(pallet_parachain_staking, MinDelegation, u128),
1
			Balance::from(5 * MOVR)
		);
		// crowdloan min reward
1
		assert_eq!(
1
			get!(pallet_crowdloan_rewards, MinimumReward, u128),
1
			Balance::from(0u128)
		);
		// deposit for AuthorMapping
1
		assert_eq!(
1
			get!(pallet_author_mapping, DepositAmount, u128),
1
			Balance::from(100 * MOVR)
		);
		// proxy deposits
1
		assert_eq!(
1
			get!(pallet_proxy, ProxyDepositBase, u128),
1
			Balance::from(1 * MOVR + 800 * MICROMOVR)
		);
1
		assert_eq!(
1
			get!(pallet_proxy, ProxyDepositFactor, u128),
1
			Balance::from(2100 * MICROMOVR)
		);
1
		assert_eq!(
1
			get!(pallet_proxy, AnnouncementDepositBase, u128),
1
			Balance::from(1 * MOVR + 800 * MICROMOVR)
		);
1
		assert_eq!(
1
			get!(pallet_proxy, AnnouncementDepositFactor, u128),
1
			Balance::from(5600 * MICROMOVR)
		);
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
	}
	#[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),
			300
		);
1
		assert_eq!(
1
			get!(
				pallet_parachain_staking,
				MaxBottomDelegationsPerCandidate,
				u32
			),
			50
		);
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() {
		// 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
	}
}