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 Moonbase Runtime.
18
//!
19
//! Primary features of this runtime include:
20
//! * Ethereum compatibility
21
//! * Moonbase 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 256.
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
pub mod asset_config;
32
pub mod governance;
33
pub mod xcm_config;
34

            
35
mod migrations;
36
mod precompiles;
37

            
38
// Re-export required by get! macro.
39
#[cfg(feature = "std")]
40
pub use fp_evm::GenesisAccount;
41
pub use frame_support::traits::Get;
42
pub use moonbeam_core_primitives::{
43
	AccountId, AccountIndex, Address, AssetId, Balance, BlockNumber, DigestItem, Hash, Header,
44
	Index, Signature,
45
};
46
pub use pallet_author_slot_filter::EligibilityValue;
47
pub use pallet_parachain_staking::{weights::WeightInfo, InflationInfo, Range};
48
pub use precompiles::{
49
	MoonbasePrecompiles, PrecompileName, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
50
};
51

            
52
use account::AccountId20;
53
use cumulus_pallet_parachain_system::{
54
	RelayChainStateProof, RelayStateProof, RelaychainDataProvider, ValidationData,
55
};
56
use cumulus_primitives_core::{relay_chain, AggregateMessageOrigin};
57
use fp_rpc::TransactionStatus;
58
use frame_support::{
59
	construct_runtime,
60
	dispatch::{DispatchClass, GetDispatchInfo, PostDispatchInfo},
61
	ensure,
62
	pallet_prelude::DispatchResult,
63
	parameter_types,
64
	traits::{
65
		fungible::{Balanced, Credit, HoldConsideration, Inspect},
66
		tokens::imbalance::ResolveTo,
67
		tokens::{PayFromAccount, UnityAssetBalanceConversion},
68
		ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse,
69
		EqualPrivilegeOnly, FindAuthor, Imbalance, InstanceFilter, LinearStoragePrice, OnFinalize,
70
		OnUnbalanced,
71
	},
72
	weights::{
73
		constants::{RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND},
74
		ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
75
		WeightToFeePolynomial,
76
	},
77
	PalletId,
78
};
79

            
80
use frame_system::{EnsureRoot, EnsureSigned};
81
use governance::councils::*;
82
use moonbeam_rpc_primitives_txpool::TxPoolResponse;
83
use moonbeam_runtime_common::{
84
	timestamp::{ConsensusHookWrapperForRelayTimestamp, RelayTimestamp},
85
	weights as moonbeam_weights,
86
};
87
use nimbus_primitives::CanAuthor;
88
use pallet_ethereum::Call::transact;
89
use pallet_ethereum::{PostLogContent, Transaction as EthereumTransaction};
90
use pallet_evm::{
91
	Account as EVMAccount, EVMFungibleAdapter, EnsureAddressNever, EnsureAddressRoot,
92
	FeeCalculator, GasWeightMapping, IdentityAddressMapping,
93
	OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner,
94
};
95
use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment};
96
use pallet_treasury::TreasuryAccountId;
97
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
98
use scale_info::TypeInfo;
99
use sp_api::impl_runtime_apis;
100
use sp_consensus_slots::Slot;
101
use sp_core::{OpaqueMetadata, H160, H256, U256};
102
use sp_runtime::{
103
	create_runtime_str, generic, impl_opaque_keys,
104
	traits::{
105
		BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, IdentityLookup,
106
		PostDispatchInfoOf, UniqueSaturatedInto, Zero,
107
	},
108
	transaction_validity::{
109
		InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
110
	},
111
	ApplyExtrinsicResult, DispatchErrorWithPostInfo, FixedPointNumber, Perbill, Permill,
112
	Perquintill,
113
};
114
use sp_std::{
115
	convert::{From, Into},
116
	prelude::*,
117
};
118
#[cfg(feature = "std")]
119
use sp_version::NativeVersion;
120
use sp_version::RuntimeVersion;
121

            
122
use smallvec::smallvec;
123
use sp_runtime::serde::{Deserialize, Serialize};
124

            
125
#[cfg(any(feature = "std", test))]
126
pub use sp_runtime::BuildStorage;
127

            
128
pub type Precompiles = MoonbasePrecompiles<Runtime>;
129

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

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

            
137
	pub const WEI: Balance = 1;
138
	pub const KILOWEI: Balance = 1_000;
139
	pub const MEGAWEI: Balance = 1_000_000;
140
	pub const GIGAWEI: Balance = 1_000_000_000;
141
	pub const MICROUNIT: Balance = 1_000_000_000_000;
142
	pub const MILLIUNIT: Balance = 1_000_000_000_000_000;
