1
// Copyright 2021 Parity Technologies (UK) Ltd.
2
// This file is part of Polkadot.
3

            
4
// Polkadot 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
// Polkadot 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 Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Parachain runtime mock.
18

            
19
use frame_support::{
20
	construct_runtime,
21
	dispatch::GetDispatchInfo,
22
	ensure, parameter_types,
23
	traits::{
24
		fungible::NativeOrWithId, AsEnsureOriginWithArg, ConstU32, EitherOf, Everything, Get,
25
		InstanceFilter, Nothing, PalletInfoAccess,
26
	},
27
	weights::Weight,
28
	PalletId,
29
};
30
pub use moonbeam_runtime::xcm_config::AssetType;
31

            
32
use frame_system::{pallet_prelude::BlockNumberFor, EnsureNever, EnsureRoot};
33
use moonbeam_runtime_common::{
34
	impl_asset_conversion::AssetRateConverter, impl_multiasset_paymaster::MultiAssetPaymaster,
35
	xcm_origins::AllowSiblingParachains,
36
};
37
use pallet_moonbeam_foreign_assets::{MapSuccessToGovernance, MapSuccessToXcm};
38
use pallet_xcm::{migration::v1::VersionUncheckedMigrateToV1, EnsureXcm};
39
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
40
use sp_core::{H160, H256};
41
use sp_runtime::{
42
	traits::{BlakeTwo256, Hash, IdentityLookup, MaybeEquivalence, Zero},
43
	Permill,
44
};
45
use sp_std::{
46
	convert::{From, Into, TryFrom},
47
	prelude::*,
48
};
49
use xcm::{latest::prelude::*, Version as XcmVersion, VersionedXcm};
50

            
51
use cumulus_primitives_core::relay_chain::HrmpChannelId;
52
use pallet_ethereum::PostLogContent;
53
use polkadot_core_primitives::BlockNumber as RelayBlockNumber;
54
use polkadot_parachain::primitives::{Id as ParaId, Sibling};
55
use xcm::latest::{
56
	Error as XcmError, ExecuteXcm,
57
	Junction::{PalletInstance, Parachain},
58
	Location, NetworkId, Outcome, Xcm,
59
};
60
use xcm_builder::{
61
	AccountKey20Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
62
	AllowTopLevelPaidExecutionFrom, Case, ConvertedConcreteId, EnsureXcmOrigin, FixedWeightBounds,
63
	FungibleAdapter as XcmCurrencyAdapter, FungiblesAdapter, IsConcrete, NoChecking,
64
	ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
65
	SiblingParachainConvertsVia, SignedAccountKey20AsNative, SovereignSignedViaLocation,
66
	TakeWeightCredit, WithComputedOrigin,
67
};
68
use xcm_executor::{traits::JustTry, Config, XcmExecutor};
69

            
70
#[cfg(feature = "runtime-benchmarks")]
71
use moonbeam_runtime_common::benchmarking::BenchmarkHelper as ArgumentsBenchmarkHelper;
72
use scale_info::TypeInfo;
73
use xcm_simulator::{
74
	DmpMessageHandlerT as DmpMessageHandler, XcmpMessageFormat,
75
	XcmpMessageHandlerT as XcmpMessageHandler,
76
};
77

            
78
pub type AccountId = moonbeam_core_primitives::AccountId;
79
pub type Balance = u128;
80
pub type AssetId = u128;
81
pub type BlockNumber = BlockNumberFor<Runtime>;
82

            
83
parameter_types! {
84
	pub const BlockHashCount: u32 = 250;
85
}
86

            
87
impl frame_system::Config for Runtime {
88
	type RuntimeOrigin = RuntimeOrigin;
89
	type RuntimeCall = RuntimeCall;
90
	type RuntimeTask = RuntimeTask;
91
	type Nonce = u64;
92
	type Block = Block;
93
	type Hash = H256;
94
	type Hashing = ::sp_runtime::traits::BlakeTwo256;
95
	type AccountId = AccountId;
96
	type Lookup = IdentityLookup<AccountId>;
97
	type RuntimeEvent = RuntimeEvent;
98
	type BlockHashCount = BlockHashCount;
99
	type BlockWeights = ();
100
	type BlockLength = ();
101
	type Version = ();
102
	type PalletInfo = PalletInfo;
103
	type AccountData = pallet_balances::AccountData<Balance>;
104
	type OnNewAccount = ();
105
	type OnKilledAccount = ();
106
	type DbWeight = ();
107
	type BaseCallFilter = Everything;
108
	type SystemWeightInfo = ();
109
	type SS58Prefix = ();
110
	type OnSetCode = ();
111
	type MaxConsumers = frame_support::traits::ConstU32<16>;
112
	type SingleBlockMigrations = ();
113
	type MultiBlockMigrator = ();
114
	type PreInherents = ();
115
	type PostInherents = ();
116
	type PostTransactions = ();
117
	type ExtensionsWeightInfo = ();
118
}
119

            
120
parameter_types! {
121
	pub ExistentialDeposit: Balance = 0;
122
	pub const MaxLocks: u32 = 50;
123
	pub const MaxReserves: u32 = 50;
124
}
125

            
126
impl pallet_balances::Config for Runtime {
127
	type MaxLocks = MaxLocks;
128
	type Balance = Balance;
129
	type RuntimeEvent = RuntimeEvent;
130
	type DustRemoval = ();
131
	type ExistentialDeposit = ExistentialDeposit;
132
	type AccountStore = System;
133
	type WeightInfo = ();
134
	type MaxReserves = MaxReserves;
135
	type ReserveIdentifier = [u8; 8];
136
	type RuntimeHoldReason = ();
137
	type FreezeIdentifier = ();
138
	type MaxFreezes = ();
139
	type RuntimeFreezeReason = ();
140
	type DoneSlashHandler = ();
141
}
142

            
143
pub type ForeignAssetInstance = ();
144

            
145
// Required for runtime benchmarks
146
pallet_assets::runtime_benchmarks_enabled! {
147
	pub struct BenchmarkHelper;
148
	impl<AssetIdParameter> pallet_assets::BenchmarkHelper<AssetIdParameter> for BenchmarkHelper
149
	where
150
		AssetIdParameter: From<u128>,
151
	{
152
		fn create_asset_id_parameter(id: u32) -> AssetIdParameter {
153
			(id as u128).into()
154
		}
155
	}
156
}
157

            
158
parameter_types! {
159
	pub const AssetDeposit: Balance = 1; // Does not really matter as this will be only called by root
160
	pub const ApprovalDeposit: Balance = 0;
161
	pub const AssetsStringLimit: u32 = 50;
162
	pub const MetadataDepositBase: Balance = 0;
163
	pub const MetadataDepositPerByte: Balance = 0;
164
	pub const AssetAccountDeposit: Balance = 0;
165
}
166

            
167
impl pallet_assets::Config<ForeignAssetInstance> for Runtime {
168
	type RuntimeEvent = RuntimeEvent;
169
	type Balance = Balance;
170
	type AssetId = AssetId;
171
	type Currency = Balances;
172
	type ForceOrigin = EnsureRoot<AccountId>;
173
	type AssetDeposit = AssetDeposit;
174
	type MetadataDepositBase = MetadataDepositBase;
175
	type MetadataDepositPerByte = MetadataDepositPerByte;
176
	type ApprovalDeposit = ApprovalDeposit;
177
	type StringLimit = AssetsStringLimit;
178
	type Freezer = ();
179
	type Extra = ();
180
	type AssetAccountDeposit = AssetAccountDeposit;
181
	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
182
	type RemoveItemsLimit = ConstU32<656>;
183
	type AssetIdParameter = AssetId;
184
	type CreateOrigin = AsEnsureOriginWithArg<EnsureNever<AccountId>>;
185
	type CallbackHandle = ();
186
	pallet_assets::runtime_benchmarks_enabled! {
187
		type BenchmarkHelper = BenchmarkHelper;
188
	}
189
}
190

            
191
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
192
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
193
/// `Transact` in order to determine the dispatch Origin.
194
pub type LocationToAccountId = (
195
	// The parent (Relay-chain) origin converts to the default `AccountId`.
196
	ParentIsPreset<AccountId>,
197
	// Sibling parachain origins convert to AccountId via the `ParaId::into`.
198
	SiblingParachainConvertsVia<Sibling, AccountId>,
199
	AccountKey20Aliases<RelayNetwork, AccountId>,
200
	// Generate remote accounts according to polkadot standards
201
	xcm_builder::HashedDescription<
202
		AccountId,
203
		xcm_builder::DescribeFamily<xcm_builder::DescribeAllTerminal>,
204
	>,
205
);
206

            
207
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
208
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
209
/// biases the kind of local `Origin` it will become.
210
pub type XcmOriginToTransactDispatchOrigin = (
211
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
212
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
213
	// foreign chains who want to have a local sovereign account on this chain which they control.
214
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
215
	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
216
	// recognised.
217
	RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
218
	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
219
	// recognised.
220
	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
221
	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
222
	// transaction from the Root origin.
223
	ParentAsSuperuser<RuntimeOrigin>,
224
	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
225
	pallet_xcm::XcmPassthrough<RuntimeOrigin>,
226
	SignedAccountKey20AsNative<RelayNetwork, RuntimeOrigin>,
227
);
228

            
229
parameter_types! {
230
	pub const UnitWeightCost: Weight = Weight::from_parts(1u64, 1u64);
231
	pub MaxInstructions: u32 = 100;
232
}
233

            
234
// Instructing how incoming xcm assets will be handled
235
pub type ForeignFungiblesTransactor = FungiblesAdapter<
236
	// Use this fungibles implementation:
237
	Assets,
238
	// Use this currency when it is a fungible asset matching the given location or name:
239
	(
240
		ConvertedConcreteId<
241
			AssetId,
242
			Balance,
243
			xcm_primitives::AsAssetType<AssetId, AssetType, AssetManager>,
244
			JustTry,
245
		>,
246
	),
247
	// Do a simple punn to convert an AccountId32 Location into a native chain account ID:
248
	LocationToAccountId,
249
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
250
	AccountId,
251
	// We dont allow teleports.
252
	NoChecking,
253
	// We dont track any teleports
254
	(),
255
>;
256

            
257
pub type LocalAssetTransactor = XcmCurrencyAdapter<
258
	// Use this currency:
259
	Balances,
260
	// Use this currency when it is a fungible asset matching any of the locations in
261
	// SelfReserveRepresentations
262
	IsConcrete<SelfReserve>,
263
	// We can convert the Locations with our converter above:
264
	LocationToAccountId,
265
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
266
	AccountId,
267
	// We dont allow teleport
268
	(),
269
>;
270

            
271
// We use all transactors
272
pub type AssetTransactors = (LocalAssetTransactor, ForeignFungiblesTransactor);
273
pub type XcmRouter = super::ParachainXcmRouter<MsgQueue>;
274

            
275
pub type XcmBarrier = (
276
	// Weight that is paid for may be consumed.
277
	TakeWeightCredit,
278
	// Expected responses are OK.
279
	AllowKnownQueryResponses<PolkadotXcm>,
280
	WithComputedOrigin<
281
		(
282
			// If the message is one that immediately attemps to pay for execution, then allow it.
283
			AllowTopLevelPaidExecutionFrom<Everything>,
284
			// Subscriptions for version tracking are OK.
285
			AllowSubscriptionsFrom<Everything>,
286
		),
287
		UniversalLocation,
288
		ConstU32<8>,
289
	>,
290
);
291

            
292
parameter_types! {
293
	/// Xcm fees will go to the treasury account
294
	pub XcmFeesAccount: AccountId = Treasury::account_id();
295
	/// Parachain token units per second of execution
296
	pub ParaTokensPerSecond: u128 = WEIGHT_REF_TIME_PER_SECOND as u128;
297
}
298

            
299
pub struct WeightToFee;
300
impl sp_weights::WeightToFee for WeightToFee {
301
	type Balance = Balance;
302

            
303
46
	fn weight_to_fee(weight: &Weight) -> Self::Balance {
304
		use sp_runtime::SaturatedConversion as _;
305
46
		Self::Balance::saturated_from(weight.ref_time())
306
46
			.saturating_mul(ParaTokensPerSecond::get())
307
46
			.saturating_div(frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND as u128)
308
46
	}
309
}
310

            
311
parameter_types! {
312
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
313
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
314
	pub UniversalLocation: InteriorLocation =
315
		[GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into();
316
	pub SelfReserve: Location = Location {
317
		parents:0,
318
		interior: [
319
			PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
320
		].into()
321
	};
322
	pub const MaxAssetsIntoHolding: u32 = 64;
323

            
324
	pub AssetHubLocation: Location = Location::new(1, [Parachain(1000)]);
325
	pub RelayLocationFilter: AssetFilter = Wild(AllOf {
326
		fun: WildFungible,
327
		id: xcm::prelude::AssetId(Location::parent()),
328
	});
329

            
330
	pub RelayChainNativeAssetFromAssetHub: (AssetFilter, Location) = (
331
		RelayLocationFilter::get(),
332
		AssetHubLocation::get()
333
	);
334
}
335

            
336
use frame_system::RawOrigin;
337
use sp_runtime::traits::PostDispatchInfoOf;
338
use sp_runtime::DispatchErrorWithPostInfo;
339
use xcm_executor::traits::CallDispatcher;
340
moonbeam_runtime_common::impl_moonbeam_xcm_call!();
341

            
342
type Reserves = (
343
	// Relaychain (DOT) from Asset Hub
344
	Case<RelayChainNativeAssetFromAssetHub>,
345
	// Assets which the reserve is the same as the origin.
346
	xcm_primitives::MultiNativeAsset<
347
		xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>,
348
	>,
349
);
350

            
351
pub struct XcmConfig;
352
impl Config for XcmConfig {
353
	type RuntimeCall = RuntimeCall;
354
	type XcmSender = XcmRouter;
355
	type AssetTransactor = AssetTransactors;
356
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
357
	type IsReserve = Reserves;
358
	type IsTeleporter = ();
359
	type UniversalLocation = UniversalLocation;
360
	type Barrier = XcmBarrier;
361
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
362
	type Trader = pallet_xcm_weight_trader::Trader<Runtime>;
363
	type ResponseHandler = PolkadotXcm;
364
	type SubscriptionService = PolkadotXcm;
365
	type AssetTrap = PolkadotXcm;
366
	type AssetClaims = PolkadotXcm;
367
	type CallDispatcher = MoonbeamCall;
368
	type AssetLocker = ();
369
	type AssetExchanger = ();
370
	type PalletInstancesInfo = ();
371
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
372
	type FeeManager = ();
373
	type MessageExporter = ();
374
	type UniversalAliases = Nothing;
375
	type SafeCallFilter = Everything;
376
	type Aliasers = Nothing;
377
	type TransactionalProcessor = ();
378
	type HrmpNewChannelOpenRequestHandler = ();
379
	type HrmpChannelAcceptedHandler = ();
380
	type HrmpChannelClosingHandler = ();
381
	type XcmRecorder = PolkadotXcm;
382
}
383

            
384
impl cumulus_pallet_xcm::Config for Runtime {
385
	type RuntimeEvent = RuntimeEvent;
386
	type XcmExecutor = XcmExecutor<XcmConfig>;
387
}
388

            
389
// Our currencyId. We distinguish for now between SelfReserve, and Others, defined by their Id.
390
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
391
pub enum CurrencyId {
392
	SelfReserve,
393
	ForeignAsset(AssetId),
394
}
395

            
396
// How to convert from CurrencyId to Location
397
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
398
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
399
	for CurrencyIdToLocation<AssetXConverter>
400
where
401
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
402
{
403
23
	fn convert(currency: CurrencyId) -> Option<Location> {
404
23
		match currency {
405
			CurrencyId::SelfReserve => {
406
6
				let multi: Location = SelfReserve::get();
407
6
				Some(multi)
408
			}
409
17
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
410
		}
411
23
	}
412
}
413

            
414
parameter_types! {
415
	pub const BaseXcmWeight: Weight = Weight::from_parts(100u64, 100u64);
416
	pub const MaxAssetsForTransfer: usize = 2;
417
	pub SelfLocation: Location = Location::here();
418
	pub SelfLocationAbsolute: Location = Location {
419
		parents:1,
420
		interior: [
421
			Parachain(MsgQueue::parachain_id().into())
422
		].into()
423
	};
424
}
425

            
426
parameter_types! {
427
	pub const ProposalBond: Permill = Permill::from_percent(5);
428
	pub const ProposalBondMinimum: Balance = 0;
429
	pub const SpendPeriod: u32 = 0;
430
	pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
431
	pub const MaxApprovals: u32 = 100;
432
	pub TreasuryAccount: AccountId = Treasury::account_id();
433
}
434

            
435
impl pallet_treasury::Config for Runtime {
436
	type PalletId = TreasuryId;
437
	type Currency = Balances;
438
	type RejectOrigin = EnsureRoot<AccountId>;
439
	type RuntimeEvent = RuntimeEvent;
440
	type SpendPeriod = SpendPeriod;
441
	type Burn = ();
442
	type BurnDestination = ();
443
	type MaxApprovals = MaxApprovals;
444
	type WeightInfo = ();
445
	type SpendFunds = ();
446
	type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>; // Same as Polkadot
447
	type AssetKind = NativeOrWithId<AssetId>;
448
	type Beneficiary = AccountId;
449
	type BeneficiaryLookup = IdentityLookup<AccountId>;
450
	type Paymaster = MultiAssetPaymaster<Runtime, TreasuryAccount, Balances>;
451
	type BalanceConverter = AssetRateConverter<Runtime, Balances>;
452
	type PayoutPeriod = ConstU32<0>;
453
	#[cfg(feature = "runtime-benchmarks")]
454
	type BenchmarkHelper = ArgumentsBenchmarkHelper;
455
	type BlockNumberProvider = System;
456
}
457

            
458
#[frame_support::pallet]
459
pub mod mock_msg_queue {
460
	use super::*;
461
	use frame_support::pallet_prelude::*;
462

            
463
	#[pallet::config]
464
	pub trait Config: frame_system::Config {
465
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
466
		type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
467
	}
468

            
469
	#[pallet::call]
470
	impl<T: Config> Pallet<T> {}
471

            
472
1
	#[pallet::pallet]
473
	pub struct Pallet<T>(_);
474

            
475
1092
	#[pallet::storage]
476
	#[pallet::getter(fn parachain_id)]
477
	pub(super) type ParachainId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
478

            
479
	impl<T: Config> Get<ParaId> for Pallet<T> {
480
43
		fn get() -> ParaId {
481
43
			Self::parachain_id()
482
43
		}
483
	}
484

            
485
	pub type MessageId = [u8; 32];
486

            
487
	#[pallet::event]
488
47
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
489
	pub enum Event<T: Config> {
490
		// XCMP
491
		/// Some XCM was executed OK.
492
		Success(Option<T::Hash>),
493
		/// Some XCM failed.
494
		Fail(Option<T::Hash>, XcmError),
495
		/// Bad XCM version used.
496
		BadVersion(Option<T::Hash>),
497
		/// Bad XCM format used.
498
		BadFormat(Option<T::Hash>),
499

            
500
		// DMP
501
		/// Downward message is invalid XCM.
502
		InvalidFormat(MessageId),
503
		/// Downward message is unsupported version of XCM.
504
		UnsupportedVersion(MessageId),
505
4
		/// Downward message executed with the given outcome.
506
		ExecutedDownward(MessageId, Outcome),
507
	}
508

            
509
	impl<T: Config> Pallet<T> {
510
234
		pub fn set_para_id(para_id: ParaId) {
511
234
			ParachainId::<T>::put(para_id);
512
234
		}
513

            
514
27
		fn handle_xcmp_message(
515
27
			sender: ParaId,
516
27
			_sent_at: RelayBlockNumber,
517
27
			xcm: VersionedXcm<T::RuntimeCall>,
518
27
			max_weight: Weight,
519
27
		) -> Result<Weight, XcmError> {
520
27
			let hash = Encode::using_encoded(&xcm, T::Hashing::hash);
521
27
			let (result, event) = match Xcm::<T::RuntimeCall>::try_from(xcm) {
522
27
				Ok(xcm) => {
523
27
					let location = Location::new(1, [Parachain(sender.into())]);
524
27
					let mut id = [0u8; 32];
525
27
					id.copy_from_slice(hash.as_ref());
526
27
					match T::XcmExecutor::prepare_and_execute(
527
27
						location,
528
27
						xcm,
529
27
						&mut id,
530
27
						max_weight,
531
27
						Weight::zero(),
532
27
					) {
533
						Outcome::Error { error } => {
534
							(Err(error.clone()), Event::Fail(Some(hash), error))
535
						}
536
27
						Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))),
537
						// As far as the caller is concerned, this was dispatched without error, so
538
						// we just report the weight used.
539
						Outcome::Incomplete { used, error } => {
540
							(Ok(used), Event::Fail(Some(hash), error))
541
						}
542
					}
543
				}
544
				Err(()) => (
545
					Err(XcmError::UnhandledXcmVersion),
546
					Event::BadVersion(Some(hash)),
547
				),
548
			};
549
27
			Self::deposit_event(event);
550
27
			result
551
27
		}
