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

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

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

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

            
17
//! The 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.
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
#[cfg(not(feature = "disable-genesis-builder"))]
33
pub mod genesis_config_preset;
34
pub mod governance;
35
pub mod runtime_params;
36
pub mod xcm_config;
37

            
38
mod migrations;
39
mod precompiles;
40

            
41
extern crate alloc;
42
extern crate core;
43

            
44
use alloc::borrow::Cow;
45
// Re-export required by get! macro.
46
#[cfg(feature = "std")]
47
pub use fp_evm::GenesisAccount;
48
pub use frame_support::traits::Get;
49
pub use moonbeam_core_primitives::{
50
	AccountId, AccountIndex, Address, AssetId, Balance, BlockNumber, DigestItem, Hash, Header,
51
	Index, Signature,
52
};
53
pub use pallet_author_slot_filter::EligibilityValue;
54
pub use pallet_parachain_staking::{weights::WeightInfo, InflationInfo, Range};
55
pub use precompiles::{
56
	MoonbasePrecompiles, PrecompileName, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
57
};
58

            
59
use account::AccountId20;
60
use cumulus_pallet_parachain_system::{
61
	RelayChainStateProof, RelayStateProof, RelaychainDataProvider, ValidationData,
62
};
63
use cumulus_primitives_core::{relay_chain, AggregateMessageOrigin};
64
use fp_rpc::TransactionStatus;
65
use frame_support::{
66
	construct_runtime,
67
	dispatch::{DispatchClass, GetDispatchInfo, PostDispatchInfo},
68
	ensure,
69
	pallet_prelude::DispatchResult,
70
	parameter_types,
71
	traits::{
72
		fungible::{Balanced, Credit, HoldConsideration, Inspect, NativeOrWithId},
73
		ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, EitherOf,
74
		EitherOfDiverse, EqualPrivilegeOnly, FindAuthor, InstanceFilter, LinearStoragePrice,
75
		OnFinalize, OnUnbalanced,
76
	},
77
	weights::{
78
		constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, Weight, WeightToFeeCoefficient,
79
		WeightToFeeCoefficients, WeightToFeePolynomial,
80
	},
81
	PalletId,
82
};
83
use frame_system::{EnsureRoot, EnsureSigned};
84
use governance::councils::*;
85
use moonbeam_rpc_primitives_txpool::TxPoolResponse;
86
use moonbeam_runtime_common::{
87
	impl_asset_conversion::AssetRateConverter, impl_multiasset_paymaster::MultiAssetPaymaster,
88
};
89
use nimbus_primitives::CanAuthor;
90
use pallet_ethereum::Call::transact;
91
use pallet_ethereum::{PostLogContent, Transaction as EthereumTransaction};
92
use pallet_evm::{
93
	Account as EVMAccount, EVMFungibleAdapter, EnsureAddressNever, EnsureAddressRoot,
94
	FeeCalculator, FrameSystemAccountProvider, GasWeightMapping, IdentityAddressMapping,
95
	OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner,
96
};
97
use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment};
98
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
99
use runtime_params::*;
100
use scale_info::TypeInfo;
101
use sp_api::impl_runtime_apis;
102
use sp_consensus_slots::Slot;
103
use sp_core::{OpaqueMetadata, H160, H256, U256};
104
use sp_runtime::generic::Preamble;
105
use sp_runtime::{
106
	generic, impl_opaque_keys,
107
	traits::{
108
		BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, IdentityLookup,
109
		PostDispatchInfoOf, UniqueSaturatedInto, Zero,
110
	},
111
	transaction_validity::{
112
		InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
113
	},
114
	ApplyExtrinsicResult, DispatchErrorWithPostInfo, FixedPointNumber, Perbill, Permill,
115
	Perquintill,
116
};
117
use sp_std::{
118
	convert::{From, Into},
119
	prelude::*,
120
};
121
#[cfg(feature = "std")]
122
use sp_version::NativeVersion;
123
use sp_version::RuntimeVersion;
124
use xcm::{
125
	Version as XcmVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
126
};
127
use xcm_runtime_apis::{
128
	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
129
	fees::Error as XcmPaymentApiError,
130
};
131

            
132
use smallvec::smallvec;
133
use sp_runtime::serde::{Deserialize, Serialize};
134

            
135
#[cfg(any(feature = "std", test))]
136
pub use sp_runtime::BuildStorage;
137

            
138
pub type Precompiles = MoonbasePrecompiles<Runtime>;
139

            
140
mod weights;
141

            
142
pub(crate) use weights as moonbase_weights;
143

            
144
pub use weights::xcm as moonbase_xcm_weights;
145

            
146
/// UNIT, the native token, uses 18 decimals of precision.
147
pub mod currency {
148
	use super::Balance;
149

            
150
	// Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
151
	pub const SUPPLY_FACTOR: Balance = 1;
152

            
153
	pub const WEI: Balance = 1;
154
	pub const KILOWEI: Balance = 1_000;
155
	pub const MEGAWEI: Balance = 1_000_000;
156
	pub const GIGAWEI: Balance = 1_000_000_000;
157
	pub const MICROUNIT: Balance = 1_000_000_000_000;
158
	pub const MILLIUNIT: Balance = 1_000_000_000_000_000;
159
	pub const UNIT: Balance = 1_000_000_000_000_000_000;
160
	pub const KILOUNIT: Balance = 1_000_000_000_000_000_000_000;
161

            
162
	pub const TRANSACTION_BYTE_FEE: Balance = 1 * GIGAWEI * SUPPLY_FACTOR;
163
	pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
164
	pub const WEIGHT_FEE: Balance = 50 * KILOWEI * SUPPLY_FACTOR / 4;
165

            
166
14
	pub const fn deposit(items: u32, bytes: u32) -> Balance {
167
14
		items as Balance * 1 * UNIT * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
168
14
	}
169
}
170

            
171
/// Maximum PoV size we support right now.
172
// Reference: https://github.com/polkadot-fellows/runtimes/pull/553
173
pub const MAX_POV_SIZE: u32 = 10 * 1024 * 1024;
174

            
175
/// Maximum weight per block
176
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
177
	WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