143
	pub const UNIT: Balance = 1_000_000_000_000_000_000;
144
	pub const KILOUNIT: Balance = 1_000_000_000_000_000_000_000;
145

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

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

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

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

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

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

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

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

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

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

            
234
parameter_types! {
235
	pub const Version: RuntimeVersion = VERSION;
236
	/// TODO: this is left here so that `impl_runtime_apis_plus_common` will find the same type for
237
	/// `BlockWeights` in all runtimes. It can probably be removed once the custom
238
	/// `RuntimeBlockWeights` has been pushed to each runtime.
239
	pub BlockWeights: frame_system::limits::BlockWeights = RuntimeBlockWeights::get();
240
	/// We allow for 5 MB blocks.
241
	pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
242
		::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
243
}
244

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

            
292
impl pallet_utility::Config for Runtime {
293
	type RuntimeEvent = RuntimeEvent;
294
	type RuntimeCall = RuntimeCall;
295
	type PalletsOrigin = OriginCaller;
296
	type WeightInfo = moonbeam_weights::pallet_utility::WeightInfo<Runtime>;
297
}
298

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

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

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

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

            
335
pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
336
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
337
where
338
	R: pallet_balances::Config + pallet_treasury::Config,
339
{
340
	// this seems to be called for substrate-based transactions
341
1
	fn on_unbalanceds<B>(
342
1
		mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
343
1
	) {
344
1
		if let Some(fees) = fees_then_tips.next() {
345
			// for fees, 80% are burned, 20% to the treasury
346
1
			let (_, to_treasury) = fees.ration(80, 20);
347
1
			// Balances pallet automatically burns dropped Credits by decreasing
348
1
			// total_supply accordingly
349
1
			ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(
350
1
				to_treasury,
351
1
			);
352

            
353
			// handle tip if there is one
354
1
			if let Some(tip) = fees_then_tips.next() {
355
1
				// for now we use the same burn/treasury strategy used for regular fees
356
1
				let (_, to_treasury) = tip.ration(80, 20);
357
1
				ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(
358
1
					to_treasury,
359
1
				);
360
1
			}
361
		}
362
1
	}
363

            
364
	// this is called from pallet_evm for Ethereum-based transactions
365
	// (technically, it calls on_unbalanced, which calls this when non-zero)
366
129
	fn on_nonzero_unbalanced(amount: Credit<R::AccountId, pallet_balances::Pallet<R>>) {
367
129
		// Balances pallet automatically burns dropped Credits by decreasing
368
129
		// total_supply accordingly
369
129
		let (_, to_treasury) = amount.ration(80, 20);
370
129
		ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
371
129
	}
372
}
373

            
374
pub struct LengthToFee;
375
impl WeightToFeePolynomial for LengthToFee {
376
	type Balance = Balance;
377

            
378
96
	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
379
96
		smallvec![
380
			WeightToFeeCoefficient {
381
				degree: 1,
382
96
				coeff_frac: Perbill::zero(),
383
				coeff_integer: currency::TRANSACTION_BYTE_FEE,
384
				negative: false,
385
			},
386
			WeightToFeeCoefficient {
387
				degree: 3,
388
96
				coeff_frac: Perbill::zero(),
389
96
				coeff_integer: 1 * currency::SUPPLY_FACTOR,
390
				negative: false,
391
			},
392
		]
393
96
	}
394
}
395

            
396
impl pallet_transaction_payment::Config for Runtime {
397
	type RuntimeEvent = RuntimeEvent;
398
	type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees<Runtime>>;
399
	type OperationalFeeMultiplier = ConstU8<5>;
400
	type WeightToFee = ConstantMultiplier<Balance, ConstU128<{ currency::WEIGHT_FEE }>>;
401
	type LengthToFee = LengthToFee;
402
	type FeeMultiplierUpdate = FastAdjustingFeeUpdate<Runtime>;
403
}
404

            
405
impl pallet_sudo::Config for Runtime {
406
	type RuntimeCall = RuntimeCall;
407
	type RuntimeEvent = RuntimeEvent;
408
	type WeightInfo = moonbeam_weights::pallet_sudo::WeightInfo<Runtime>;
409
}
410

            
411
impl pallet_evm_chain_id::Config for Runtime {}
412

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

            
419
/// Approximate ratio of the amount of Weight per Gas.
420
/// u64 works for approximations because Weight is a very small unit compared to gas.
421
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
422
/// The highest amount of new storage that can be created in a block (160KB).
423
pub const BLOCK_STORAGE_LIMIT: u64 = 160 * 1024;
424
parameter_types! {
425
	pub BlockGasLimit: U256
426
		= U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
427
	/// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less
428
	/// than this will decrease the weight and more will increase.
429
	pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(35);
430
	/// The adjustment variable of the runtime. Higher values will cause `TargetBlockFullness` to
431
	/// change the fees more rapidly. This fast multiplier responds by doubling/halving in
432
	/// approximately one hour at extreme block congestion levels.
433
	pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(4, 1_000);
434
	/// Minimum amount of the multiplier. This value cannot be too low. A test case should ensure
435
	/// that combined with `AdjustmentVariable`, we can recover from the minimum.
436
	/// See `multiplier_can_grow_from_zero` in integration_tests.rs.
437
	pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10);
