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

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

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

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

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

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

            
108
use runtime_params::*;
109

            
110
use smallvec::smallvec;
111
#[cfg(feature = "std")]
112
use sp_version::NativeVersion;
113
use sp_version::RuntimeVersion;
114

            
115
use nimbus_primitives::CanAuthor;
116

            
117
pub use precompiles::{
118
	MoonriverPrecompiles, PrecompileName, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
119
};
120

            
121
#[cfg(any(feature = "std", test))]
122
pub use sp_runtime::BuildStorage;
123

            
124
pub type Precompiles = MoonriverPrecompiles<Runtime>;
125

            
126
pub mod asset_config;
127
pub mod governance;
128
pub mod runtime_params;
129
pub mod xcm_config;
130

            
131
mod migrations;
132
mod precompiles;
133

            
134
pub use governance::councils::*;
135

            
136
/// MOVR, the native token, uses 18 decimals of precision.
137
pub mod currency {
138
	use super::Balance;
139

            
140
	// Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
141
	pub const SUPPLY_FACTOR: Balance = 1;
142

            
143
	pub const WEI: Balance = 1;
144
	pub const KILOWEI: Balance = 1_000;
145
	pub const MEGAWEI: Balance = 1_000_000;
146
	pub const GIGAWEI: Balance = 1_000_000_000;
147
	pub const MICROMOVR: Balance = 1_000_000_000_000;
148
	pub const MILLIMOVR: Balance = 1_000_000_000_000_000;
149
	pub const MOVR: Balance = 1_000_000_000_000_000_000;
150
	pub const KILOMOVR: Balance = 1_000_000_000_000_000_000_000;
151

            
152
	pub const TRANSACTION_BYTE_FEE: Balance = 1 * GIGAWEI * SUPPLY_FACTOR;
153
	pub const STORAGE_BYTE_FEE: Balance = 100 * MICROMOVR * SUPPLY_FACTOR;
154
	pub const WEIGHT_FEE: Balance = 50 * KILOWEI * SUPPLY_FACTOR / 4;
155

            
156
32
	pub const fn deposit(items: u32, bytes: u32) -> Balance {
157
32
		items as Balance * 1 * MOVR * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
158
32
	}
159
}
160

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

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

            
178
	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
179
	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
180

            
181
	impl_opaque_keys! {
182
		pub struct SessionKeys {
183
			pub nimbus: AuthorInherent,
184
			pub vrf: session_keys_primitives::VrfSessionKey,
185
		}
186
	}
187
}
188

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

            
206
/// We need to duplicate this because the `runtime_version` macro is conflicting with the
207
/// conditional compilation at the state_version field.
208
#[cfg(not(feature = "runtime-benchmarks"))]
209
#[sp_version::runtime_version]
210
pub const VERSION: RuntimeVersion = RuntimeVersion {
211
	spec_name: create_runtime_str!("moonriver"),
212
	impl_name: create_runtime_str!("moonriver"),
213
	authoring_version: 3,
214
	spec_version: 3400,
215
	impl_version: 0,
216
	apis: RUNTIME_API_VERSIONS,
217
	transaction_version: 3,
218
	state_version: 1,
219
};
220

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

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

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

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

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

            
310
impl pallet_utility::Config for Runtime {
311
	type RuntimeEvent = RuntimeEvent;
312
	type RuntimeCall = RuntimeCall;
313
	type PalletsOrigin = OriginCaller;
314
	type WeightInfo = moonriver_weights::pallet_utility::WeightInfo<Runtime>;
315
}
316

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

            
325
parameter_types! {
326
	pub const ExistentialDeposit: Balance = 0;
327
}
328

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

            
347
pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
348
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
349
where
350
	R: pallet_balances::Config + pallet_treasury::Config,
