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, ensure, parameter_types,
21
	traits::{
22
		fungible::NativeOrWithId, ConstU32, EitherOf, Everything, Get, InstanceFilter, Nothing,
23
		PalletInfoAccess,
24
	},
25
	weights::Weight,
26
	PalletId,
27
};
28
pub use moonbeam_runtime::xcm_config::AssetType;
29

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

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

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

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

            
81
parameter_types! {
82
	pub const BlockHashCount: u32 = 250;
83
}
84

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

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

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

            
141
parameter_types! {
142
	pub const AssetDeposit: Balance = 10; // Does not really matter as this will be only called by root
143
	pub const ApprovalDeposit: Balance = 0;
144
	pub const AssetsStringLimit: u32 = 50;
145
	pub const MetadataDepositBase: Balance = 0;
146
	pub const MetadataDepositPerByte: Balance = 0;
147
	pub const AssetAccountDeposit: Balance = 0;
148
}
149

            
150
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
151
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
152
/// `Transact` in order to determine the dispatch Origin.
153
pub type LocationToAccountId = (
154
	// The parent (Relay-chain) origin converts to the default `AccountId`.
155
	ParentIsPreset<AccountId>,
156
	// Sibling parachain origins convert to AccountId via the `ParaId::into`.
157
	SiblingParachainConvertsVia<Sibling, AccountId>,
158
	AccountKey20Aliases<RelayNetwork, AccountId>,
159
	// Generate remote accounts according to polkadot standards
160
	xcm_builder::HashedDescription<
161
		AccountId,
162
		xcm_builder::DescribeFamily<xcm_builder::DescribeAllTerminal>,
163
	>,
164
);
165

            
166
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
167
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
168
/// biases the kind of local `Origin` it will become.
169
pub type XcmOriginToTransactDispatchOrigin = (
170
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
171
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
172
	// foreign chains who want to have a local sovereign account on this chain which they control.
173
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
174
	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
175
	// recognised.
176
	RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
177
	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
178
	// recognised.
179
	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
180
	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
181
	// transaction from the Root origin.
182
	ParentAsSuperuser<RuntimeOrigin>,
183
	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
184
	pallet_xcm::XcmPassthrough<RuntimeOrigin>,
185
	SignedAccountKey20AsNative<RelayNetwork, RuntimeOrigin>,
186
);
187

            
188
parameter_types! {
189
	pub const UnitWeightCost: Weight = Weight::from_parts(1u64, 1u64);
190
	pub MaxInstructions: u32 = 100;
191
}
192

            
193
/// The transactor for our own chain currency.
194
pub type LocalAssetTransactor = FungibleAdapter<
195
	// Use this currency:
196
	Balances,
197
	// Use this currency when it is a fungible asset matching any of the locations in
198
	// SelfReserveRepresentations
199
	IsConcrete<SelfReserve>,
200
	// We can convert the Locations with our converter above:
201
	LocationToAccountId,
202
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
203
	AccountId,
204
	// We dont allow teleport
205
	(),