438
	/// Maximum multiplier. We pick a value that is expensive but not impossibly so; it should act
439
	/// as a safety net.
440
	pub MaximumMultiplier: Multiplier = Multiplier::from(100_000u128);
441
	pub PrecompilesValue: MoonbasePrecompiles<Runtime> = MoonbasePrecompiles::<_>::new();
442
	pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
443
	/// The amount of gas per pov. A ratio of 16 if we convert ref_time to gas and we compare
444
	/// it with the pov_size for a block. E.g.
445
	/// ceil(
446
	///     (max_extrinsic.ref_time() / max_extrinsic.proof_size()) / WEIGHT_PER_GAS
447
	/// )
448
	/// We should re-check `xcm_config::Erc20XcmBridgeTransferGasLimit` when changing this value
449
	pub const GasLimitPovSizeRatio: u64 = 16;
450
	/// The amount of gas per storage (in bytes): BLOCK_GAS_LIMIT / BLOCK_STORAGE_LIMIT
451
	/// (60_000_000 / 160 kb)
452
	pub GasLimitStorageGrowthRatio: u64 = 366;
453
}
454

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

            
480
/// A "Fast" TargetedFeeAdjustment. Parameters chosen based on model described here:
481
/// https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html#-1.-fast-adjusting-mechanism // editorconfig-checker-disable-line
482
///
483
/// The adjustment algorithm boils down to:
484
///
485
/// diff = (previous_block_weight - target) / maximum_block_weight
486
/// next_multiplier = prev_multiplier * (1 + (v * diff) + ((v * diff)^2 / 2))
487
/// assert(next_multiplier > min)
488
///     where: v is AdjustmentVariable
489
///            target is TargetBlockFullness
490
///            min is MinimumMultiplier
491
pub type FastAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
492
	R,
493
	TargetBlockFullness,
494
	AdjustmentVariable,
495
	MinimumMultiplier,
496
	MaximumMultiplier,
497
>;
498

            
499
/// The author inherent provides an AccountId, but pallet evm needs an H160.
500
/// This simple adapter makes the conversion for any types T, U such that T: Into<U>
501
pub struct FindAuthorAdapter<T, U, Inner>(sp_std::marker::PhantomData<(T, U, Inner)>);
502

            
503
impl<T, U, Inner> FindAuthor<U> for FindAuthorAdapter<T, U, Inner>
504
where
505
	T: Into<U>,
506
	Inner: FindAuthor<T>,