351
{
352
	// this seems to be called for substrate-based transactions
353
1
	fn on_unbalanceds<B>(
354
1
		mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
355
1
	) {
356
1
		if let Some(fees) = fees_then_tips.next() {
357
1
			let treasury_perbill =
358
1
				runtime_params::dynamic_params::runtime_config::FeesTreasuryProportion::get();
359
1
			let treasury_part = treasury_perbill.deconstruct();
360
1
			let burn_part = Perbill::one().deconstruct() - treasury_part;
361
1
			let (_, to_treasury) = fees.ration(burn_part, treasury_part);
362
1
			// Balances pallet automatically burns dropped Credits by decreasing
363
1
			// total_supply accordingly
364
1
			ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(
365
1
				to_treasury,
366
1
			);
367

            
368
			// handle tip if there is one
369
1
			if let Some(tip) = fees_then_tips.next() {
370
1
				// for now we use the same burn/treasury strategy used for regular fees
371
1
				let (_, to_treasury) = tip.ration(80, 20);
372
1
				ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(
373
1
					to_treasury,
374
1
				);
375
1
			}
376
		}
377
1
	}
378

            
379
	// this is called from pallet_evm for Ethereum-based transactions
380
	// (technically, it calls on_unbalanced, which calls this when non-zero)
381
152
	fn on_nonzero_unbalanced(amount: Credit<R::AccountId, pallet_balances::Pallet<R>>) {
382
152
		// Balances pallet automatically burns dropped Credits by decreasing
383
152
		// total_supply accordingly
384
152
		let (_, to_treasury) = amount.ration(80, 20);
385
152
		ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
386
152
	}
387
}
388

            
389
pub struct LengthToFee;
390
impl WeightToFeePolynomial for LengthToFee {
391
	type Balance = Balance;
392

            
393
88
	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
394
88
		smallvec![
395
			WeightToFeeCoefficient {
396
				degree: 1,
397
88
				coeff_frac: Perbill::zero(),
398
				coeff_integer: currency::TRANSACTION_BYTE_FEE,
399
				negative: false,
400
			},
401
			WeightToFeeCoefficient {
402
				degree: 3,
403
88
				coeff_frac: Perbill::zero(),
404
88
				coeff_integer: 1 * currency::SUPPLY_FACTOR,
405
				negative: false,
406
			},
407
		]
408
88
	}
409
}
410

            
411
impl pallet_transaction_payment::Config for Runtime {
412
	type RuntimeEvent = RuntimeEvent;
413
	type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees<Runtime>>;
414
	type OperationalFeeMultiplier = ConstU8<5>;
415
	type WeightToFee = ConstantMultiplier<Balance, ConstU128<{ currency::WEIGHT_FEE }>>;
416
	type LengthToFee = LengthToFee;
417
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime>;
418
}
419

            
420
impl pallet_evm_chain_id::Config for Runtime {}
421

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

            
428
/// Approximate ratio of the amount of Weight per Gas.
429
/// u64 works for approximations because Weight is a very small unit compared to gas.
430
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
431

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

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

            
489
/// Parameterized slow adjusting fee updated based on
490
/// https://w3f-research.readthedocs.io/en/latest/polkadot/overview/2-token-economics.html#-2.-slow-adjusting-mechanism // editorconfig-checker-disable-line
491
///
492
/// The adjustment algorithm boils down to:
493
///
494
/// diff = (previous_block_weight - target) / maximum_block_weight
495
/// next_multiplier = prev_multiplier * (1 + (v * diff) + ((v * diff)^2 / 2))
496
/// assert(next_multiplier > min)
497
///     where: v is AdjustmentVariable
498
///            target is TargetBlockFullness
499
///            min is MinimumMultiplier
500
pub type SlowAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
501
	R,
502
	TargetBlockFullness,
503
	AdjustmentVariable,
504
	MinimumMultiplier,
505
	MaximumMultiplier,
506
>;
507

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

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

            
516
impl<Inner> FindAuthor<H160> for FindAuthorAdapter<Inner>
517
where
518
	Inner: FindAuthor<AccountId20>,