206
>;
207

            
208
// These will be our transactors
209
// We use both transactors
210
pub type AssetTransactors = (LocalAssetTransactor, EvmForeignAssets);
211
pub type XcmRouter = super::ParachainXcmRouter<MsgQueue>;
212

            
213
pub type XcmBarrier = (
214
	// Weight that is paid for may be consumed.
215
	TakeWeightCredit,
216
	// Expected responses are OK.
217
	AllowKnownQueryResponses<PolkadotXcm>,
218
	WithComputedOrigin<
219
		(
220
			// If the message is one that immediately attemps to pay for execution, then allow it.
221
			AllowTopLevelPaidExecutionFrom<Everything>,
222
			// Subscriptions for version tracking are OK.
223
			AllowSubscriptionsFrom<Everything>,
224
		),
225
		UniversalLocation,
226
		ConstU32<8>,
227
	>,
228
);
229

            
230
parameter_types! {
231
	/// Xcm fees will go to the treasury account
232
	pub XcmFeesAccount: AccountId = Treasury::account_id();
233
	/// Parachain token units per second of execution
234
	pub ParaTokensPerSecond: u128 = WEIGHT_REF_TIME_PER_SECOND as u128;
235
}
236

            
237
pub struct WeightToFee;
238
impl sp_weights::WeightToFee for WeightToFee {
239
	type Balance = Balance;
240

            
241
46
	fn weight_to_fee(weight: &Weight) -> Self::Balance {
242
		use sp_runtime::SaturatedConversion as _;
243
46
		Self::Balance::saturated_from(weight.ref_time())
244
46
			.saturating_mul(ParaTokensPerSecond::get())
245
46
			.saturating_div(frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND as u128)
246
46
	}
247
}
248

            
249
parameter_types! {
250
	pub RelayNetwork: NetworkId = moonbeam_runtime::xcm_config::RelayNetwork::get();
251
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
252
	pub UniversalLocation: InteriorLocation =
253
		[GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into();
254
	pub SelfReserve: Location = Location {
255
		parents:0,
256
		interior: [
257
			PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
258
		].into()
259
	};
260
	pub const MaxAssetsIntoHolding: u32 = 64;
261

            
262
	pub AssetHubLocation: Location = Location::new(1, [Parachain(1000)]);
263
	pub RelayLocationFilter: AssetFilter = Wild(AllOf {
264
		fun: WildFungible,
265
		id: xcm::prelude::AssetId(Location::parent()),
266
	});
267

            
268
	pub RelayChainNativeAssetFromAssetHub: (AssetFilter, Location) = (
269
		RelayLocationFilter::get(),
270
		AssetHubLocation::get()
271
	);
272
}
273

            
274
use frame_system::RawOrigin;
275
use sp_runtime::traits::PostDispatchInfoOf;
276
use sp_runtime::DispatchErrorWithPostInfo;
277
use xcm_executor::traits::CallDispatcher;
278
moonbeam_runtime_common::impl_moonbeam_xcm_call!();
279

            
280
type Reserves = (
281
	// Relaychain (DOT) from Asset Hub
282
	Case<RelayChainNativeAssetFromAssetHub>,
283
	// Assets which the reserve is the same as the origin.
284
	xcm_primitives::MultiNativeAsset<
285
		xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>,
286
	>,
287
);
288

            
289
pub struct XcmConfig;
290
impl Config for XcmConfig {
291
	type RuntimeCall = RuntimeCall;
292
	type XcmSender = XcmRouter;
293
	type AssetTransactor = AssetTransactors;
294
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
295
	type IsReserve = Reserves;
296
	type IsTeleporter = ();
297
	type UniversalLocation = UniversalLocation;
298
	type Barrier = XcmBarrier;
299
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
300
	type Trader = pallet_xcm_weight_trader::Trader<Runtime>;
301
	type ResponseHandler = PolkadotXcm;
302
	type SubscriptionService = PolkadotXcm;
303
	type AssetTrap = PolkadotXcm;
304
	type AssetClaims = PolkadotXcm;
305
	type CallDispatcher = MoonbeamCall;
306
	type AssetLocker = ();
307
	type AssetExchanger = ();
308
	type PalletInstancesInfo = ();
309
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
310
	type FeeManager = ();
311
	type MessageExporter = ();
312
	type UniversalAliases = Nothing;
313
	type SafeCallFilter = Everything;
314
	type Aliasers = Nothing;
315
	type TransactionalProcessor = ();
316
	type HrmpNewChannelOpenRequestHandler = ();
317
	type HrmpChannelAcceptedHandler = ();
318
	type HrmpChannelClosingHandler = ();
319
	type XcmRecorder = PolkadotXcm;
320
	type XcmEventEmitter = ();
321
}
322

            
323
impl cumulus_pallet_xcm::Config for Runtime {
324
	type RuntimeEvent = RuntimeEvent;
325
	type XcmExecutor = XcmExecutor<XcmConfig>;
326
}
327

            
328
// Our currencyId. We distinguish for now between SelfReserve, and Others, defined by their Id.
329
#[derive(
330
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
331
)]
332
pub enum CurrencyId {
333
	SelfReserve,
334
	ForeignAsset(AssetId),
335
}
336

            
337
// How to convert from CurrencyId to Location
338
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
339
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
340
	for CurrencyIdToLocation<AssetXConverter>