178
	MAX_POV_SIZE as u64,
179
);
180

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

            
193
	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
194
	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
195

            
196
	impl_opaque_keys! {
197
		pub struct SessionKeys {
198
			pub nimbus: AuthorInherent,
199
			pub vrf: session_keys_primitives::VrfSessionKey,
200
		}
201
	}
202
}
203

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

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

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

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

            
255
parameter_types! {
256
	pub const Version: RuntimeVersion = VERSION;
257
	/// TODO: this is left here so that `impl_runtime_apis_plus_common` will find the same type for
258
	/// `BlockWeights` in all runtimes. It can probably be removed once the custom
259
	/// `RuntimeBlockWeights` has been pushed to each runtime.
260
	pub BlockWeights: frame_system::limits::BlockWeights = RuntimeBlockWeights::get();
261
	/// We allow for 5 MB blocks.
262
	pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
263
		::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
264
}
265

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

            
317
impl pallet_utility::Config for Runtime {
318
	type RuntimeEvent = RuntimeEvent;
319
	type RuntimeCall = RuntimeCall;
320
	type PalletsOrigin = OriginCaller;
321
	type WeightInfo = moonbase_weights::pallet_utility::WeightInfo<Runtime>;
322
}
323

            
324
impl pallet_timestamp::Config for Runtime {
325
	/// A timestamp: milliseconds since the unix epoch.
326
	type Moment = u64;
327
	type OnTimestampSet = ();
328
	type MinimumPeriod = ConstU64<{ RELAY_CHAIN_SLOT_DURATION_MILLIS as u64 / 2 }>;
329
	type WeightInfo = moonbase_weights::pallet_timestamp::WeightInfo<Runtime>;
330
}
331

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

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

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

            
361
pub struct LengthToFee;
362
impl WeightToFeePolynomial for LengthToFee {
363
	type Balance = Balance;
364

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

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

            
399
impl pallet_sudo::Config for Runtime {
400
	type RuntimeCall = RuntimeCall;
401
	type RuntimeEvent = RuntimeEvent;
402
	type WeightInfo = moonbase_weights::pallet_sudo::WeightInfo<Runtime>;
403
}
404

            
405
impl pallet_evm_chain_id::Config for Runtime {}
406

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

            
413
/// Approximate ratio of the amount of Weight per Gas.
414
/// u64 works for approximations because Weight is a very small unit compared to gas.
415
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
416

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

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

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

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

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

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

            
514
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
515

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

            
542
	type WeightInfo = moonbase_weights::pallet_evm::WeightInfo<Runtime>;
543
	type CreateOriginFilter = ();
544
	type CreateInnerOriginFilter = ();
545
}
546

            
547
parameter_types! {
548
	pub MaxServiceWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
549
	pub const NoPreimagePostponement: Option<u32> = Some(10);
550
}
551

            
552
impl pallet_scheduler::Config for Runtime {
553
	type RuntimeEvent = RuntimeEvent;
554
	type RuntimeOrigin = RuntimeOrigin;
555
	type PalletsOrigin = OriginCaller;
556
	type RuntimeCall = RuntimeCall;
557
	type MaximumWeight = MaxServiceWeight;
558
	type ScheduleOrigin = EnsureRoot<AccountId>;
559
	type MaxScheduledPerBlock = ConstU32<50>;
560
	type WeightInfo = moonbase_weights::pallet_scheduler::WeightInfo<Runtime>;
561
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
562
	type Preimages = Preimage;
563
	type BlockNumberProvider = System;
564
}
565

            
566
parameter_types! {
567
	pub const PreimageBaseDeposit: Balance = 5 * currency::UNIT * currency::SUPPLY_FACTOR ;
568
	pub const PreimageByteDeposit: Balance = currency::STORAGE_BYTE_FEE;
569
	pub const PreimageHoldReason: RuntimeHoldReason =
570
		RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
571
}
572

            
573
impl pallet_preimage::Config for Runtime {
574
	type WeightInfo = moonbase_weights::pallet_preimage::WeightInfo<Runtime>;
575
	type RuntimeEvent = RuntimeEvent;
576
	type Currency = Balances;
577
	type ManagerOrigin = EnsureRoot<AccountId>;
578
	type Consideration = HoldConsideration<
579
		AccountId,
580
		Balances,
581
		PreimageHoldReason,
582
		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
583
	>;
584
}
585

            
586
parameter_types! {
587
	pub const ProposalBond: Permill = Permill::from_percent(5);
588
	pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
589
	pub TreasuryAccount: AccountId = Treasury::account_id();
590
	pub const MaxSpendBalance: crate::Balance = crate::Balance::max_value();
591
}
592

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

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

            
623
parameter_types! {
624
	pub const MaxSubAccounts: u32 = 100;
625
	pub const MaxAdditionalFields: u32 = 100;
626
	pub const MaxRegistrars: u32 = 20;
627
	pub const PendingUsernameExpiration: u32 = 7 * DAYS;
628
	pub const MaxSuffixLength: u32 = 7;
629
	pub const MaxUsernameLength: u32 = 32;
630
}
631

            
632
type IdentityForceOrigin =
633
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
634
type IdentityRegistrarOrigin =
635
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
636

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

            
663
pub struct TransactionConverter;
664

            
665
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
666
21
	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