552
	}
553

            
554
	impl<T: Config> XcmpMessageHandler for Pallet<T> {
555
27
		fn handle_xcmp_messages<'a, I: Iterator<Item = (ParaId, RelayBlockNumber, &'a [u8])>>(
556
27
			iter: I,
557
27
			max_weight: Weight,
558
27
		) -> Weight {
559
54
			for (sender, sent_at, data) in iter {
560
27
				let mut data_ref = data;
561
27
				let _ = XcmpMessageFormat::decode(&mut data_ref)
562
27
					.expect("Simulator encodes with versioned xcm format; qed");
563
27

            
564
27
				let mut remaining_fragments = &data_ref[..];
565
54
				while !remaining_fragments.is_empty() {
566
27
					if let Ok(xcm) =
567
27
						VersionedXcm::<T::RuntimeCall>::decode(&mut remaining_fragments)
568
27
					{
569
27
						let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight);
570
27
					} else {
571
						debug_assert!(false, "Invalid incoming XCMP message data");
572
					}
573
				}
574
			}
575
27
			max_weight
576
27
		}
577
	}
578

            
579
	impl<T: Config> DmpMessageHandler for Pallet<T> {
580
20
		fn handle_dmp_messages(
581
20
			iter: impl Iterator<Item = (RelayBlockNumber, Vec<u8>)>,
582
20
			limit: Weight,
583
20
		) -> Weight {
584
20
			for (_i, (_sent_at, data)) in iter.enumerate() {
585
20
				let mut id = sp_io::hashing::blake2_256(&data[..]);
586
20
				let maybe_msg = VersionedXcm::<T::RuntimeCall>::decode(&mut &data[..])
587
20
					.map(Xcm::<T::RuntimeCall>::try_from);
588
20
				match maybe_msg {
589
					Err(_) => {
590
						Self::deposit_event(Event::InvalidFormat(id));
591
					}
592
					Ok(Err(())) => {
593
						Self::deposit_event(Event::UnsupportedVersion(id));
594
					}
595
20
					Ok(Ok(x)) => {
596
20
						let outcome = T::XcmExecutor::prepare_and_execute(
597
20
							Parent,
598
20
							x,
599
20
							&mut id,
600
20
							limit,
601
20
							Weight::zero(),
602
20
						);
603
20

            
604
20
						Self::deposit_event(Event::ExecutedDownward(id, outcome));
605
20
					}
606
				}
607
			}
608
20
			limit
609
20
		}
610
	}