507
{
508
6789
	fn find_author<'a, I>(digests: I) -> Option<U>
509
6789
	where
510
6789
		I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
511
6789
	{
512
6789
		Inner::find_author(digests).map(Into::into)
513
6789
	}
514
}
515

            
516
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
517

            
518
impl pallet_evm::Config for Runtime {
519
	type FeeCalculator = TransactionPaymentAsGasPrice;
520
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
521
	type WeightPerGas = WeightPerGas;
522
	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
523
	type CallOrigin = EnsureAddressRoot<AccountId>;
524
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
525
	type AddressMapping = IdentityAddressMapping;
526
	type Currency = Balances;
527
	type RuntimeEvent = RuntimeEvent;
528
	type Runner = pallet_evm::runner::stack::Runner<Self>;
529
	type PrecompilesType = MoonbasePrecompiles<Self>;
530
	type PrecompilesValue = PrecompilesValue;
531
	type ChainId = EthereumChainId;
532
	type OnChargeTransaction = OnChargeEVMTransaction<DealWithFees<Runtime>>;
533
	type BlockGasLimit = BlockGasLimit;
534
	type FindAuthor = FindAuthorAdapter<AccountId20, H160, AuthorInherent>;
535
	type OnCreate = ();
536
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
537
	type SuicideQuickClearLimit = ConstU32<0>;
538
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
539
	type Timestamp = RelayTimestamp;
540
	type WeightInfo = moonbeam_weights::pallet_evm::WeightInfo<Runtime>;
541
}
542

            
543
parameter_types! {
544
	pub MaximumSchedulerWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
545
	pub const NoPreimagePostponement: Option<u32> = Some(10);
546
}
547

            
548
impl pallet_scheduler::Config for Runtime {
549
	type RuntimeEvent = RuntimeEvent;
550
	type RuntimeOrigin = RuntimeOrigin;
551
	type PalletsOrigin = OriginCaller;
552
	type RuntimeCall = RuntimeCall;
553
	type MaximumWeight = MaximumSchedulerWeight;
554
	type ScheduleOrigin = EnsureRoot<AccountId>;
555
	type MaxScheduledPerBlock = ConstU32<50>;
556
	type WeightInfo = moonbeam_weights::pallet_scheduler::WeightInfo<Runtime>;
557
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
558
	type Preimages = Preimage;
559
}
560

            
561
parameter_types! {
562
	pub const PreimageBaseDeposit: Balance = 5 * currency::UNIT * currency::SUPPLY_FACTOR ;
563
	pub const PreimageByteDeposit: Balance = currency::STORAGE_BYTE_FEE;
564
	pub const PreimageHoldReason: RuntimeHoldReason =
565
		RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
566
}
567

            
568
impl pallet_preimage::Config for Runtime {
569
	type WeightInfo = moonbeam_weights::pallet_preimage::WeightInfo<Runtime>;
570
	type RuntimeEvent = RuntimeEvent;
571
	type Currency = Balances;
572
	type ManagerOrigin = EnsureRoot<AccountId>;
573
	type Consideration = HoldConsideration<
574
		AccountId,
575
		Balances,
576
		PreimageHoldReason,
577
		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
578
	>;
579
}
580

            
581
parameter_types! {
582
	pub const ProposalBond: Permill = Permill::from_percent(5);
583
	pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
584
	pub TreasuryAccount: AccountId = Treasury::account_id();
585
}
586

            
587
type TreasuryApproveOrigin = EitherOfDiverse<
588
	EnsureRoot<AccountId>,
589
	pallet_collective::EnsureProportionAtLeast<AccountId, TreasuryCouncilInstance, 3, 5>,
590
>;
591

            
592
type TreasuryRejectOrigin = EitherOfDiverse<
593
	EnsureRoot<AccountId>,
594
	pallet_collective::EnsureProportionMoreThan<AccountId, TreasuryCouncilInstance, 1, 2>,