667
21
		UncheckedExtrinsic::new_bare(
668
21
			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
669
21
		)
670
21
	}
671
}
672

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

            
687
parameter_types! {
688
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
689
}
690

            
691
impl pallet_ethereum::Config for Runtime {
692
	type RuntimeEvent = RuntimeEvent;
693
	type StateRoot =
694
		pallet_ethereum::IntermediateStateRoot<<Runtime as frame_system::Config>::Version>;
695
	type PostLogContent = PostBlockAndTxnHashes;
696
	type ExtraDataLength = ConstU32<30>;
697
}
698

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

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

            
727
parameter_types! {
728
	// Reserved weight is 1/4 of MAXIMUM_BLOCK_WEIGHT
729
	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
730
	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
731
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
732
}
733

            
734
/// Relay chain slot duration, in milliseconds.
735
const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
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
	RELAY_CHAIN_SLOT_DURATION_MILLIS,
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 = ConsensusHook;
760
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
761
	type WeightInfo = moonbase_weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
762
	type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
763
}
764

            
765
impl parachain_info::Config for Runtime {}
766

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

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

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

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

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

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

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

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

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

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

            
902
impl pallet_async_backing::Config for Runtime {
903
	type AllowMultipleBlocksPerSlot = ConstBool<true>;
904
	type GetAndVerifySlot = pallet_async_backing::RelaySlot;
905
	type SlotDuration = ConstU64<MILLISECS_PER_BLOCK>;
906
	type ExpectedBlockTime = ConstU64<MILLISECS_PER_BLOCK>;
907
}
908

            
909
parameter_types! {
910
	pub const InitializationPayment: Perbill = Perbill::from_percent(30);
911
	pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100);
912
	pub const SignatureNetworkIdentifier:  &'static [u8] = b"moonbase-";