611
}
612

            
613
// Pallet to provide the version, used to test runtime upgrade version changes
614
#[frame_support::pallet]
615
pub mod mock_version_changer {
616
	use super::*;
617
	use frame_support::pallet_prelude::*;
618

            
619
	#[pallet::config]
620
	pub trait Config: frame_system::Config {
621
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
622
	}
623

            
624
	#[pallet::call]
625
	impl<T: Config> Pallet<T> {}
626

            
627
1
	#[pallet::pallet]
628
	pub struct Pallet<T>(_);
629

            
630
10
	#[pallet::storage]
631
	#[pallet::getter(fn current_version)]
632
	pub(super) type CurrentVersion<T: Config> = StorageValue<_, XcmVersion, ValueQuery>;
633

            
634
	impl<T: Config> Get<XcmVersion> for Pallet<T> {
635
2
		fn get() -> XcmVersion {
636
2
			Self::current_version()
637
2
		}
638
	}
639

            
640
	#[pallet::event]
641
2
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
642
	pub enum Event<T: Config> {
643
		// XCMP
644
2
		/// Some XCM was executed OK.
645
		VersionChanged(XcmVersion),
646
	}
647

            
648
	impl<T: Config> Pallet<T> {
649
2
		pub fn set_version(version: XcmVersion) {
650
2
			CurrentVersion::<T>::put(version);
651
2
			Self::deposit_event(Event::VersionChanged(version));
652
2
		}
653
	}
654
}
655

            
656
impl mock_msg_queue::Config for Runtime {
657
	type RuntimeEvent = RuntimeEvent;
658
	type XcmExecutor = XcmExecutor<XcmConfig>;
659
}
660

            
661
impl mock_version_changer::Config for Runtime {
662
	type RuntimeEvent = RuntimeEvent;
663
}
664

            
665
pub type LocalOriginToLocation =
666
	xcm_primitives::SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