519
{
520
6785
	fn find_author<'a, I>(digests: I) -> Option<H160>
521
6785
	where
522
6785
		I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
523
6785
	{
524
6785
		Inner::find_author(digests).map(Into::into)
525
6785
	}
526
}
527

            
528
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
529

            
530
impl pallet_evm::Config for Runtime {
531
	type FeeCalculator = TransactionPaymentAsGasPrice;
532
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
533
	type WeightPerGas = WeightPerGas;
534
	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
535
	type CallOrigin = EnsureAddressRoot<AccountId>;
536
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
537
	type AddressMapping = IdentityAddressMapping;
538
	type Currency = Balances;
539
	type RuntimeEvent = RuntimeEvent;
540
	type Runner = pallet_evm::runner::stack::Runner<Self>;
541
	type PrecompilesType = MoonriverPrecompiles<Self>;
542
	type PrecompilesValue = PrecompilesValue;
543
	type ChainId = EthereumChainId;
544
	type OnChargeTransaction = OnChargeEVMTransaction<DealWithFees<Runtime>>;
545
	type BlockGasLimit = BlockGasLimit;
546
	type FindAuthor = FindAuthorAdapter<AuthorInherent>;
547
	type OnCreate = ();
548
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
549
	type SuicideQuickClearLimit = ConstU32<0>;
550
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
551
	type Timestamp = RelayTimestamp;
552
	type WeightInfo = moonriver_weights::pallet_evm::WeightInfo<Runtime>;
553
}
554

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

            
559
impl pallet_scheduler::Config for Runtime {
560
	type RuntimeEvent = RuntimeEvent;
561
	type RuntimeOrigin = RuntimeOrigin;
562
	type PalletsOrigin = OriginCaller;
563
	type RuntimeCall = RuntimeCall;
564
	type MaximumWeight = MaximumSchedulerWeight;
565
	type ScheduleOrigin = EnsureRoot<AccountId>;
566
	type MaxScheduledPerBlock = ConstU32<50>;
567
	type WeightInfo = moonriver_weights::pallet_scheduler::WeightInfo<Runtime>;
568
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
569
	type Preimages = Preimage;
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
}
597

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

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

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

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

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

            
668
pub struct TransactionConverter;
669

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

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

            
692
parameter_types! {
693
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
694
}
695

            
696
impl pallet_ethereum::Config for Runtime {
697
	type RuntimeEvent = RuntimeEvent;
698
	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
699
	type PostLogContent = PostBlockAndTxnHashes;
700
	type ExtraDataLength = ConstU32<30>;
701
}
702

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

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

            
731
parameter_types! {
732
	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
733
	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
734
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
735
}
736

            
737
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
738
/// into the relay chain.
739
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
740
/// How many parachain blocks are processed by the relay chain per parent. Limits the
741
/// number of blocks authored per slot.
742
const BLOCK_PROCESSING_VELOCITY: u32 = 1;
743

            
744
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
745
	Runtime,
746
	BLOCK_PROCESSING_VELOCITY,
747
	UNINCLUDED_SEGMENT_CAPACITY,