913

            
914
}
915

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

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

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

            
980
impl Default for ProxyType {
981
	fn default() -> Self {
982
		Self::Any
983
	}
984
}
985

            
986
fn is_governance_precompile(precompile_name: &precompiles::PrecompileName) -> bool {
987
	matches!(
988
		precompile_name,
989
		PrecompileName::TreasuryCouncilInstance
990
			| PrecompileName::ReferendaPrecompile
991
			| PrecompileName::ConvictionVotingPrecompile
992
			| PrecompileName::PreimagePrecompile
993
			| PrecompileName::OpenTechCommitteeInstance,
994
	)
995
}
996

            
997
// Be careful: Each time this filter is modified, the substrate filter must also be modified
998
// consistently.
999
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
	fn is_evm_proxy_call_allowed(
		&self,
		call: &pallet_evm_precompile_proxy::EvmSubCall,
		recipient_has_code: bool,
		gas: u64,
	) -> precompile_utils::EvmResult<bool> {
		Ok(match self {
			ProxyType::Any => {
				match PrecompileName::from_address(call.to.0) {
					// Any precompile that can execute a subcall should be forbidden here,
					// to ensure that unauthorized smart contract can't be called
					// indirectly.
					// To be safe, we only allow the precompiles we need.
					Some(
						PrecompileName::AuthorMappingPrecompile
						| PrecompileName::ParachainStakingPrecompile,
					) => true,
					Some(ref precompile) if is_governance_precompile(precompile) => true,
					// All non-whitelisted precompiles are forbidden
					Some(_) => false,
					// Allow evm transfer to "simple" account (no code nor precompile)
					// For the moment, no smart contract other than precompiles is allowed.
					// In the future, we may create a dynamic whitelist to authorize some audited
					// smart contracts through governance.
					None => {
						// If the address is not recognized, allow only evm transfer to "simple"
						// accounts (no code nor precompile).
						// Note: Checking the presence of the code is not enough because some
						// precompiles have no code.
						!recipient_has_code
							&& !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
								call.to.0, gas,
							)?
					}
				}
			}
			ProxyType::NonTransfer => {
				call.value == U256::zero()
					&& match PrecompileName::from_address(call.to.0) {
						Some(
							PrecompileName::AuthorMappingPrecompile
							| PrecompileName::ParachainStakingPrecompile,
						) => true,
						Some(ref precompile) if is_governance_precompile(precompile) => true,
						_ => false,
					}
			}
			ProxyType::Governance => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(ref precompile) if is_governance_precompile(precompile)
					)
			}
			ProxyType::Staking => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(
							PrecompileName::AuthorMappingPrecompile
								| PrecompileName::ParachainStakingPrecompile
						)
					)
			}
			// The proxy precompile does not contain method cancel_proxy
			ProxyType::CancelProxy => false,
			ProxyType::Balances => {
				// Allow only "simple" accounts as recipient (no code nor precompile).
				// Note: Checking the presence of the code is not enough because some precompiles
				// have no code.
				!recipient_has_code
					&& !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
						call.to.0, gas,
					)?
			}
			ProxyType::AuthorMapping => {
				call.value == U256::zero()
					&& matches!(
						PrecompileName::from_address(call.to.0),
						Some(PrecompileName::AuthorMappingPrecompile)
					)
			}
			// There is no identity precompile
			ProxyType::IdentityJudgement => false,
		})
	}
}
// Be careful: Each time this filter is modified, the EVM filter must also be modified consistently.
impl InstanceFilter<RuntimeCall> for ProxyType {
	fn filter(&self, c: &RuntimeCall) -> bool {
		match self {
			ProxyType::Any => true,
			ProxyType::NonTransfer => match c {
				RuntimeCall::Identity(
					pallet_identity::Call::add_sub { .. } | pallet_identity::Call::set_subs { .. },
				) => false,
				call => {
					matches!(
						call,
						RuntimeCall::System(..)
							| RuntimeCall::ParachainSystem(..)
							| RuntimeCall::Timestamp(..)
							| RuntimeCall::ParachainStaking(..)
							| RuntimeCall::Referenda(..)
							| RuntimeCall::Preimage(..)
							| RuntimeCall::ConvictionVoting(..)
							| RuntimeCall::TreasuryCouncilCollective(..)
							| RuntimeCall::OpenTechCommitteeCollective(..)
							| RuntimeCall::Utility(..)
							| RuntimeCall::Proxy(..)
							| RuntimeCall::Identity(..)
							| RuntimeCall::AuthorMapping(..)
							| RuntimeCall::CrowdloanRewards(
								pallet_crowdloan_rewards::Call::claim { .. }
							)
					)
				}
			},
			ProxyType::Governance => matches!(
				c,
				RuntimeCall::Referenda(..)
					| RuntimeCall::Preimage(..)
					| RuntimeCall::ConvictionVoting(..)
					| RuntimeCall::TreasuryCouncilCollective(..)
					| RuntimeCall::OpenTechCommitteeCollective(..)
					| RuntimeCall::Utility(..)
			),
			ProxyType::Staking => matches!(
				c,
				RuntimeCall::ParachainStaking(..)
					| RuntimeCall::Utility(..)
					| RuntimeCall::AuthorMapping(..)
					| RuntimeCall::MoonbeamOrbiters(..)
			),
			ProxyType::CancelProxy => matches!(
				c,
				RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
			),
			ProxyType::Balances => {
				matches!(c, RuntimeCall::Balances(..) | RuntimeCall::Utility(..))
			}
			ProxyType::AuthorMapping => matches!(c, RuntimeCall::AuthorMapping(..)),
			ProxyType::IdentityJudgement => matches!(
				c,
				RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
					| RuntimeCall::Utility(..)
			),
		}
	}
	fn is_superset(&self, o: &Self) -> bool {
		match (self, o) {
			(x, y) if x == y => true,
			(ProxyType::Any, _) => true,
			(_, ProxyType::Any) => false,
			_ => false,
		}
	}
}
impl pallet_proxy::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeCall = RuntimeCall;
	type Currency = Balances;
	type ProxyType = ProxyType;
	// One storage item; key size 32, value size 8
	type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
	// Additional storage item size of 21 bytes (20 bytes AccountId + 1 byte sizeof(ProxyType)).
	type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 21) }>;
	type MaxProxies = ConstU32<32>;
	type WeightInfo = moonbase_weights::pallet_proxy::WeightInfo<Runtime>;
	type MaxPending = ConstU32<32>;
	type CallHasher = BlakeTwo256;
	type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
	// Additional storage item size of 56 bytes:
	// - 20 bytes AccountId
	// - 32 bytes Hasher (Blake2256)
	// - 4 bytes BlockNumber (u32)
	type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 56) }>;
	type BlockNumberProvider = System;
}
pub type ForeignAssetMigratorOrigin = EitherOfDiverse<
	EnsureRoot<AccountId>,
	EitherOfDiverse<
		pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
		EitherOf<
			governance::custom_origins::GeneralAdmin,
			governance::custom_origins::FastGeneralAdmin,
		>,
	>,