595
>;
596

            
597
impl pallet_treasury::Config for Runtime {
598
	type PalletId = TreasuryId;
599
	type Currency = Balances;
600
	// At least three-fifths majority of the council is required (or root) to approve a proposal
601
	type ApproveOrigin = TreasuryApproveOrigin;
602
	// More than half of the council is required (or root) to reject a proposal
603
	type RejectOrigin = TreasuryRejectOrigin;
604
	type RuntimeEvent = RuntimeEvent;
605
	// If spending proposal rejected, transfer proposer bond to treasury
606
	type OnSlash = Treasury;
607
	type ProposalBond = ProposalBond;
608
	type ProposalBondMinimum = ConstU128<{ 1 * currency::UNIT * currency::SUPPLY_FACTOR }>;
609
	type SpendPeriod = ConstU32<{ 6 * DAYS }>;
610
	type Burn = ();
611
	type BurnDestination = ();
612
	type MaxApprovals = ConstU32<100>;
613
	type WeightInfo = moonbeam_weights::pallet_treasury::WeightInfo<Runtime>;
614
	type SpendFunds = ();
615
	type ProposalBondMaximum = ();
616
	#[cfg(not(feature = "runtime-benchmarks"))]
617
	type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>; // Disabled, no spending
618
	#[cfg(feature = "runtime-benchmarks")]
619
	type SpendOrigin =
620
		frame_system::EnsureWithSuccess<EnsureRoot<AccountId>, AccountId, benches::MaxBalance>;
621
	type AssetKind = ();
622
	type Beneficiary = AccountId;
623
	type BeneficiaryLookup = IdentityLookup<AccountId>;
624
	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
625
	type BalanceConverter = UnityAssetBalanceConversion;
626
	type PayoutPeriod = ConstU32<{ 30 * DAYS }>;
627
	#[cfg(feature = "runtime-benchmarks")]
628
	type BenchmarkHelper = BenchmarkHelper;
629
}
630

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

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

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

            
669
pub struct TransactionConverter;
670

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

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

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

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

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

            
721
impl pallet_ethereum_xcm::Config for Runtime {
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
}
729

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

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

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

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

            
763
impl parachain_info::Config for Runtime {}
764

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

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

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

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

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

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

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

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

            
878
#[cfg(test)]
879
mod mock {
880
	use super::*;
881
	pub struct MockRandomness;
882
	impl frame_support::traits::Randomness<H256, BlockNumber> for MockRandomness {
883
		fn random(subject: &[u8]) -> (H256, BlockNumber) {
884
			(H256(sp_io::hashing::blake2_256(subject)), 0)
885
		}
886
	}
887
}
888

            
889
impl pallet_author_slot_filter::Config for Runtime {
890
	type RuntimeEvent = RuntimeEvent;
891
	#[cfg(not(test))]
892
	type RandomnessSource = Randomness;
893
	#[cfg(test)]
894
	type RandomnessSource = mock::MockRandomness;
895
	type PotentialAuthors = ParachainStaking;
896
	type WeightInfo = moonbeam_weights::pallet_author_slot_filter::WeightInfo<Runtime>;
897
}
898

            
899
impl pallet_async_backing::Config for Runtime {
900
	type AllowMultipleBlocksPerSlot = ConstBool<true>;
901
	type GetAndVerifySlot = pallet_async_backing::RelaySlot;
902
	type ExpectedBlockTime = ConstU64<6000>;
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"moonbase-";
909

            
910
}
911

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

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

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

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

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

            
992
// Be careful: Each time this filter is modified, the substrate filter must also be modified
993
// consistently.
994
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
995
	fn is_evm_proxy_call_allowed(
996
		&self,
997
		call: &pallet_evm_precompile_proxy::EvmSubCall,
998
		recipient_has_code: bool,
999
		gas: u64,
	) -> precompile_utils::EvmResult<bool> {
		Ok(match self {
			ProxyType::Any => true,
			ProxyType::NonTransfer => {
				call.value == U256::zero()
					&& match PrecompileName::from_address(call.to.0) {
						Some(
							PrecompileName::AuthorMappingPrecompile
							| PrecompileName::IdentityPrecompile
							| 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 = moonbeam_weights::pallet_proxy::WeightInfo<Runtime>;
	type MaxPending = ConstU32<32>;
	type CallHasher = BlakeTwo256;
	type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
	// Additional storage item size of 56 bytes:
	// - 20 bytes AccountId
	// - 32 bytes Hasher (Blake2256)
	// - 4 bytes BlockNumber (u32)
	type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 56) }>;
}
impl pallet_migrations::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	// TODO wire up our correct list of migrations here. Maybe this shouldn't be in
	// `moonbeam_runtime_common`.
	type MigrationsList = (
		moonbeam_runtime_common::migrations::CommonMigrations<Runtime>,
		migrations::MoonbaseMigrations,
	);
	type XcmExecutionManager = XcmExecutionManager;
}
impl pallet_moonbeam_lazy_migrations::Config for Runtime {
	type WeightInfo = moonbeam_weights::pallet_moonbeam_lazy_migrations::WeightInfo<Runtime>;
}
/// Maintenance mode Call filter
pub struct MaintenanceFilter;
impl Contains<RuntimeCall> for MaintenanceFilter {
	fn contains(c: &RuntimeCall) -> bool {
		match c {
			RuntimeCall::Assets(_) => false,
			RuntimeCall::Balances(_) => false,
			RuntimeCall::CrowdloanRewards(_) => false,
			RuntimeCall::Ethereum(_) => false,
			RuntimeCall::EVM(_) => false,
			RuntimeCall::Identity(_) => false,
			RuntimeCall::XTokens(_) => 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 {
192
	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 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
8
			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,
		}
192
	}
}
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 = moonbeam_weights::pallet_moonbeam_orbiters::WeightInfo<Runtime>;
}
/// Only callable after `set_validation_data` is called which forms this proof the same way
fn relay_chain_state_proof<Runtime>() -> RelayChainStateProof
where
	Runtime: cumulus_pallet_parachain_system::Config,
{
	let relay_storage_root = ValidationData::<Runtime>::get()
		.expect("set in `set_validation_data`")
		.relay_parent_storage_root;
	let relay_chain_state =
		RelayStateProof::<Runtime>::get().expect("set in `set_validation_data`");
	RelayChainStateProof::new(ParachainInfo::get(), relay_storage_root, relay_chain_state)
		.expect("Invalid relay chain state proof, already constructed in `set_validation_data`")
}
pub struct BabeDataGetter<Runtime>(sp_std::marker::PhantomData<Runtime>);
impl<Runtime> pallet_randomness::GetBabeData<u64, Option<Hash>> for BabeDataGetter<Runtime>
where
	Runtime: cumulus_pallet_parachain_system::Config,
{
	// Tolerate panic here because only ever called in inherent (so can be omitted)
	fn get_epoch_index() -> u64 {
		if cfg!(feature = "runtime-benchmarks") {
			// storage reads as per actual reads
			let _relay_storage_root = ValidationData::<Runtime>::get();
			let _relay_chain_state = RelayStateProof::<Runtime>::get();
			const BENCHMARKING_NEW_EPOCH: u64 = 10u64;
			return BENCHMARKING_NEW_EPOCH;
		}
		relay_chain_state_proof::<Runtime>()
			.read_optional_entry(relay_chain::well_known_keys::EPOCH_INDEX)
			.ok()
			.flatten()
			.expect("expected to be able to read epoch index from relay chain state proof")
	}
	fn get_epoch_randomness() -> Option<Hash> {
		if cfg!(feature = "runtime-benchmarks") {
			// storage reads as per actual reads
			let _relay_storage_root = ValidationData::<Runtime>::get();
			let _relay_chain_state = RelayStateProof::<Runtime>::get();
			let benchmarking_babe_output = Hash::default();
			return Some(benchmarking_babe_output);
		}
		relay_chain_state_proof::<Runtime>()
			.read_optional_entry(relay_chain::well_known_keys::ONE_EPOCH_AGO_RANDOMNESS)
			.ok()
			.flatten()
	}
}
impl pallet_randomness::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type AddressMapping = sp_runtime::traits::ConvertInto;
	type Currency = Balances;
	type BabeDataGetter = BabeDataGetter<Runtime>;
	type VrfKeyLookup = AuthorMapping;
	type Deposit = ConstU128<{ 1 * currency::UNIT * currency::SUPPLY_FACTOR }>;
	type MaxRandomWords = ConstU8<100>;
	type MinBlockDelay = ConstU32<2>;
	type MaxBlockDelay = ConstU32<2_000>;
	type BlockExpirationDelay = ConstU32<10_000>;
	type EpochExpirationDelay = ConstU64<10_000>;
	type WeightInfo = moonbeam_weights::pallet_randomness::WeightInfo<Runtime>;
}
impl pallet_root_testing::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
}
parameter_types! {
	// One storage item; key size is 32 + 20; value is size 4+4+16+20 bytes = 44 bytes.
	pub const DepositBase: Balance = currency::deposit(1, 96);
	// Additional storage item size of 20 bytes.
	pub const DepositFactor: Balance = currency::deposit(0, 20);
	pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeCall = RuntimeCall;
	type Currency = Balances;
	type DepositBase = DepositBase;
	type DepositFactor = DepositFactor;
	type MaxSignatories = MaxSignatories;
	type WeightInfo = moonbeam_weights::pallet_multisig::WeightInfo<Runtime>;
}
impl pallet_relay_storage_roots::Config for Runtime {
	type MaxStorageRoots = ConstU32<30>;
	type RelaychainStateProvider = cumulus_pallet_parachain_system::RelaychainDataProvider<Self>;
	type WeightInfo = moonbeam_weights::pallet_relay_storage_roots::WeightInfo<Runtime>;
}
impl pallet_precompile_benchmarks::Config for Runtime {
	type WeightInfo = moonbeam_weights::pallet_precompile_benchmarks::WeightInfo<Runtime>;
}
744058
construct_runtime! {
	pub enum Runtime
	{
		System: frame_system::{Pallet, Call, Storage, Config<T>, Event<T>} = 0,
		Utility: pallet_utility::{Pallet, Call, Event} = 1,
		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2,
		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 3,
		Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>} = 4,
		// Previously 5: pallet_randomness_collective_flip
		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>} = 6,
		TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Config<T>, Event<T>} = 7,
		ParachainInfo: parachain_info::{Pallet, Storage, Config<T>} = 8,
		EthereumChainId: pallet_evm_chain_id::{Pallet, Storage, Config<T>} = 9,
		EVM: pallet_evm::{Pallet, Config<T>, Call, Storage, Event<T>} = 10,
		Ethereum: pallet_ethereum::{Pallet, Call, Storage, Event, Origin, Config<T>} = 11,
		ParachainStaking: pallet_parachain_staking::{Pallet, Call, Storage, Event<T>, Config<T>} = 12,
		Scheduler: pallet_scheduler::{Pallet, Storage, Event<T>, Call} = 13,
		// Previously 14: pallet_democracy::{Pallet, Storage, Config<T>, Event<T>, Call} = 14,
		// Previously 15: CouncilCollective: pallet_collective::<Instance1>
		// Previously 16: TechCommitteeCollective: pallet_collective::<Instance2>
		Treasury: pallet_treasury::{Pallet, Storage, Config<T>, Event<T>, Call} = 17,
		AuthorInherent: pallet_author_inherent::{Pallet, Call, Storage, Inherent} = 18,
		AuthorFilter: pallet_author_slot_filter::{Pallet, Call, Storage, Event, Config<T>} = 19,
		CrowdloanRewards: pallet_crowdloan_rewards::{Pallet, Call, Config<T>, Storage, Event<T>} = 20,
		AuthorMapping: pallet_author_mapping::{Pallet, Call, Config<T>, Storage, Event<T>} = 21,
		Proxy: pallet_proxy::{Pallet, Call, Storage, Event<T>} = 22,
		MaintenanceMode: pallet_maintenance_mode::{Pallet, Call, Config<T>, Storage, Event} = 23,
		Identity: pallet_identity::{Pallet, Call, Storage, Event<T>} = 24,
		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 25,
		CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 26,
		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 27,
		PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 28,
		Assets: pallet_assets::{Pallet, Call, Storage, Event<T>} = 29,
		XTokens: orml_xtokens::{Pallet, Call, Storage, Event<T>} = 30,
		AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event<T>} = 31,
		Migrations: pallet_migrations::{Pallet, Storage, Config<T>, Event<T>} = 32,
		XcmTransactor: pallet_xcm_transactor::{Pallet, Call, Config<T>, Storage, Event<T>} = 33,
		ProxyGenesisCompanion: pallet_proxy_genesis_companion::{Pallet, Config<T>} = 34,
		// Previously 35: BaseFee
		// Previously 36: pallet_assets::<Instance1>
		MoonbeamOrbiters: pallet_moonbeam_orbiters::{Pallet, Call, Storage, Event<T>, Config<T>} = 37,
		EthereumXcm: pallet_ethereum_xcm::{Pallet, Call, Storage, Origin} = 38,
		Randomness: pallet_randomness::{Pallet, Call, Storage, Event<T>, Inherent} = 39,
		TreasuryCouncilCollective:
			pallet_collective::<Instance3>::{Pallet, Call, Storage, Event<T>, Origin<T>, Config<T>} = 40,
		ConvictionVoting: pallet_conviction_voting::{Pallet, Call, Storage, Event<T>} = 41,
		Referenda: pallet_referenda::{Pallet, Call, Storage, Event<T>} = 42,
		Origins: governance::custom_origins::{Origin} = 43,
		Preimage: pallet_preimage::{Pallet, Call, Storage, Event<T>, HoldReason} = 44,
		Whitelist: pallet_whitelist::{Pallet, Call, Storage, Event<T>} = 45,
		OpenTechCommitteeCollective:
			pallet_collective::<Instance4>::{Pallet, Call, Storage, Event<T>, Origin<T>, Config<T>} = 46,
		RootTesting: pallet_root_testing::{Pallet, Call, Storage, Event<T>} = 47,
		Erc20XcmBridge: pallet_erc20_xcm_bridge::{Pallet} = 48,
		Multisig: pallet_multisig::{Pallet, Call, Storage, Event<T>} = 49,
		AsyncBacking: pallet_async_backing::{Pallet, Storage} = 50,
		MoonbeamLazyMigrations: pallet_moonbeam_lazy_migrations::{Pallet, Call, Storage} = 51,
		RelayStorageRoots: pallet_relay_storage_roots::{Pallet, Storage} = 52,
		PrecompileBenchmarks: pallet_precompile_benchmarks::{Pallet} = 53,
		MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 54,
		EmergencyParaXcm: pallet_emergency_para_xcm::{Pallet, Call, Storage, Event} = 55,
	}