341
where
342
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
343
{
344
23
	fn convert(currency: CurrencyId) -> Option<Location> {
345
23
		match currency {
346
			CurrencyId::SelfReserve => {
347
6
				let multi: Location = SelfReserve::get();
348
6
				Some(multi)
349
			}
350
17
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
351
		}
352
23
	}
353
}
354

            
355
parameter_types! {
356
	pub const BaseXcmWeight: Weight = Weight::from_parts(100u64, 100u64);
357
	pub const MaxAssetsForTransfer: usize = 2;
358
	pub SelfLocation: Location = Location::here();
359
	pub SelfLocationAbsolute: Location = Location {
360
		parents:1,
361
		interior: [
362
			Parachain(MsgQueue::parachain_id().into())
363
		].into()
364
	};
365
}
366

            
367
parameter_types! {
368
	pub const ProposalBond: Permill = Permill::from_percent(5);
369
	pub const ProposalBondMinimum: Balance = 0;
370
	pub const SpendPeriod: u32 = 0;
371
	pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
372
	pub const MaxApprovals: u32 = 100;
373
	pub TreasuryAccount: AccountId = Treasury::account_id();
374
}
375

            
376
impl pallet_treasury::Config for Runtime {
377
	type PalletId = TreasuryId;
378
	type Currency = Balances;
379
	type RejectOrigin = EnsureRoot<AccountId>;
380
	type RuntimeEvent = RuntimeEvent;
381
	type SpendPeriod = SpendPeriod;
382
	type Burn = ();
383
	type BurnDestination = ();
384
	type MaxApprovals = MaxApprovals;
385
	type WeightInfo = ();
386
	type SpendFunds = ();
387
	type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>; // Same as Polkadot
388
	type AssetKind = NativeOrWithId<AssetId>;
389
	type Beneficiary = AccountId;
390
	type BeneficiaryLookup = IdentityLookup<AccountId>;
391
	type Paymaster = MultiAssetPaymaster<Runtime, TreasuryAccount, Balances>;
392
	type BalanceConverter = AssetRateConverter<Runtime, Balances>;
393
	type PayoutPeriod = ConstU32<0>;
394
	#[cfg(feature = "runtime-benchmarks")]
395
	type BenchmarkHelper = ArgumentsBenchmarkHelper;
396
	type BlockNumberProvider = System;
397
}
398

            
399
#[frame_support::pallet]
400
pub mod mock_msg_queue {
401
	use super::*;
402
	use frame_support::pallet_prelude::*;
403

            
404
	#[pallet::config]
405
	pub trait Config: frame_system::Config {
406
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
407
		type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
408
	}
409

            
410
	#[pallet::call]
411
	impl<T: Config> Pallet<T> {}
412

            
413
3
	#[pallet::pallet]
414
	pub struct Pallet<T>(_);
415

            
416
1089
	#[pallet::storage]
417
	#[pallet::getter(fn parachain_id)]
418
	pub(super) type ParachainId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
419

            
420
	impl<T: Config> Get<ParaId> for Pallet<T> {
421
43
		fn get() -> ParaId {
422
43
			Self::parachain_id()
423
43
		}
424
	}
425

            
426
	pub type MessageId = [u8; 32];
427

            
428
	#[pallet::event]
429
46
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
430
	pub enum Event<T: Config> {
431
		// XCMP
432
		/// Some XCM was executed OK.
433
		Success(Option<T::Hash>),
434
		/// Some XCM failed.
435
		Fail(Option<T::Hash>, XcmError),
436
		/// Bad XCM version used.
437
		BadVersion(Option<T::Hash>),
438
		/// Bad XCM format used.
439
		BadFormat(Option<T::Hash>),
440

            
441
		// DMP
442
		/// Downward message is invalid XCM.
443
		InvalidFormat(MessageId),
444
		/// Downward message is unsupported version of XCM.
445
		UnsupportedVersion(MessageId),
446
		/// Downward message executed with the given outcome.
447
		ExecutedDownward(MessageId, Outcome),
448
	}
449

            
450
	impl<T: Config> Pallet<T> {
451
234
		pub fn set_para_id(para_id: ParaId) {
452
234
			ParachainId::<T>::put(para_id);
453
234
		}
454

            
455
27
		fn handle_xcmp_message(
456
27
			sender: ParaId,
457
27
			_sent_at: RelayBlockNumber,
458
27
			xcm: VersionedXcm<T::RuntimeCall>,
459
27
			max_weight: Weight,
460
27
		) -> Result<Weight, XcmError> {
461
27
			let hash = Encode::using_encoded(&xcm, T::Hashing::hash);
462
27
			let (result, event) = match Xcm::<T::RuntimeCall>::try_from(xcm) {
463
27
				Ok(xcm) => {
464
27
					let location = Location::new(1, [Parachain(sender.into())]);
465
27
					let mut id = [0u8; 32];
466
27
					id.copy_from_slice(hash.as_ref());
467
27
					match T::XcmExecutor::prepare_and_execute(
468
27
						location,
469
27
						xcm,
470
27
						&mut id,
471
27
						max_weight,
472
27
						Weight::zero(),
473
27
					) {
474
						Outcome::Error { error } => {
475
							(Err(error.clone()), Event::Fail(Some(hash), error))
476
						}
477
27
						Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))),
478
						// As far as the caller is concerned, this was dispatched without error, so
479
						// we just report the weight used.
480
						Outcome::Incomplete { used, error } => {
481
							(Ok(used), Event::Fail(Some(hash), error))
482
						}
483
					}
484
				}
485
				Err(()) => (
486
					Err(XcmError::UnhandledXcmVersion),
487
					Event::BadVersion(Some(hash)),
488
				),
489
			};