>;
impl pallet_moonbeam_lazy_migrations::Config for Runtime {
	type WeightInfo = moonbase_weights::pallet_moonbeam_lazy_migrations::WeightInfo<Runtime>;
}
/// Maintenance mode Call filter
pub struct MaintenanceFilter;
impl Contains<RuntimeCall> for MaintenanceFilter {
	fn contains(c: &RuntimeCall) -> bool {
		match c {
			RuntimeCall::Balances(_) => false,
			RuntimeCall::CrowdloanRewards(_) => false,
			RuntimeCall::Ethereum(_) => false,
			RuntimeCall::EVM(_) => false,
			RuntimeCall::Identity(_) => false,
			RuntimeCall::ParachainStaking(_) => false,
			RuntimeCall::MoonbeamOrbiters(_) => false,
			RuntimeCall::PolkadotXcm(_) => false,
			RuntimeCall::Treasury(_) => false,
			RuntimeCall::XcmTransactor(_) => false,
			RuntimeCall::EthereumXcm(_) => false,
			_ => true,
		}
	}
}
/// Normal Call Filter
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
357
	fn contains(c: &RuntimeCall) -> bool {
357
		match c {
			// 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
7
			RuntimeCall::EVM(_) => false,
350
			_ => true,
		}
357
	}
}
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;
	type BlockNumberProvider = System;
}
parameter_types! {
	pub OrbiterReserveIdentifier: [u8; 4] = [b'o', b'r', b'b', b'i'];
}
type AddCollatorOrigin =
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
type DelCollatorOrigin =
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
impl pallet_moonbeam_orbiters::Config for Runtime {
	type 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 = moonbase_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 = moonbase_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 = moonbase_weights::pallet_multisig::WeightInfo<Runtime>;
	type BlockNumberProvider = System;
}
impl pallet_relay_storage_roots::Config for Runtime {
	type MaxStorageRoots = ConstU32<30>;
	type RelaychainStateProvider = cumulus_pallet_parachain_system::RelaychainDataProvider<Self>;
	type WeightInfo = moonbase_weights::pallet_relay_storage_roots::WeightInfo<Runtime>;
}
#[cfg(feature = "runtime-benchmarks")]
impl pallet_precompile_benchmarks::Config for Runtime {
	type WeightInfo = moonbase_weights::pallet_precompile_benchmarks::WeightInfo<Runtime>;
}
impl pallet_parameters::Config for Runtime {
	type AdminOrigin = EnsureRoot<AccountId>;
	type RuntimeEvent = RuntimeEvent;
	type RuntimeParameters = RuntimeParameters;
	type WeightInfo = moonbase_weights::pallet_parameters::WeightInfo<Runtime>;
}
impl cumulus_pallet_weight_reclaim::Config for Runtime {
	type WeightInfo = moonbase_weights::cumulus_pallet_weight_reclaim::WeightInfo<Runtime>;
}
impl pallet_migrations::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	#[cfg(not(feature = "runtime-benchmarks"))]
	type Migrations = migrations::MultiBlockMigrationList<Runtime>;
	#[cfg(feature = "runtime-benchmarks")]
	type Migrations = pallet_migrations::mock_helpers::MockedMigrations;
	type CursorMaxLen = ConstU32<65_536>;
	type IdentifierMaxLen = ConstU32<256>;
	type MigrationStatusHandler = ();
	type FailedMigrationHandler = MaintenanceMode;
	type MaxServiceWeight = MaxServiceWeight;
	type WeightInfo = weights::pallet_migrations::WeightInfo<Runtime>;
}
11097
construct_runtime! {
11097
	pub enum Runtime
11097
	{
11097
		System: frame_system::{Pallet, Call, Storage, Config<T>, Event<T>} = 0,
11097
		Utility: pallet_utility::{Pallet, Call, Event} = 1,
11097
		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2,
11097
		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 3,
11097
		Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>} = 4,
11097
		// Previously 5: pallet_randomness_collective_flip
11097
		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>} = 6,