3623893
}
/// 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>,
);
/// 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,
>;
#[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_sudo, Sudo]
		[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_xcmp_queue, XcmpQueue]
		[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_relay_storage_roots, RelayStorageRoots]
		[pallet_precompile_benchmarks, PrecompileBenchmarks]
		[pallet_moonbeam_lazy_migrations, MoonbeamLazyMigrations]
	);
}
// 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.
// }
// ```
602402
moonbeam_runtime_common::impl_runtime_apis_plus_common! {
602402
	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
602402
		fn validate_transaction(
8
			source: TransactionSource,
8
			xt: <Block as BlockT>::Extrinsic,
8
			block_hash: <Block as BlockT>::Hash,
8
		) -> TransactionValidity {
8
			// Filtered calls should not enter the tx pool as they'll fail if inserted.
8
			// If this call is not allowed, we return early.
8
			if !<Runtime as frame_system::Config>::BaseCallFilter::contains(&xt.0.function) {
602402
				return InvalidTransaction::Call.into();
602402
			}
602402

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

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

            
602402
			let dispatch_info = xt.get_dispatch_info();
602402

            
602402
			// If this is a pallet ethereum transaction, then its priority is already set
602402
			// according to effective priority fee from pallet ethereum. If it is any other kind of
602402
			// transaction, we modify its priority. The goal is to arrive at a similar metric used
602402
			// by pallet ethereum, which means we derive a fee-per-gas from the txn's tip and
602402
			// weight.
602402
			Ok(match &xt.0.function {
602402
				RuntimeCall::Ethereum(transact { .. }) => intermediate_valid,
602402
				_ if dispatch_info.class != DispatchClass::Normal => intermediate_valid,
602402
				_ => {
602402
					let tip = match xt.0.signature {
602402
						None => 0,
602402
						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()
602402
						}
602402
					};
602402

            
602402
					let effective_gas =
						<Runtime as pallet_evm::Config>::GasWeightMapping::weight_to_gas(
							dispatch_info.weight
						);
602402
					let tip_per_gas = if effective_gas > 0 {
602402
						tip.saturating_div(effective_gas as u128)
602402
					} else {
602402
						0
602402
					};
602402

            
602402
					// Overwrite the original prioritization with this ethereum one
602402
					intermediate_valid.priority = tip_per_gas as u64;
					intermediate_valid
602402
				}
602402
			})
602402
		}