490
27
			Self::deposit_event(event);
491
27
			result
492
27
		}
493
	}
494

            
495
	impl<T: Config> XcmpMessageHandler for Pallet<T> {
496
27
		fn handle_xcmp_messages<'a, I: Iterator<Item = (ParaId, RelayBlockNumber, &'a [u8])>>(
497
27
			iter: I,
498
27
			max_weight: Weight,
499
27
		) -> Weight {
500
54
			for (sender, sent_at, data) in iter {
501
27
				let mut data_ref = data;
502
27
				let _ = XcmpMessageFormat::decode(&mut data_ref)
503
27
					.expect("Simulator encodes with versioned xcm format; qed");
504
27

            
505
27
				let mut remaining_fragments = &data_ref[..];
506
54
				while !remaining_fragments.is_empty() {
507
27
					if let Ok(xcm) =
508
27
						VersionedXcm::<T::RuntimeCall>::decode(&mut remaining_fragments)
509
27
					{
510
27
						let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight);
511
27
					} else {
512
						debug_assert!(false, "Invalid incoming XCMP message data");
513
					}
514
				}
515
			}
516
27
			max_weight
517
27
		}
518
	}
519

            
520
	impl<T: Config> DmpMessageHandler for Pallet<T> {
521
19
		fn handle_dmp_messages(
522
19
			iter: impl Iterator<Item = (RelayBlockNumber, Vec<u8>)>,
523
19
			limit: Weight,
524
19
		) -> Weight {
525
19
			for (_i, (_sent_at, data)) in iter.enumerate() {
526
19
				let mut id = sp_io::hashing::blake2_256(&data[..]);
527
19
				let maybe_msg = VersionedXcm::<T::RuntimeCall>::decode(&mut &data[..])
528
19
					.map(Xcm::<T::RuntimeCall>::try_from);
529
19
				match maybe_msg {
530
					Err(_) => {
531
						Self::deposit_event(Event::InvalidFormat(id));
532
					}
533
					Ok(Err(())) => {
534
						Self::deposit_event(Event::UnsupportedVersion(id));
535
					}
536
19
					Ok(Ok(x)) => {
537
19
						let outcome = T::XcmExecutor::prepare_and_execute(
538
19
							Parent,
539
19
							x,
540
19
							&mut id,
541
19
							limit,
542
19
							Weight::zero(),
543
19
						);
544
19

            
545
19
						Self::deposit_event(Event::ExecutedDownward(id, outcome));
546
19
					}
547
				}
548
			}
549
19
			limit
550
19
		}
551
	}