11097
		TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Config<T>, Event<T>} = 7,
11097
		ParachainInfo: parachain_info::{Pallet, Storage, Config<T>} = 8,
11097
		EthereumChainId: pallet_evm_chain_id::{Pallet, Storage, Config<T>} = 9,
11097
		EVM: pallet_evm::{Pallet, Config<T>, Call, Storage, Event<T>} = 10,
11097
		Ethereum: pallet_ethereum::{Pallet, Call, Storage, Event, Origin, Config<T>} = 11,
11097
		ParachainStaking: pallet_parachain_staking::{Pallet, Call, Storage, Event<T>, Config<T>} = 12,
11097
		Scheduler: pallet_scheduler::{Pallet, Storage, Event<T>, Call} = 13,
11097
		// Previously 14: pallet_democracy::{Pallet, Storage, Config<T>, Event<T>, Call} = 14,
11097
		// Previously 15: CouncilCollective: pallet_collective::<Instance1>
11097
		// Previously 16: TechCommitteeCollective: pallet_collective::<Instance2>
11097
		Treasury: pallet_treasury::{Pallet, Storage, Config<T>, Event<T>, Call} = 17,
11097
		AuthorInherent: pallet_author_inherent::{Pallet, Call, Storage, Inherent} = 18,
11097
		AuthorFilter: pallet_author_slot_filter::{Pallet, Call, Storage, Event, Config<T>} = 19,
11097
		CrowdloanRewards: pallet_crowdloan_rewards::{Pallet, Call, Config<T>, Storage, Event<T>} = 20,
11097
		AuthorMapping: pallet_author_mapping::{Pallet, Call, Config<T>, Storage, Event<T>} = 21,
11097
		Proxy: pallet_proxy::{Pallet, Call, Storage, Event<T>} = 22,
11097
		MaintenanceMode: pallet_maintenance_mode::{Pallet, Call, Config<T>, Storage, Event} = 23,
11097
		Identity: pallet_identity::{Pallet, Call, Storage, Event<T>} = 24,
11097
		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 25,
11097
		CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 26,
11097
		// Previously 27: DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>},
11097
		PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 28,
11097
		// [Removed] Assets: pallet_assets::{Pallet, Call, Storage, Event<T>} = 29,
11097
		// Previously 30: XTokens
11097
		// Previously 31: AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event<T>}
11097
		// [Removed] Migrations: pallet_migrations::{Pallet, Storage, Config<T>, Event<T>} = 32,
11097
		XcmTransactor: pallet_xcm_transactor::{Pallet, Call, Config<T>, Storage, Event<T>} = 33,
11097
		ProxyGenesisCompanion: pallet_proxy_genesis_companion::{Pallet, Config<T>} = 34,
11097
		// Previously 35: BaseFee
11097
		// Previously 36: pallet_assets::<Instance1>
11097
		MoonbeamOrbiters: pallet_moonbeam_orbiters::{Pallet, Call, Storage, Event<T>, Config<T>} = 37,
11097
		EthereumXcm: pallet_ethereum_xcm::{Pallet, Call, Storage, Origin, Event<T>} = 38,
11097
		Randomness: pallet_randomness::{Pallet, Call, Storage, Event<T>, Inherent} = 39,
11097
		TreasuryCouncilCollective:
11097
			pallet_collective::<Instance3>::{Pallet, Call, Storage, Event<T>, Origin<T>, Config<T>} = 40,
11097
		ConvictionVoting: pallet_conviction_voting::{Pallet, Call, Storage, Event<T>} = 41,
11097
		Referenda: pallet_referenda::{Pallet, Call, Storage, Event<T>} = 42,
11097
		Origins: governance::custom_origins::{Origin} = 43,
11097
		Preimage: pallet_preimage::{Pallet, Call, Storage, Event<T>, HoldReason} = 44,
11097
		Whitelist: pallet_whitelist::{Pallet, Call, Storage, Event<T>} = 45,
11097
		OpenTechCommitteeCollective:
11097
			pallet_collective::<Instance4>::{Pallet, Call, Storage, Event<T>, Origin<T>, Config<T>} = 46,
11097
		RootTesting: pallet_root_testing::{Pallet, Call, Storage, Event<T>} = 47,