602402
	}
602402

            
602402
	impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
602402
		fn can_build_upon(
			included_hash: <Block as BlockT>::Hash,
			slot: async_backing_primitives::Slot,
		) -> bool {
			ConsensusHook::can_build_upon(included_hash, slot)
		}
602402
	}
602402
}
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::<orml_xtokens::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(std::mem::size_of::<pallet_asset_manager::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
		);
1
		assert!(std::mem::size_of::<pallet_xcm_transactor::Call<Runtime>>() <= CALL_ALIGN as usize);
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 * MICROUNIT));
		// treasury minimums
1
		assert_eq!(
1
			get!(pallet_treasury, ProposalBondMinimum, u128),
1
			Balance::from(1 * UNIT)
1
		);
		// pallet_identity deposits
1
		assert_eq!(
1
			get!(pallet_identity, BasicDeposit, u128),
1
			Balance::from(1 * UNIT + 25800 * MICROUNIT)
1
		);
1
		assert_eq!(
1
			get!(pallet_identity, ByteDeposit, u128),
1
			Balance::from(100 * MICROUNIT)
1
		);
1
		assert_eq!(
1
			get!(pallet_identity, SubAccountDeposit, u128),
1
			Balance::from(1 * UNIT + 5300 * MICROUNIT)
1
		);
		// staking minimums