748
>;
749

            
750
impl cumulus_pallet_parachain_system::Config for Runtime {
751
	type RuntimeEvent = RuntimeEvent;
752
	type OnSystemEvent = ();
753
	type SelfParaId = ParachainInfo;
754
	type ReservedDmpWeight = ReservedDmpWeight;
755
	type OutboundXcmpMessageSource = XcmpQueue;
756
	type XcmpMessageHandler = XcmpQueue;
757
	type ReservedXcmpWeight = ReservedXcmpWeight;
758
	type CheckAssociatedRelayNumber = EmergencyParaXcm;
759
	type ConsensusHook = ConsensusHookWrapperForRelayTimestamp<Runtime, ConsensusHook>;
760
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
761
	type WeightInfo = moonriver_weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
762
}
763

            
764
impl parachain_info::Config for Runtime {}
765

            
766
pub struct OnNewRound;
767
impl pallet_parachain_staking::OnNewRound for OnNewRound {
768
40
	fn on_new_round(round_index: pallet_parachain_staking::RoundIndex) -> Weight {
769
40
		MoonbeamOrbiters::on_new_round(round_index)
770
40
	}
771
}
772
pub struct PayoutCollatorOrOrbiterReward;
773
impl pallet_parachain_staking::PayoutCollatorReward<Runtime> for PayoutCollatorOrOrbiterReward {
774
16
	fn payout_collator_reward(
775
16
		for_round: pallet_parachain_staking::RoundIndex,
776
16
		collator_id: AccountId,
777
16
		amount: Balance,
778
16
	) -> Weight {
779
16
		let extra_weight =
780
16
			if MoonbeamOrbiters::is_collator_pool_with_active_orbiter(for_round, collator_id) {
781
				MoonbeamOrbiters::distribute_rewards(for_round, collator_id, amount)
782
			} else {
783
16
				ParachainStaking::mint_collator_reward(for_round, collator_id, amount)
784
			};
785

            
786
16
		<Runtime as frame_system::Config>::DbWeight::get()
787
16
			.reads(1)
788
16
			.saturating_add(extra_weight)
789
16
	}
790
}
791

            
792
pub struct OnInactiveCollator;
793
impl pallet_parachain_staking::OnInactiveCollator<Runtime> for OnInactiveCollator {
794
	fn on_inactive_collator(
795
		collator_id: AccountId,
796
		round: pallet_parachain_staking::RoundIndex,
797
	) -> Result<Weight, DispatchErrorWithPostInfo<PostDispatchInfo>> {
798
		let extra_weight = if !MoonbeamOrbiters::is_collator_pool_with_active_orbiter(
799
			round,
800
			collator_id.clone(),
801
		) {
802
			ParachainStaking::go_offline_inner(collator_id)?;
803
			<Runtime as pallet_parachain_staking::Config>::WeightInfo::go_offline(
804
				pallet_parachain_staking::MAX_CANDIDATES,
805
			)
806
		} else {
807
			Weight::zero()
808
		};
809

            
810
		Ok(<Runtime as frame_system::Config>::DbWeight::get()
811
			.reads(1)
812
			.saturating_add(extra_weight))
813
	}
814
}
815

            
816
type MonetaryGovernanceOrigin =
817
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
818

            
819
pub struct RelayChainSlotProvider;
820
impl Get<Slot> for RelayChainSlotProvider {
821
40
	fn get() -> Slot {
822
40
		let slot_info = pallet_async_backing::pallet::Pallet::<Runtime>::slot_info();
823
40
		slot_info.unwrap_or_default().0
824
40
	}
825
}
826

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

            
871
impl pallet_author_inherent::Config for Runtime {
872
	type SlotBeacon = RelaychainDataProvider<Self>;
873
	type AccountLookup = MoonbeamOrbiters;
874
	type CanAuthor = AuthorFilter;
875
	type AuthorId = AccountId;
876
	type WeightInfo = moonriver_weights::pallet_author_inherent::WeightInfo<Runtime>;
877
}
878

            
879
impl pallet_author_slot_filter::Config for Runtime {
880
	type RuntimeEvent = RuntimeEvent;
881
	type RandomnessSource = Randomness;
882
	type PotentialAuthors = ParachainStaking;
883
	type WeightInfo = moonriver_weights::pallet_author_slot_filter::WeightInfo<Runtime>;
884
}
885

            
886
impl pallet_async_backing::Config for Runtime {
887
	type AllowMultipleBlocksPerSlot = ConstBool<true>;
888
	type GetAndVerifySlot = pallet_async_backing::RelaySlot;
889
	type ExpectedBlockTime = ConstU64<6000>;
890
}
891

            
892
parameter_types! {
893
	pub const InitializationPayment: Perbill = Perbill::from_percent(30);
894
	pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100);
895
	pub const SignatureNetworkIdentifier:  &'static [u8] = b"moonriver-";