11097
		Erc20XcmBridge: pallet_erc20_xcm_bridge::{Pallet} = 48,
11097
		Multisig: pallet_multisig::{Pallet, Call, Storage, Event<T>} = 49,
11097
		AsyncBacking: pallet_async_backing::{Pallet, Storage} = 50,
11097
		MoonbeamLazyMigrations: pallet_moonbeam_lazy_migrations::{Pallet, Call, Storage} = 51,
11097
		RelayStorageRoots: pallet_relay_storage_roots::{Pallet, Storage} = 52,
11097

            
11097
		#[cfg(feature = "runtime-benchmarks")]
11097
		PrecompileBenchmarks: pallet_precompile_benchmarks::{Pallet} = 53,
11097

            
11097
		MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 54,
11097
		EmergencyParaXcm: pallet_emergency_para_xcm::{Pallet, Call, Storage, Event} = 55,
11097
		EvmForeignAssets: pallet_moonbeam_foreign_assets::{Pallet, Call, Storage, Event<T>} = 56,
11097
		Parameters: pallet_parameters = 57,
11097
		XcmWeightTrader: pallet_xcm_weight_trader::{Pallet, Call, Storage, Event<T>} = 58,
11097
		MultiBlockMigrations: pallet_migrations = 117,
11097
		WeightReclaim: cumulus_pallet_weight_reclaim = 118,
11097
	}
663000
}
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The TransactionExtension to the basic transaction logic.
pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
	Runtime,
	(
		frame_system::CheckNonZeroSender<Runtime>,
		frame_system::CheckSpecVersion<Runtime>,
		frame_system::CheckTxVersion<Runtime>,
		frame_system::CheckGenesis<Runtime>,
		frame_system::CheckEra<Runtime>,
		frame_system::CheckNonce<Runtime>,
		frame_system::CheckWeight<Runtime>,
		pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
		frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
	),
>;
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic =
	fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension, H160>;
/// Executive: handles dispatch to the various pallets.
pub type Executive = frame_executive::Executive<
	Runtime,
	Block,
	frame_system::ChainContext<Runtime>,
	Runtime,
	AllPalletsWithSystem,