552
}
553

            
554
// Pallet to provide the version, used to test runtime upgrade version changes
555
#[frame_support::pallet]
556
pub mod mock_version_changer {
557
	use super::*;
558
	use frame_support::pallet_prelude::*;
559

            
560
	#[pallet::config]
561
	pub trait Config: frame_system::Config {
562
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
563
	}
564

            
565
	#[pallet::call]
566
	impl<T: Config> Pallet<T> {}
567

            
568
3
	#[pallet::pallet]
569
	pub struct Pallet<T>(_);
570

            
571
10
	#[pallet::storage]
572
	#[pallet::getter(fn current_version)]
573
	pub(super) type CurrentVersion<T: Config> = StorageValue<_, XcmVersion, ValueQuery>;
574

            
575
	impl<T: Config> Get<XcmVersion> for Pallet<T> {
576
2
		fn get() -> XcmVersion {
577
2
			Self::current_version()
578
2
		}
579
	}
580

            
581
	#[pallet::event]
582
2
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
583
	pub enum Event<T: Config> {
584
		// XCMP
585
		/// Some XCM was executed OK.
586
		VersionChanged(XcmVersion),
587
	}
588

            
589
	impl<T: Config> Pallet<T> {
590
2
		pub fn set_version(version: XcmVersion) {
591
2
			CurrentVersion::<T>::put(version);
592
2
			Self::deposit_event(Event::VersionChanged(version));
593
2
		}
594
	}
595
}
596

            
597
impl mock_msg_queue::Config for Runtime {
598
	type RuntimeEvent = RuntimeEvent;
599
	type XcmExecutor = XcmExecutor<XcmConfig>;
600
}
601

            
602
impl mock_version_changer::Config for Runtime {
603
	type RuntimeEvent = RuntimeEvent;
604
}
605

            
606
pub type LocalOriginToLocation =
607
	xcm_primitives::SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
608

            
609
parameter_types! {
610
	pub MatcherLocation: Location = Location::here();
611
}
612

            
613
impl pallet_xcm::Config for Runtime {
614
	type RuntimeEvent = RuntimeEvent;
615
	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
616
	type XcmRouter = XcmRouter;
617
	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
618
	type XcmExecuteFilter = frame_support::traits::Nothing;
619
	type XcmExecutor = XcmExecutor<XcmConfig>;
620
	// Do not allow teleports
621
	type XcmTeleportFilter = Nothing;
622
	type XcmReserveTransferFilter = Everything;
623
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
624
	type UniversalLocation = UniversalLocation;
625
	type RuntimeOrigin = RuntimeOrigin;
626
	type RuntimeCall = RuntimeCall;
627
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
628
	// We use a custom one to test runtime ugprades
629
	type AdvertisedXcmVersion = XcmVersioner;
630
	type Currency = Balances;
631
	type CurrencyMatcher = IsConcrete<MatcherLocation>;
632
	type TrustedLockers = ();
633
	type SovereignAccountOf = ();
634
	type MaxLockers = ConstU32<8>;
635
	type WeightInfo = pallet_xcm::TestWeightInfo;
636
	type MaxRemoteLockConsumers = ConstU32<0>;
637
	type RemoteLockConsumerIdentifier = ();
638
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
639
	type AuthorizedAliasConsideration = Disabled;
640
	type AssetHubMigrationStarted = ConstBool<false>;
641
}
642

            
643
#[derive(
644
	Clone,
645
	Default,
646
	Eq,
647
	Debug,
648
	PartialEq,
649
	Ord,
650
	PartialOrd,
651
	Encode,
652
	Decode,
653
	TypeInfo,
654
	DecodeWithMemTracking,
655
)]
656
pub struct AssetMetadata {
657
	pub name: Vec<u8>,
658
	pub symbol: Vec<u8>,
659
	pub decimals: u8,
660
}
661

            
662
pub struct AccountIdToH160;
663
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
664
238
	fn convert(account_id: AccountId) -> H160 {
665
238
		account_id.into()
666
238
	}
667
}
668

            
669
pub type ForeignAssetManagerOrigin = EitherOf<
670
	MapSuccessToXcm<EnsureXcm<AllowSiblingParachains>>,
671
	MapSuccessToGovernance<EnsureRoot<AccountId>>,