896

            
897
}
898

            
899
impl pallet_crowdloan_rewards::Config for Runtime {
900
	type RuntimeEvent = RuntimeEvent;
901
	type Initialized = ConstBool<false>;
902
	type InitializationPayment = InitializationPayment;
903
	type MaxInitContributors = ConstU32<500>;
904
	type MinimumReward = ConstU128<0>;
905
	type RewardCurrency = Balances;
906
	type RelayChainAccountId = [u8; 32];
907
	type RewardAddressAssociateOrigin = EnsureSigned<Self::AccountId>;
908
	type RewardAddressChangeOrigin = EnsureSigned<Self::AccountId>;
909
	type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold;
910
	type SignatureNetworkIdentifier = SignatureNetworkIdentifier;
911
	type VestingBlockNumber = relay_chain::BlockNumber;
912
	type VestingBlockProvider = RelaychainDataProvider<Self>;
913
	type WeightInfo = moonriver_weights::pallet_crowdloan_rewards::WeightInfo<Runtime>;
914
}
915

            
916
// This is a simple session key manager. It should probably either work with, or be replaced
917
// entirely by pallet sessions
918
impl pallet_author_mapping::Config for Runtime {
919
	type RuntimeEvent = RuntimeEvent;
920
	type DepositCurrency = Balances;
921
	type DepositAmount = ConstU128<{ 100 * currency::MOVR * currency::SUPPLY_FACTOR }>;
922
	type Keys = session_keys_primitives::VrfId;
923
	type WeightInfo = moonriver_weights::pallet_author_mapping::WeightInfo<Runtime>;
924
}
925

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

            
961
impl Default for ProxyType {
962
	fn default() -> Self {
963
		Self::Any
964
	}
965
}
966

            
967
fn is_governance_precompile(precompile_name: &precompiles::PrecompileName) -> bool {
968
	matches!(
969
		precompile_name,
970
		PrecompileName::TreasuryCouncilInstance
971
			| PrecompileName::PreimagePrecompile
972
			| PrecompileName::ReferendaPrecompile
973
			| PrecompileName::ConvictionVotingPrecompile
974
			| PrecompileName::OpenTechCommitteeInstance
975
	)
976
}
977

            
978
// Be careful: Each time this filter is modified, the substrate filter must also be modified
979
// consistently.
980
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
981
	fn is_evm_proxy_call_allowed(
982
		&self,
983
		call: &pallet_evm_precompile_proxy::EvmSubCall,
984
		recipient_has_code: bool,
985
		gas: u64,
986
	) -> precompile_utils::EvmResult<bool> {
987
		Ok(match self {
988
			ProxyType::Any => {
989
				match PrecompileName::from_address(call.to.0) {
990
					// Any precompile that can execute a subcall should be forbidden here,
991
					// to ensure that unauthorized smart contract can't be called
992
					// indirectly.
993
					// To be safe, we only allow the precompiles we need.
994
					Some(
995
						PrecompileName::AuthorMappingPrecompile
996
						| PrecompileName::ParachainStakingPrecompile,
997
					) => true,
998
					Some(ref precompile) if is_governance_precompile(precompile) => true,
999
					// 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 => {
				matches!(
					c,
					RuntimeCall::System(..)
						| RuntimeCall::ParachainSystem(..)
						| RuntimeCall::Timestamp(..)
						| RuntimeCall::ParachainStaking(..)
						| RuntimeCall::Referenda(..)
						| RuntimeCall::Preimage(..)
						| RuntimeCall::ConvictionVoting(..)
						| RuntimeCall::TreasuryCouncilCollective(..)
						| RuntimeCall::OpenTechCommitteeCollective(..)
						| RuntimeCall::Identity(..)
						| RuntimeCall::Utility(..)
						| RuntimeCall::Proxy(..) | RuntimeCall::AuthorMapping(..)
						| RuntimeCall::CrowdloanRewards(
							pallet_crowdloan_rewards::Call::claim { .. }
						)
				)
			}
			ProxyType::Governance => matches!(
				c,
				RuntimeCall::Referenda(..)
					| RuntimeCall::Preimage(..)
					| RuntimeCall::ConvictionVoting(..)
					| RuntimeCall::TreasuryCouncilCollective(..)
					| RuntimeCall::OpenTechCommitteeCollective(..)
					| RuntimeCall::Utility(..)
			),
			ProxyType::Staking => matches!(
				c,
				RuntimeCall::ParachainStaking(..)
					| RuntimeCall::Utility(..)
					| RuntimeCall::AuthorMapping(..)
					| RuntimeCall::MoonbeamOrbiters(..)
			),
			ProxyType::CancelProxy => matches!(
				c,
				RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
			),
			ProxyType::Balances => {
				matches!(c, RuntimeCall::Balances(..) | RuntimeCall::Utility(..))
			}
			ProxyType::AuthorMapping => matches!(c, RuntimeCall::AuthorMapping(..)),
			ProxyType::IdentityJudgement => matches!(
				c,
				RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
					| RuntimeCall::Utility(..)
			),
		}
	}
	fn is_superset(&self, o: &Self) -> bool {
		match (self, o) {
			(x, y) if x == y => true,
			(ProxyType::Any, _) => true,
			(_, ProxyType::Any) => false,
			_ => false,
		}
	}
}
impl pallet_proxy::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeCall = RuntimeCall;
	type Currency = Balances;
	type ProxyType = ProxyType;
	// One storage item; key size 32, value size 8
	type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
	// Additional storage item size of 21 bytes (20 bytes AccountId + 1 byte sizeof(ProxyType)).
	type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 21) }>;
	type MaxProxies = ConstU32<32>;
	type WeightInfo = 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;
}
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::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 {
208
	fn contains(c: &RuntimeCall) -> bool {
		match c {
24
			RuntimeCall::Assets(method) => match method {
8
				pallet_assets::Call::transfer { .. } => true,
				pallet_assets::Call::transfer_keep_alive { .. } => true,
8
				pallet_assets::Call::approve_transfer { .. } => true,
8
				pallet_assets::Call::transfer_approved { .. } => true,
				pallet_assets::Call::cancel_approval { .. } => true,
				pallet_assets::Call::destroy_accounts { .. } => true,
				pallet_assets::Call::destroy_approvals { .. } => true,
				pallet_assets::Call::finish_destroy { .. } => true,
				_ => false,
			},
			// We just want to enable this in case of live chains, since the default version
			// is populated at genesis
24
			RuntimeCall::PolkadotXcm(method) => match method {
				pallet_xcm::Call::force_default_xcm_version { .. } => true,
16
				pallet_xcm::Call::transfer_assets { .. } => true,
				pallet_xcm::Call::transfer_assets_using_type_and_then { .. } => true,
8
				_ => 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,
			RuntimeCall::Treasury(
				pallet_treasury::Call::spend { .. }
				| pallet_treasury::Call::payout { .. }
				| pallet_treasury::Call::check_status { .. }
				| pallet_treasury::Call::void_spend { .. },
			) => false,
160
			_ => true,
		}
208
	}
}
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>;
}
744948
construct_runtime! {
	pub enum Runtime
	{
		// System support stuff.
		System: frame_system::{Pallet, Call, Storage, Config<T>, Event<T>} = 0,
		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>} = 1,
		// Previously 2: pallet_randomness_collective_flip
		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 3,
		ParachainInfo: parachain_info::{Pallet, Storage, Config<T>} = 4,
		RootTesting: pallet_root_testing::{Pallet, Call, Storage, Event<T>} = 5,
		// Monetary stuff.
		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 10,
		TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Config<T>, Event<T>} = 11,
		// Consensus support.
		ParachainStaking: pallet_parachain_staking::{Pallet, Call, Storage, Event<T>, Config<T>} = 20,
		AuthorInherent: pallet_author_inherent::{Pallet, Call, Storage, Inherent} = 21,
		AuthorFilter: pallet_author_slot_filter::{Pallet, Call, Storage, Event, Config<T>} = 22,
		AuthorMapping: pallet_author_mapping::{Pallet, Call, Config<T>, Storage, Event<T>} = 23,
		MoonbeamOrbiters: pallet_moonbeam_orbiters::{Pallet, Call, Storage, Event<T>} = 24,
		AsyncBacking: pallet_async_backing::{Pallet, Storage} = 25,
		// Handy utilities.
		Utility: pallet_utility::{Pallet, Call, Event} = 30,
		Proxy: pallet_proxy::{Pallet, Call, Storage, Event<T>} = 31,
		MaintenanceMode: pallet_maintenance_mode::{Pallet, Call, Config<T>, Storage, Event} = 32,
		Identity: pallet_identity::{Pallet, Call, Storage, Event<T>} = 33,
		Migrations: pallet_migrations::{Pallet, Storage, Config<T>, Event<T>} = 34,
		ProxyGenesisCompanion: pallet_proxy_genesis_companion::{Pallet, Config<T>} = 35,
		Multisig: pallet_multisig::{Pallet, Call, Storage, Event<T>} = 36,
		MoonbeamLazyMigrations: pallet_moonbeam_lazy_migrations::{Pallet, Call, Storage} = 37,
		Parameters: pallet_parameters = 38,
		// 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, Config<T>, 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,
		Assets: pallet_assets::{Pallet, Call, Storage, Event<T>} = 104,
		AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event<T>} = 105,
		// Previously 106: XTokens
		XcmTransactor: pallet_xcm_transactor::{Pallet, Call, Storage, Event<T>} = 107,
		// Previously 108: pallet_assets::<Instance1>
		EthereumXcm: pallet_ethereum_xcm::{Pallet, Call, Storage, Origin, Event<T>} = 109,
		Erc20XcmBridge: pallet_erc20_xcm_bridge::{Pallet} = 110,
		MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 111,
		EvmForeignAssets: pallet_moonbeam_foreign_assets::{Pallet, Call, Storage, Event<T>} = 114,
		XcmWeightTrader: pallet_xcm_weight_trader::{Pallet, Call, Storage, Event<T>} = 115,
		EmergencyParaXcm: pallet_emergency_para_xcm::{Pallet, Call, Storage, Event} = 116,
		// Utils
		RelayStorageRoots: pallet_relay_storage_roots::{Pallet, Storage} = 112,
		PrecompileBenchmarks: pallet_precompile_benchmarks::{Pallet} = 113,
		// Randomness
		Randomness: pallet_randomness::{Pallet, Call, Storage, Event<T>, Inherent} = 120,
	}