667

            
668
parameter_types! {
669
	pub MatcherLocation: Location = Location::here();
670
}
671

            
672
impl pallet_xcm::Config for Runtime {
673
	type RuntimeEvent = RuntimeEvent;
674
	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
675
	type XcmRouter = XcmRouter;
676
	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
677
	type XcmExecuteFilter = frame_support::traits::Nothing;
678
	type XcmExecutor = XcmExecutor<XcmConfig>;
679
	// Do not allow teleports
680
	type XcmTeleportFilter = Nothing;
681
	type XcmReserveTransferFilter = Everything;
682
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
683
	type UniversalLocation = UniversalLocation;
684
	type RuntimeOrigin = RuntimeOrigin;
685
	type RuntimeCall = RuntimeCall;
686
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
687
	// We use a custom one to test runtime ugprades
688
	type AdvertisedXcmVersion = XcmVersioner;
689
	type Currency = Balances;
690
	type CurrencyMatcher = IsConcrete<MatcherLocation>;
691
	type TrustedLockers = ();
692
	type SovereignAccountOf = ();
693
	type MaxLockers = ConstU32<8>;
694
	type WeightInfo = pallet_xcm::TestWeightInfo;
695
	type MaxRemoteLockConsumers = ConstU32<0>;
696
	type RemoteLockConsumerIdentifier = ();
697
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
698
}
699

            
700
// We instruct how to register the Assets
701
// In this case, we tell it to Create an Asset in pallet-assets
702
pub struct AssetRegistrar;
703
use frame_support::pallet_prelude::DispatchResult;
704
impl pallet_asset_manager::AssetRegistrar<Runtime> for AssetRegistrar {
705
33
	fn create_foreign_asset(
706
33
		asset: AssetId,
707
33
		min_balance: Balance,
708
33
		metadata: AssetMetadata,
709
33
		is_sufficient: bool,
710
33
	) -> DispatchResult {
711
33
		Assets::force_create(
712
33
			RuntimeOrigin::root(),
713
33
			asset,
714
33
			AssetManager::account_id(),
715
33
			is_sufficient,
716
33
			min_balance,
717
33
		)?;
718

            
719
33
		Assets::force_set_metadata(
720
33
			RuntimeOrigin::root(),
721
33
			asset,
722
33
			metadata.name,
723
33
			metadata.symbol,
724
33
			metadata.decimals,
725
33
			false,
726
33
		)
727
33
	}
728

            
729
	fn destroy_foreign_asset(asset: AssetId) -> DispatchResult {
730
		// Mark the asset as destroying
731
		Assets::start_destroy(RuntimeOrigin::root(), asset.into())?;
732

            
733
		Ok(())
734
	}
735

            
736
	fn destroy_asset_dispatch_info_weight(asset: AssetId) -> Weight {
737
		RuntimeCall::Assets(
738
			pallet_assets::Call::<Runtime, ForeignAssetInstance>::start_destroy {
739
				id: asset.into(),
740
			},
741
		)
742
		.get_dispatch_info()
743
		.total_weight()
744
	}
745
}
746

            
747
#[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
748
pub struct AssetMetadata {
749
	pub name: Vec<u8>,
750
	pub symbol: Vec<u8>,
751
	pub decimals: u8,
752
}
753

            
754
impl pallet_asset_manager::Config for Runtime {
755
	type RuntimeEvent = RuntimeEvent;
756
	type Balance = Balance;
757
	type AssetId = AssetId;
758
	type AssetRegistrarMetadata = AssetMetadata;
759
	type ForeignAssetType = AssetType;
760
	type AssetRegistrar = AssetRegistrar;
761
	type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
762
	type WeightInfo = ();
763
}
764

            
765
pub struct AccountIdToH160;
766
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
767
	fn convert(account_id: AccountId) -> H160 {
768
		account_id.into()
769
	}