672
>;
673

            
674
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
675

            
676
parameter_types! {
677
	pub ForeignAssetCreationDeposit: u128 = 100 * currency::GLMR;
678
}
679

            
680
impl pallet_moonbeam_foreign_assets::Config for Runtime {
681
	type AccountIdToH160 = AccountIdToH160;
682
	type AssetIdFilter = Everything;
683
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
684
	type ConvertLocation =
685
		SiblingParachainConvertsVia<polkadot_parachain::primitives::Sibling, AccountId>;
686
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
687
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
688
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
689
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
690
	type OnForeignAssetCreated = ();
691
	type MaxForeignAssets = ConstU32<256>;
692
	type RuntimeEvent = RuntimeEvent;
693
	type WeightInfo = ();
694
	type XcmLocationToH160 = LocationToH160;
695
	type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit;
696
	type Balance = Balance;
697
	type Currency = Balances;
698
}
699

            
700
// 1 DOT should be enough
701
parameter_types! {
702
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
703
}
704

            
705
impl pallet_xcm_transactor::Config for Runtime {
706
	type RuntimeEvent = RuntimeEvent;
707
	type Balance = Balance;
708
	type Transactor = MockTransactors;
709
	type DerivativeAddressRegistrationOrigin = EnsureRoot<AccountId>;
710
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
711
	type CurrencyId = CurrencyId;
712
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
713
	type CurrencyIdToLocation = CurrencyIdToLocation<EvmForeignAssets>;
714
	type SelfLocation = SelfLocation;
715
	type Weigher = xcm_builder::FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
716
	type UniversalLocation = UniversalLocation;
717
	type XcmSender = XcmRouter;
718
	type BaseXcmWeight = BaseXcmWeight;
719
	type AssetTransactor = AssetTransactors;
720
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
721
	type WeightInfo = ();
722
	type HrmpManipulatorOrigin = EnsureRoot<AccountId>;
723
	type HrmpOpenOrigin = EnsureRoot<AccountId>;
724
	type MaxHrmpFee = xcm_builder::Case<MaxHrmpRelayFee>;
725
}
726

            
727
parameter_types! {
728
	pub RelayLocation: Location = Location::parent();
729
}
730

            
731
impl pallet_xcm_weight_trader::Config for Runtime {
732
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
733
	type AddSupportedAssetOrigin = EnsureRoot<AccountId>;
734
	type AssetLocationFilter = Everything;
735
	type AssetTransactor = AssetTransactors;
736
	type Balance = Balance;
737
	type EditSupportedAssetOrigin = EnsureRoot<AccountId>;
738
	type NativeLocation = SelfReserve;
739
	type PauseSupportedAssetOrigin = EnsureRoot<AccountId>;
740
	type RemoveSupportedAssetOrigin = EnsureRoot<AccountId>;
741
	type RuntimeEvent = RuntimeEvent;
742
	type ResumeSupportedAssetOrigin = EnsureRoot<AccountId>;
743
	type WeightInfo = ();
744
	type WeightToFee = WeightToFee;
745
	type XcmFeesAccount = XcmFeesAccount;
746
	#[cfg(feature = "runtime-benchmarks")]
747
	type NotFilteredLocation = RelayLocation;
748
}
749

            
750
parameter_types! {
751
	pub const MinimumPeriod: u64 = 1000;
752
}
753
impl pallet_timestamp::Config for Runtime {
754
	type Moment = u64;
755
	type OnTimestampSet = ();
756
	type MinimumPeriod = MinimumPeriod;
757
	type WeightInfo = ();
758
}
759

            
760
parameter_types! {
761
	pub BlockGasLimit: U256 = moonbeam_runtime::BlockGasLimit::get();
762
	pub WeightPerGas: Weight = moonbeam_runtime::WeightPerGas::get();
763
	pub const GasLimitPovSizeRatio: u64 = moonbeam_runtime::GasLimitPovSizeRatio::get();
764
	pub GasLimitStorageGrowthRatio: u64 = moonbeam_runtime::GasLimitStorageGrowthRatio::get();
765
}
766

            
767
impl pallet_evm::Config for Runtime {
768
	type FeeCalculator = ();
769
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
770
	type WeightPerGas = WeightPerGas;
771

            
772
	type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
773
	type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
774

            
775
	type AddressMapping = pallet_evm::IdentityAddressMapping;
776
	type Currency = Balances;
777
	type Runner = pallet_evm::runner::stack::Runner<Self>;
778

            
779
	type RuntimeEvent = RuntimeEvent;
780
	type PrecompilesType = ();
781
	type PrecompilesValue = ();
782
	type ChainId = ();
783
	type BlockGasLimit = BlockGasLimit;
784
	type OnChargeTransaction = ();
785
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
786
	type FindAuthor = ();
787
	type OnCreate = ();
788
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
789
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
790
	type Timestamp = Timestamp;
791
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
792
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
793
	type CreateOriginFilter = ();
794
	type CreateInnerOriginFilter = ();
795
}
796

            
797
#[allow(dead_code)]
798
pub struct NormalFilter;
799

            
800
impl frame_support::traits::Contains<RuntimeCall> for NormalFilter {
801
	fn contains(c: &RuntimeCall) -> bool {
802
		match c {
803
			_ => true,
804
		}
805
	}
806
}
807

            
808
// We need to use the encoding from the relay mock runtime
809
#[derive(Encode, Decode)]
810
pub enum RelayCall {
811
	#[codec(index = 5u8)]
812
	// the index should match the position of the module in `construct_runtime!`
813
	Utility(UtilityCall),
814
	#[codec(index = 6u8)]
815
	// the index should match the position of the module in `construct_runtime!`
816
	Hrmp(HrmpCall),
817
}
818

            
819
#[derive(Encode, Decode)]
820
pub enum UtilityCall {
821
	#[codec(index = 1u8)]
822
	AsDerivative(u16),
823
}
824

            
825
// HRMP call encoding, needed for xcm transactor pallet
826
#[derive(Encode, Decode)]
827
pub enum HrmpCall {
828
	#[codec(index = 0u8)]
829
	InitOpenChannel(ParaId, u32, u32),
830
	#[codec(index = 1u8)]
831
	AcceptOpenChannel(ParaId),
832
	#[codec(index = 2u8)]
833
	CloseChannel(HrmpChannelId),
834
	#[codec(index = 6u8)]
835
	CancelOpenRequest(HrmpChannelId, u32),
836
}
837

            
838
#[derive(
839
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
840
)]
841
pub enum MockTransactors {
842
	Relay,
843
}
844

            
845
impl xcm_primitives::XcmTransact for MockTransactors {
846
3
	fn destination(self) -> Location {
847
3
		match self {
848
3
			MockTransactors::Relay => Location::parent(),
849
3
		}
850
3
	}
851

            
852
7
	fn utility_pallet_index(&self) -> u8 {
853
7
		RelayIndices::<Runtime>::get().utility
854
7
	}
855

            
856
	fn staking_pallet_index(&self) -> u8 {
857
		RelayIndices::<Runtime>::get().staking
858
	}
859
}
860

            
861
#[allow(dead_code)]
862
pub struct MockHrmpEncoder;
863

            
864
impl xcm_primitives::HrmpEncodeCall for MockHrmpEncoder {
865
	fn hrmp_encode_call(
866
		call: xcm_primitives::HrmpAvailableCalls,
867
	) -> Result<Vec<u8>, xcm::latest::Error> {
868
		match call {
869
			xcm_primitives::HrmpAvailableCalls::InitOpenChannel(a, b, c) => Ok(RelayCall::Hrmp(
870
				HrmpCall::InitOpenChannel(a.clone(), b.clone(), c.clone()),
871
			)
872
			.encode()),
873
			xcm_primitives::HrmpAvailableCalls::AcceptOpenChannel(a) => {
874
				Ok(RelayCall::Hrmp(HrmpCall::AcceptOpenChannel(a.clone())).encode())
875
			}
876
			xcm_primitives::HrmpAvailableCalls::CloseChannel(a) => {
877
				Ok(RelayCall::Hrmp(HrmpCall::CloseChannel(a.clone())).encode())
878
			}
879
			xcm_primitives::HrmpAvailableCalls::CancelOpenRequest(a, b) => {
880
				Ok(RelayCall::Hrmp(HrmpCall::CancelOpenRequest(a.clone(), b.clone())).encode())
881
			}
882
		}
883
	}
884
}
885

            
886
parameter_types! {
887
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
888
}
889

            
890
impl pallet_ethereum::Config for Runtime {
891
	type RuntimeEvent = RuntimeEvent;
892
	type StateRoot =
893
		pallet_ethereum::IntermediateStateRoot<<Runtime as frame_system::Config>::Version>;
894
	type PostLogContent = PostBlockAndTxnHashes;
895
	type ExtraDataLength = ConstU32<30>;
896
}
897
parameter_types! {
898
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 0);
899
}
900

            
901
#[derive(
902
	Copy,