3605530
}
#[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!(
		[pallet_utility, Utility]
		[pallet_timestamp, Timestamp]
		[pallet_balances, Balances]
		[pallet_evm, EVM]
		[pallet_assets, Assets]
		[pallet_parachain_staking, ParachainStaking]
		[pallet_scheduler, Scheduler]
		[pallet_treasury, Treasury]
		[pallet_author_inherent, AuthorInherent]
		[pallet_author_slot_filter, AuthorFilter]
		[pallet_crowdloan_rewards, CrowdloanRewards]
		[pallet_author_mapping, AuthorMapping]
		[pallet_proxy, Proxy]
		[pallet_identity, Identity]
		[cumulus_pallet_parachain_system, ParachainSystem]
		[cumulus_pallet_xcmp_queue, XcmpQueue]
		[pallet_message_queue, MessageQueue]
		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
		[pallet_asset_manager, AssetManager]
		[pallet_xcm_transactor, XcmTransactor]
		[pallet_moonbeam_orbiters, MoonbeamOrbiters]
		[pallet_randomness, Randomness]
		[pallet_conviction_voting, ConvictionVoting]
		[pallet_referenda, Referenda]
		[pallet_preimage, Preimage]
		[pallet_whitelist, Whitelist]
		[pallet_multisig, Multisig]
		[pallet_moonbeam_lazy_migrations, MoonbeamLazyMigrations]
		[pallet_relay_storage_roots, RelayStorageRoots]
	);
}
/// 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.
// }
// ```
64
moonbeam_runtime_common::impl_runtime_apis_plus_common! {
64
	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
64
		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) {
64
				return InvalidTransaction::Call.into();
64
			}