1
		assert_eq!(
1
			get!(pallet_parachain_staking, MinCandidateStk, u128),
1
			Balance::from(500 * UNIT)
1
		);
1
		assert_eq!(
1
			get!(pallet_parachain_staking, MinDelegation, u128),
1
			Balance::from(1 * UNIT)
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 * UNIT)
1
		);
		// proxy deposits
1
		assert_eq!(
1
			get!(pallet_proxy, ProxyDepositBase, u128),
1
			Balance::from(1 * UNIT + 800 * MICROUNIT)
1
		);
1
		assert_eq!(
1
			get!(pallet_proxy, ProxyDepositFactor, u128),
1
			Balance::from(2100 * MICROUNIT)
1
		);
1
		assert_eq!(
1
			get!(pallet_proxy, AnnouncementDepositBase, u128),
1
			Balance::from(1 * UNIT + 800 * MICROUNIT)
1
		);
1
		assert_eq!(
1
			get!(pallet_proxy, AnnouncementDepositFactor, u128),
1
			Balance::from(5600 * MICROUNIT)
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 test_proxy_type_can_be_decoded_from_valid_values() {
1
		let test_cases = vec![
1
			// (input, expected)
1
			(0u8, ProxyType::Any),
1
			(1, ProxyType::NonTransfer),
1
			(2, ProxyType::Governance),
1
			(3, ProxyType::Staking),
1
			(4, ProxyType::CancelProxy),
1
			(5, ProxyType::Balances),
1
			(6, ProxyType::AuthorMapping),
1
			(7, ProxyType::IdentityJudgement),
1
		];
9
		for (input, expected) in test_cases {
8
			let actual = ProxyType::decode(&mut input.to_le_bytes().as_slice());
8
			assert_eq!(
8
				Ok(expected),
				actual,
				"failed decoding ProxyType for value '{}'",
				input
			);
		}
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
		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
	}
}