903
	Clone,
904
	Eq,
905
	PartialEq,
906
	Ord,
907
	PartialOrd,
908
	Encode,
909
	Decode,
910
	Debug,
911
	MaxEncodedLen,
912
	TypeInfo,
913
	DecodeWithMemTracking,
914
)]
915
pub enum ProxyType {
916
	NotAllowed = 0,
917
1
	Any = 1,
918
}
919

            
920
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
921

            
922
impl InstanceFilter<RuntimeCall> for ProxyType {
923
	fn filter(&self, _c: &RuntimeCall) -> bool {
924
		match self {
925
			ProxyType::NotAllowed => false,
926
			ProxyType::Any => true,
927
		}
928
	}
929
	fn is_superset(&self, _o: &Self) -> bool {
930
		false
931
	}
932
}
933

            
934
impl Default for ProxyType {
935
	fn default() -> Self {
936
		Self::NotAllowed
937
	}
938
}
939

            
940
parameter_types! {
941
	pub const ProxyCost: u64 = 1;
942
}
943

            
944
impl pallet_proxy::Config for Runtime {
945
	type RuntimeEvent = RuntimeEvent;
946
	type RuntimeCall = RuntimeCall;
947
	type Currency = Balances;
948
	type ProxyType = ProxyType;
949
	type ProxyDepositBase = ProxyCost;
950
	type ProxyDepositFactor = ProxyCost;
951
	type MaxProxies = ConstU32<32>;
952
	type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
953
	type MaxPending = ConstU32<32>;
954
	type CallHasher = BlakeTwo256;
955
	type AnnouncementDepositBase = ProxyCost;
956
	type AnnouncementDepositFactor = ProxyCost;
957
	type BlockNumberProvider = System;
958
}
959

            
960
pub struct EthereumXcmEnsureProxy;
961
impl xcm_primitives::EnsureProxy<AccountId> for EthereumXcmEnsureProxy {
962
2
	fn ensure_ok(delegator: AccountId, delegatee: AccountId) -> Result<(), &'static str> {
963
		// The EVM implicitely contains an Any proxy, so we only allow for "Any" proxies
964
1
		let def: pallet_proxy::ProxyDefinition<AccountId, ProxyType, BlockNumber> =
965
2
			pallet_proxy::Pallet::<Runtime>::find_proxy(
966
2
				&delegator,
967
2
				&delegatee,
968
2
				Some(ProxyType::Any),
969
2
			)
970
2
			.map_err(|_| "proxy error: expected `ProxyType::Any`")?;
971
		// We only allow to use it for delay zero proxies, as the call will iMmediatly be executed
972
1
		ensure!(def.delay.is_zero(), "proxy delay is Non-zero`");
973
1
		Ok(())
974
2
	}