>;
#[cfg(feature = "runtime-benchmarks")]
use moonbeam_runtime_common::benchmarking::BenchmarkHelper;
use moonbeam_runtime_common::deal_with_fees::{
	DealWithEthereumBaseFees, DealWithEthereumPriorityFees, DealWithSubstrateFeesAndTip,
};
#[cfg(feature = "runtime-benchmarks")]
mod benches {
	frame_support::parameter_types! {
		pub const MaxBalance: crate::Balance = crate::Balance::max_value();
	}
	frame_benchmarking::define_benchmarks!(
		[frame_system, SystemBench::<Runtime>]
		[frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
		[pallet_utility, Utility]
		[pallet_timestamp, Timestamp]
		[pallet_balances, Balances]
		[pallet_sudo, Sudo]
		[pallet_evm, EVM]
		[pallet_parachain_staking, ParachainStaking]
		[pallet_scheduler, Scheduler]
		[pallet_treasury, Treasury]
		[pallet_author_inherent, AuthorInherent]
		[pallet_author_slot_filter, AuthorFilter]
		[pallet_crowdloan_rewards, CrowdloanRewards]
		[pallet_author_mapping, AuthorMapping]
		[pallet_proxy, Proxy]
		[pallet_transaction_payment, PalletTransactionPaymentBenchmark::<Runtime>]
		[pallet_identity, Identity]
		[cumulus_pallet_parachain_system, ParachainSystem]
		[cumulus_pallet_xcmp_queue, XcmpQueue]
		[pallet_message_queue, MessageQueue]
		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
		[pallet_xcm_transactor, XcmTransactor]
		[pallet_moonbeam_foreign_assets, EvmForeignAssets]
		[pallet_moonbeam_orbiters, MoonbeamOrbiters]
		[pallet_randomness, Randomness]
		[pallet_conviction_voting, ConvictionVoting]
		[pallet_referenda, Referenda]
		[pallet_preimage, Preimage]
		[pallet_whitelist, Whitelist]
		[pallet_multisig, Multisig]
		[pallet_migrations, MultiBlockMigrations]
		// Currently there are no extrinsics to benchmark for the Lazy Migrations pallet
		// [pallet_moonbeam_lazy_migrations, MoonbeamLazyMigrations]
		[pallet_relay_storage_roots, RelayStorageRoots]
		[pallet_precompile_benchmarks, PrecompileBenchmarks]
		[pallet_parameters, Parameters]
		[pallet_xcm_weight_trader, XcmWeightTrader]
		[pallet_collective, TreasuryCouncilCollective]
		[pallet_collective, OpenTechCommitteeCollective]
		[cumulus_pallet_weight_reclaim, WeightReclaim]
	);
}
// All of our runtimes share most of their Runtime API implementations.
// We use a macro to implement this common part and add runtime-specific additional implementations.
// This macro expands to :
// ```
// impl_runtime_apis! {
//     // All impl blocks shared between all runtimes.
//
//     // Specific impls provided to the `impl_runtime_apis_plus_common!` macro.
// }
// ```
moonbeam_runtime_common::impl_runtime_apis_plus_common!(
	{
		impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
7
			fn validate_transaction(
7
				source: TransactionSource,
7
				xt: <Block as BlockT>::Extrinsic,
7
				block_hash: <Block as BlockT>::Hash,
7
			) -> TransactionValidity {
7
				// Filtered calls should not enter the tx pool as they'll fail if inserted.
7
				// If this call is not allowed, we return early.
7
				if !<Runtime as frame_system::Config>::BaseCallFilter::contains(&xt.0.function) {
7
					return InvalidTransaction::Call.into();
				}
				// This runtime uses Substrate's pallet transaction payment. This
				// makes the chain feel like a standard Substrate chain when submitting
				// frame transactions and using Substrate ecosystem tools. It has the downside that
				// transaction are not prioritized by gas_price. The following code reprioritizes
				// transactions to overcome this.
				//
				// A more elegant, ethereum-first solution is
				// a pallet that replaces pallet transaction payment, and allows users
				// to directly specify a gas price rather than computing an effective one.
				// #HopefullySomeday
				// First we pass the transactions to the standard FRAME executive. This calculates all the
				// necessary tags, longevity and other properties that we will leave unchanged.
				// This also assigns some priority that we don't care about and will overwrite next.
				let mut intermediate_valid = Executive::validate_transaction(source, xt.clone(), block_hash)?;
				let dispatch_info = xt.get_dispatch_info();
				// If this is a pallet ethereum transaction, then its priority is already set
				// according to effective priority fee from pallet ethereum. If it is any other kind of
				// transaction, we modify its priority. The goal is to arrive at a similar metric used
				// by pallet ethereum, which means we derive a fee-per-gas from the txn's tip and
				// weight.
				Ok(match &xt.0.function {
					RuntimeCall::Ethereum(transact { .. }) => intermediate_valid,
					_ if dispatch_info.class != DispatchClass::Normal => intermediate_valid,
					_ => {
						let tip = match &xt.0.preamble {
							Preamble::Bare(_) => 0,
							Preamble::Signed(_, _, signed_extra) => {
								// Yuck, this depends on the index of ChargeTransactionPayment in TxExtension
								let charge_transaction_payment = &signed_extra.0.7;
								charge_transaction_payment.tip()
							},
							Preamble::General(_, _) => 0,
						};
						let effective_gas =
							<Runtime as pallet_evm::Config>::GasWeightMapping::weight_to_gas(
								dispatch_info.total_weight()
							);
						let tip_per_gas = if effective_gas > 0 {
							tip.saturating_div(effective_gas as u128)
						} else {
							0
						};
						// Overwrite the original prioritization with this ethereum one
						intermediate_valid.priority = tip_per_gas as u64;
						intermediate_valid
					}
				})
7
			}
		}
		impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
			fn can_build_upon(
				included_hash: <Block as BlockT>::Hash,
				slot: async_backing_primitives::Slot,
			) -> bool {
				ConsensusHook::can_build_upon(included_hash, slot)
			}
		}
	}
	// Benchmark customizations
	{}
);
// Nimbus's Executive wrapper allows relay validators to verify the seal digest
cumulus_pallet_parachain_system::register_validate_block!(
	Runtime = Runtime,
	BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
);
moonbeam_runtime_common::impl_self_contained_call!();
// Shorthand for a Get field of a pallet Config.
#[macro_export]
macro_rules! get {
	($pallet:ident, $name:ident, $type:ty) => {
		<<$crate::Runtime as $pallet::Config>::$name as $crate::Get<$type>>::get()
	};
}
#[cfg(test)]
mod tests {
	use super::{currency::*, *};
	#[test]
	// Helps us to identify a Pallet Call in case it exceeds the 1kb limit.
	// Hint: this should be a rare case. If that happens, one or more of the dispatchable arguments
	// need to be Boxed.
1
	fn call_max_size() {
		const CALL_ALIGN: u32 = 1024;
1
		assert!(std::mem::size_of::<pallet_evm_chain_id::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(std::mem::size_of::<pallet_evm::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(std::mem::size_of::<pallet_ethereum::Call<Runtime>>() <= CALL_ALIGN as usize);
1
		assert!(
1
			std::mem::size_of::<pallet_parachain_staking::Call<Runtime>>() <= CALL_ALIGN as usize
1
		);
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!(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));
		// 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
	}
}