770
}
771

            
772
pub struct EvmForeignAssetIdFilter;
773
impl frame_support::traits::Contains<AssetId> for EvmForeignAssetIdFilter {
774
	fn contains(asset_id: &AssetId) -> bool {
775
		use xcm_primitives::AssetTypeGetter as _;
776
		// We should return true only if the AssetId doesn't exist in AssetManager
777
		AssetManager::get_asset_type(*asset_id).is_none()
778
	}
779
}
780

            
781
pub type ForeignAssetManagerOrigin = EitherOf<
782
	MapSuccessToXcm<EnsureXcm<AllowSiblingParachains>>,
783
	MapSuccessToGovernance<EnsureRoot<AccountId>>,
784
>;
785

            
786
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
787

            
788
parameter_types! {
789
	pub ForeignAssetCreationDeposit: u128 = 100 * currency::GLMR;
790
}
791

            
792
impl pallet_moonbeam_foreign_assets::Config for Runtime {
793
	type AccountIdToH160 = AccountIdToH160;
794
	type AssetIdFilter = EvmForeignAssetIdFilter;
795
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
796
	type ConvertLocation =
797
		SiblingParachainConvertsVia<polkadot_parachain::primitives::Sibling, AccountId>;
798
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
799
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
800
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
801
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
802
	type OnForeignAssetCreated = ();
803
	type MaxForeignAssets = ConstU32<256>;
804
	type RuntimeEvent = RuntimeEvent;
805
	type WeightInfo = ();
806
	type XcmLocationToH160 = LocationToH160;
807
	type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit;
808
	type Balance = Balance;
809
	type Currency = Balances;
810
}
811

            
812
// 1 DOT should be enough
813
parameter_types! {
814
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
815
}
816

            
817
impl pallet_xcm_transactor::Config for Runtime {
818
	type RuntimeEvent = RuntimeEvent;
819
	type Balance = Balance;
820
	type Transactor = MockTransactors;
821
	type DerivativeAddressRegistrationOrigin = EnsureRoot<AccountId>;
822
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
823
	type CurrencyId = CurrencyId;
824
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
825
	type CurrencyIdToLocation = CurrencyIdToLocation<(
826
		EvmForeignAssets,
827
		AsAssetType<moonbeam_core_primitives::AssetId, AssetType, AssetManager>,
828
	)>;
829
	type SelfLocation = SelfLocation;
830
	type Weigher = xcm_builder::FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
831
	type UniversalLocation = UniversalLocation;
832
	type XcmSender = XcmRouter;
833
	type BaseXcmWeight = BaseXcmWeight;
834
	type AssetTransactor = AssetTransactors;
835
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
836
	type WeightInfo = ();
837
	type HrmpManipulatorOrigin = EnsureRoot<AccountId>;
838
	type HrmpOpenOrigin = EnsureRoot<AccountId>;
839
	type MaxHrmpFee = xcm_builder::Case<MaxHrmpRelayFee>;
840
}
841

            
842
parameter_types! {
843
	pub RelayLocation: Location = Location::parent();
844
}
845

            
846
impl pallet_xcm_weight_trader::Config for Runtime {
847
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
848
	type AddSupportedAssetOrigin = EnsureRoot<AccountId>;
849
	type AssetLocationFilter = Everything;
850
	type AssetTransactor = AssetTransactors;
851
	type Balance = Balance;
852
	type EditSupportedAssetOrigin = EnsureRoot<AccountId>;
853
	type NativeLocation = SelfReserve;
854
	type PauseSupportedAssetOrigin = EnsureRoot<AccountId>;
855
	type RemoveSupportedAssetOrigin = EnsureRoot<AccountId>;
856
	type RuntimeEvent = RuntimeEvent;
857
	type ResumeSupportedAssetOrigin = EnsureRoot<AccountId>;
858
	type WeightInfo = ();
859
	type WeightToFee = WeightToFee;
860
	type XcmFeesAccount = XcmFeesAccount;
861
	#[cfg(feature = "runtime-benchmarks")]
862
	type NotFilteredLocation = RelayLocation;
863
}
864

            
865
parameter_types! {
866
	pub const MinimumPeriod: u64 = 1000;
867
}
868
impl pallet_timestamp::Config for Runtime {
869
	type Moment = u64;
870
	type OnTimestampSet = ();
871
	type MinimumPeriod = MinimumPeriod;
872
	type WeightInfo = ();
873
}
874

            
875
parameter_types! {
876
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
877
	pub WeightPerGas: Weight = Weight::from_parts(1, 0);
878
	pub GasLimitPovSizeRatio: u64 = {
879
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
880
		block_gas_limit.saturating_div(MAX_POV_SIZE as u64)
881
	};
882
	pub GasLimitStorageGrowthRatio: u64 =
883
		BlockGasLimit::get().min(u64::MAX.into()).low_u64().saturating_div(BLOCK_STORAGE_LIMIT);
884
}
885

            
886
impl pallet_evm::Config for Runtime {
887
	type FeeCalculator = ();
888
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
889
	type WeightPerGas = WeightPerGas;
890

            
891
	type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
892
	type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
893

            
894
	type AddressMapping = pallet_evm::IdentityAddressMapping;
895
	type Currency = Balances;
896
	type Runner = pallet_evm::runner::stack::Runner<Self>;
897

            
898
	type RuntimeEvent = RuntimeEvent;
899
	type PrecompilesType = ();
900
	type PrecompilesValue = ();
901
	type ChainId = ();
902
	type BlockGasLimit = BlockGasLimit;
903
	type OnChargeTransaction = ();
904
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
905
	type FindAuthor = ();
906
	type OnCreate = ();
907
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
908
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
909
	type Timestamp = Timestamp;
910
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
911
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
912
}
913

            
914
#[allow(dead_code)]
915
pub struct NormalFilter;
916

            
917
impl frame_support::traits::Contains<RuntimeCall> for NormalFilter {
918
	fn contains(c: &RuntimeCall) -> bool {
919
		match c {
920
			_ => true,
921
		}
922
	}
923
}
924

            
925
// We need to use the encoding from the relay mock runtime
926
#[derive(Encode, Decode)]
927
pub enum RelayCall {
928
	#[codec(index = 5u8)]
929
	// the index should match the position of the module in `construct_runtime!`
930
	Utility(UtilityCall),
931
	#[codec(index = 6u8)]
932
	// the index should match the position of the module in `construct_runtime!`
933
	Hrmp(HrmpCall),
934
}
935

            
936
#[derive(Encode, Decode)]
937
pub enum UtilityCall {
938
	#[codec(index = 1u8)]
939
	AsDerivative(u16),
940
}
941

            
942
// HRMP call encoding, needed for xcm transactor pallet
943
#[derive(Encode, Decode)]
944
pub enum HrmpCall {
945
	#[codec(index = 0u8)]
946
	InitOpenChannel(ParaId, u32, u32),
947
	#[codec(index = 1u8)]
948
	AcceptOpenChannel(ParaId),
949
	#[codec(index = 2u8)]
950
	CloseChannel(HrmpChannelId),
951
	#[codec(index = 6u8)]
952
	CancelOpenRequest(HrmpChannelId, u32),
953
}
954

            
955
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
956
pub enum MockTransactors {
957
	Relay,
958
}
959

            
960
impl xcm_primitives::XcmTransact for MockTransactors {
961
3
	fn destination(self) -> Location {
962
3
		match self {
963
3
			MockTransactors::Relay => Location::parent(),
964
3
		}
965
3
	}
966
}
967

            
968
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
969
7
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
970
7
		match self {
971
7
			MockTransactors::Relay => match call {
972
7
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
973
7
					let mut call =
974
7
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
975
7
					call.append(&mut b.clone());
976
7
					call
977
7
				}
978
7
			},