975
}
976

            
977
impl pallet_ethereum_xcm::Config for Runtime {
978
	type RuntimeEvent = RuntimeEvent;
979
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
980
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
981
	type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
982
	type ReservedXcmpWeight = ReservedXcmpWeight;
983
	type EnsureProxy = EthereumXcmEnsureProxy;
984
	type ControllerOrigin = EnsureRoot<AccountId>;
985
	type ForceOrigin = EnsureRoot<AccountId>;
986
}
987

            
988
type Block = frame_system::mocking::MockBlockU32<Runtime>;
989

            
990
2270
construct_runtime!(
991
2270
	pub enum Runtime	{
992
2270
		System: frame_system,
993
2270
		Balances: pallet_balances,
994
2270
		MsgQueue: mock_msg_queue,
995
2270
		XcmVersioner: mock_version_changer,
996
2270

            
997
2270
		PolkadotXcm: pallet_xcm,
998
2270
		CumulusXcm: cumulus_pallet_xcm,
999
2270
		XcmTransactor: pallet_xcm_transactor,
2270
		XcmWeightTrader: pallet_xcm_weight_trader,
2270
		Treasury: pallet_treasury,
2270
		Proxy: pallet_proxy,
2270

            
2270
		Timestamp: pallet_timestamp,
2270
		EVM: pallet_evm,
2270
		Ethereum: pallet_ethereum,
2270
		EthereumXcm: pallet_ethereum_xcm,
2270
		EvmForeignAssets: pallet_moonbeam_foreign_assets,
2270
	}
2270
);
4
pub(crate) fn para_events() -> Vec<RuntimeEvent> {
4
	System::events()
4
		.into_iter()
56
		.map(|r| r.event)
56
		.filter_map(|e| Some(e))
4
		.collect::<Vec<_>>()
4
}
use frame_support::traits::{
	ConstBool, Disabled, OnFinalize, OnInitialize, UncheckedOnRuntimeUpgrade,
};
use moonbeam_runtime::{currency, xcm_config::LocationToH160};
use pallet_evm::FrameSystemAccountProvider;
use sp_weights::constants::WEIGHT_REF_TIME_PER_SECOND;
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
}