64

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

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

            
64
			let dispatch_info = xt.get_dispatch_info();
64

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

            
64
					// Calculate the fee that will be taken by pallet transaction payment
64
					let fee: u64 = TransactionPayment::compute_fee(
						xt.encode().len() as u32,
						&dispatch_info,
						tip,
					).saturated_into();
					// Calculate how much gas this effectively uses according to the existing mapping
					let effective_gas =
						<Runtime as pallet_evm::Config>::GasWeightMapping::weight_to_gas(
							dispatch_info.weight
						);
64

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

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

            
64
	impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
64
		fn can_build_upon(
			included_hash: <Block as BlockT>::Hash,
			slot: async_backing_primitives::Slot,
		) -> bool {
			ConsensusHook::can_build_upon(included_hash, slot)
		}
64
	}
64
}
struct CheckInherents;
// Parity has decided to depreciate this trait, but does not offer a satisfactory replacement,
// see issue: https://github.com/paritytech/polkadot-sdk/issues/2841
#[allow(deprecated)]
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
	fn check_inherents(
		block: &Block,
		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
	) -> sp_inherents::CheckInherentsResult {
		let relay_chain_slot = relay_state_proof
			.read_slot()
			.expect("Could not read the relay chain slot from the proof");
		let inherent_data =
			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
				relay_chain_slot,
				sp_std::time::Duration::from_secs(6),
			)
			.create_inherent_data()
			.expect("Could not create the timestamp inherent data");
		inherent_data.check_extrinsics(block)
	}
}
// Nimbus's Executive wrapper allows relay validators to verify the seal digest
cumulus_pallet_parachain_system::register_validate_block!(
	Runtime = Runtime,
	BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
	CheckInherents = CheckInherents,
);
moonbeam_runtime_common::impl_self_contained_call!();
// Shorthand for a Get field of a pallet Config.
#[macro_export]
macro_rules! get {
	($pallet:ident, $name:ident, $type:ty) => {
		<<$crate::Runtime as $pallet::Config>::$name as $crate::Get<$type>>::get()
	};
}
#[cfg(test)]
mod tests {
	use super::{currency::*, *};
	#[test]
	// Helps us to identify a Pallet Call in case it exceeds the 1kb limit.
	// Hint: this should be a rare case. If that happens, one or more of the dispatchable arguments
	// need to be Boxed.
1
	fn call_max_size() {
1
		const CALL_ALIGN: u32 = 1024;
1
		assert!(std::mem::size_of::<pallet_evm_chain_id::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(std::mem::size_of::<pallet_evm::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(std::mem::size_of::<pallet_ethereum::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(
1
			std::mem::size_of::<pallet_parachain_staking::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(
1
			std::mem::size_of::<pallet_author_inherent::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(
1
			std::mem::size_of::<pallet_author_slot_filter::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(
1
			std::mem::size_of::<pallet_crowdloan_rewards::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(std::mem::size_of::<pallet_author_mapping::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(
1
			std::mem::size_of::<pallet_maintenance_mode::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
1
		assert!(std::mem::size_of::<pallet_migrations::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(
1
			std::mem::size_of::<pallet_moonbeam_lazy_migrations::Call<Runtime>>()
1
				<= CALL_ALIGN as usize
1
		);
1
		assert!(
1
			std::mem::size_of::<pallet_proxy_genesis_companion::Call<Runtime>>()
1
				<= CALL_ALIGN as usize
1
		);
1
	}
	#[test]
1
	fn currency_constants_are_correct() {
1
		assert_eq!(SUPPLY_FACTOR, 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
	}
}