979
7
		}
980
7
	}
981
}
982

            
983
#[allow(dead_code)]
984
pub struct MockHrmpEncoder;
985

            
986
impl xcm_primitives::HrmpEncodeCall for MockHrmpEncoder {
987
	fn hrmp_encode_call(
988
		call: xcm_primitives::HrmpAvailableCalls,
989
	) -> Result<Vec<u8>, xcm::latest::Error> {
990
		match call {
991
			xcm_primitives::HrmpAvailableCalls::InitOpenChannel(a, b, c) => Ok(RelayCall::Hrmp(
992
				HrmpCall::InitOpenChannel(a.clone(), b.clone(), c.clone()),
993
			)
994
			.encode()),
995
			xcm_primitives::HrmpAvailableCalls::AcceptOpenChannel(a) => {
996
				Ok(RelayCall::Hrmp(HrmpCall::AcceptOpenChannel(a.clone())).encode())
997
			}
998
			xcm_primitives::HrmpAvailableCalls::CloseChannel(a) => {
999
				Ok(RelayCall::Hrmp(HrmpCall::CloseChannel(a.clone())).encode())
			}
			xcm_primitives::HrmpAvailableCalls::CancelOpenRequest(a, b) => {
				Ok(RelayCall::Hrmp(HrmpCall::CancelOpenRequest(a.clone(), b.clone())).encode())
			}
		}
	}
}
parameter_types! {
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
}
impl pallet_ethereum::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type StateRoot =
		pallet_ethereum::IntermediateStateRoot<<Runtime as frame_system::Config>::Version>;
	type PostLogContent = PostBlockAndTxnHashes;
	type ExtraDataLength = ConstU32<30>;
}
parameter_types! {
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 0);
}
#[derive(
	Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
)]
pub enum ProxyType {
	NotAllowed = 0,
1
	Any = 1,
}
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
impl InstanceFilter<RuntimeCall> for ProxyType {
	fn filter(&self, _c: &RuntimeCall) -> bool {
		match self {
			ProxyType::NotAllowed => false,
			ProxyType::Any => true,
		}
	}
	fn is_superset(&self, _o: &Self) -> bool {
		false
	}
}
impl Default for ProxyType {
	fn default() -> Self {
		Self::NotAllowed
	}
}
parameter_types! {
	pub const ProxyCost: u64 = 1;
}
impl pallet_proxy::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeCall = RuntimeCall;
	type Currency = Balances;
	type ProxyType = ProxyType;
	type ProxyDepositBase = ProxyCost;
	type ProxyDepositFactor = ProxyCost;
	type MaxProxies = ConstU32<32>;
	type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
	type MaxPending = ConstU32<32>;
	type CallHasher = BlakeTwo256;
	type AnnouncementDepositBase = ProxyCost;
	type AnnouncementDepositFactor = ProxyCost;
}
pub struct EthereumXcmEnsureProxy;
impl xcm_primitives::EnsureProxy<AccountId> for EthereumXcmEnsureProxy {
2
	fn ensure_ok(delegator: AccountId, delegatee: AccountId) -> Result<(), &'static str> {
		// The EVM implicitely contains an Any proxy, so we only allow for "Any" proxies
1
		let def: pallet_proxy::ProxyDefinition<AccountId, ProxyType, BlockNumber> =
2
			pallet_proxy::Pallet::<Runtime>::find_proxy(
2
				&delegator,
2
				&delegatee,
2
				Some(ProxyType::Any),
2
			)
2
			.map_err(|_| "proxy error: expected `ProxyType::Any`")?;
		// We only allow to use it for delay zero proxies, as the call will iMmediatly be executed
1
		ensure!(def.delay.is_zero(), "proxy delay is Non-zero`");
1
		Ok(())
2
	}
}
impl pallet_ethereum_xcm::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
	type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
	type ReservedXcmpWeight = ReservedXcmpWeight;
	type EnsureProxy = EthereumXcmEnsureProxy;
	type ControllerOrigin = EnsureRoot<AccountId>;
	type ForceOrigin = EnsureRoot<AccountId>;
}
type Block = frame_system::mocking::MockBlockU32<Runtime>;
9378
construct_runtime!(
1758
	pub enum Runtime	{
1758
		System: frame_system,
1758
		Balances: pallet_balances,
1758
		MsgQueue: mock_msg_queue,
1758
		XcmVersioner: mock_version_changer,
1758

            
1758
		PolkadotXcm: pallet_xcm,
1758
		Assets: pallet_assets,
1758
		CumulusXcm: cumulus_pallet_xcm,
1758
		AssetManager: pallet_asset_manager,
1758
		XcmTransactor: pallet_xcm_transactor,
1758
		XcmWeightTrader: pallet_xcm_weight_trader,
1758
		Treasury: pallet_treasury,
1758
		Proxy: pallet_proxy,
1758

            
1758
		Timestamp: pallet_timestamp,
1758
		EVM: pallet_evm,
1758
		Ethereum: pallet_ethereum,
1758
		EthereumXcm: pallet_ethereum_xcm,
1758
		EvmForeignAssets: pallet_moonbeam_foreign_assets,
1758
	}
9557
);
4
pub(crate) fn para_events() -> Vec<RuntimeEvent> {
4
	System::events()
4
		.into_iter()
44
		.map(|r| r.event)
44
		.filter_map(|e| Some(e))
4
		.collect::<Vec<_>>()
4
}
use frame_support::traits::{OnFinalize, OnInitialize, UncheckedOnRuntimeUpgrade};
use moonbeam_runtime::{currency, xcm_config::LocationToH160, BLOCK_STORAGE_LIMIT, MAX_POV_SIZE};
use pallet_evm::FrameSystemAccountProvider;
use sp_weights::constants::WEIGHT_REF_TIME_PER_SECOND;
use xcm_primitives::AsAssetType;
1
pub(crate) fn on_runtime_upgrade() {
1
	VersionUncheckedMigrateToV1::<Runtime>::on_runtime_upgrade();
1
}
1
pub(crate) fn para_roll_to(n: BlockNumber) {
2
	while System::block_number() < n {
1
		PolkadotXcm::on_finalize(System::block_number());
1
		Balances::on_finalize(System::block_number());
1
		System::on_finalize(System::block_number());
1
		System::set_block_number(System::block_number() + 1);
1
		System::on_initialize(System::block_number());
1
		Balances::on_initialize(System::block_number());
1
		PolkadotXcm::on_initialize(System::block_number());
1
	}
1
}