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
		AsEnsureOriginWithArg, ConstU32, Everything, Get, InstanceFilter, Nothing, PalletInfoAccess,
25
	},
26
	weights::Weight,
27
	PalletId,
28
};
29
pub use moonbeam_runtime::xcm_config::AssetType;
30

            
31
use frame_system::{pallet_prelude::BlockNumberFor, EnsureNever, EnsureRoot};
32
use pallet_xcm::migration::v1::VersionUncheckedMigrateToV1;
33
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
34
use sp_core::H256;
35
use sp_runtime::{
36
	traits::{BlakeTwo256, Hash, IdentityLookup, MaybeEquivalence, Zero},
37
	Permill,
38
};
39
use sp_std::{convert::TryFrom, prelude::*};
40
use xcm::{latest::prelude::*, Version as XcmVersion, VersionedXcm};
41

            
42
use cumulus_primitives_core::relay_chain::HrmpChannelId;
43
use pallet_ethereum::PostLogContent;
44
use polkadot_core_primitives::BlockNumber as RelayBlockNumber;
45
use polkadot_parachain::primitives::{Id as ParaId, Sibling};
46
use xcm::latest::{
47
	Error as XcmError, ExecuteXcm,
48
	Junction::{PalletInstance, Parachain},
49
	Location, NetworkId, Outcome, Xcm,
50
};
51
use xcm_builder::{
52
	AccountKey20Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
53
	AllowTopLevelPaidExecutionFrom, Case, ConvertedConcreteId, EnsureXcmOrigin, FixedWeightBounds,
54
	FungibleAdapter as XcmCurrencyAdapter, FungiblesAdapter, IsConcrete, NoChecking,
55
	ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
56
	SiblingParachainConvertsVia, SignedAccountKey20AsNative, SovereignSignedViaLocation,
57
	TakeWeightCredit, WithComputedOrigin,
58
};
59
use xcm_executor::{traits::JustTry, Config, XcmExecutor};
60

            
61
#[cfg(feature = "runtime-benchmarks")]
62
use moonbeam_runtime_common::benchmarking::BenchmarkHelper as ArgumentsBenchmarkHelper;
63
use scale_info::TypeInfo;
64
use xcm_simulator::{
65
	DmpMessageHandlerT as DmpMessageHandler, XcmpMessageFormat,
66
	XcmpMessageHandlerT as XcmpMessageHandler,
67
};
68

            
69
pub type AccountId = moonbeam_core_primitives::AccountId;
70
pub type Balance = u128;
71
pub type AssetId = u128;
72
pub type BlockNumber = BlockNumberFor<Runtime>;
73

            
74
parameter_types! {
75
	pub const BlockHashCount: u32 = 250;
76
}
77

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

            
111
parameter_types! {
112
	pub ExistentialDeposit: Balance = 0;
113
	pub const MaxLocks: u32 = 50;
114
	pub const MaxReserves: u32 = 50;
115
}
116

            
117
impl pallet_balances::Config for Runtime {
118
	type MaxLocks = MaxLocks;
119
	type Balance = Balance;
120
	type RuntimeEvent = RuntimeEvent;
121
	type DustRemoval = ();
122
	type ExistentialDeposit = ExistentialDeposit;
123
	type AccountStore = System;
124
	type WeightInfo = ();
125
	type MaxReserves = MaxReserves;
126
	type ReserveIdentifier = [u8; 8];
127
	type RuntimeHoldReason = ();
128
	type FreezeIdentifier = ();
129
	type MaxFreezes = ();
130
	type RuntimeFreezeReason = ();
131
	type DoneSlashHandler = ();
132
}
133

            
134
pub type ForeignAssetInstance = ();
135

            
136
// Required for runtime benchmarks
137
pallet_assets::runtime_benchmarks_enabled! {
138
	pub struct BenchmarkHelper;
139
	impl<AssetIdParameter> pallet_assets::BenchmarkHelper<AssetIdParameter> for BenchmarkHelper
140
	where
141
		AssetIdParameter: From<u128>,
142
	{
143
		fn create_asset_id_parameter(id: u32) -> AssetIdParameter {
144
			(id as u128).into()
145
		}
146
	}
147
}
148

            
149
parameter_types! {
150
	pub const AssetDeposit: Balance = 1; // Does not really matter as this will be only called by root
151
	pub const ApprovalDeposit: Balance = 0;
152
	pub const AssetsStringLimit: u32 = 50;
153
	pub const MetadataDepositBase: Balance = 0;
154
	pub const MetadataDepositPerByte: Balance = 0;
155
	pub const AssetAccountDeposit: Balance = 0;
156
}
157

            
158
impl pallet_assets::Config<ForeignAssetInstance> for Runtime {
159
	type RuntimeEvent = RuntimeEvent;
160
	type Balance = Balance;
161
	type AssetId = AssetId;
162
	type Currency = Balances;
163
	type ForceOrigin = EnsureRoot<AccountId>;
164
	type AssetDeposit = AssetDeposit;
165
	type MetadataDepositBase = MetadataDepositBase;
166
	type MetadataDepositPerByte = MetadataDepositPerByte;
167
	type ApprovalDeposit = ApprovalDeposit;
168
	type StringLimit = AssetsStringLimit;
169
	type Freezer = ();
170
	type Extra = ();
171
	type AssetAccountDeposit = AssetAccountDeposit;
172
	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
173
	type RemoveItemsLimit = ConstU32<656>;
174
	type AssetIdParameter = AssetId;
175
	type CreateOrigin = AsEnsureOriginWithArg<EnsureNever<AccountId>>;
176
	type CallbackHandle = ();
177
	pallet_assets::runtime_benchmarks_enabled! {
178
		type BenchmarkHelper = BenchmarkHelper;
179
	}
180
}
181

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

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

            
220
parameter_types! {
221
	pub const UnitWeightCost: Weight = Weight::from_parts(1u64, 1u64);
222
	pub MaxInstructions: u32 = 100;
223
}
224

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

            
248
pub type LocalAssetTransactor = XcmCurrencyAdapter<
249
	// Use this currency:
250
	Balances,
251
	// Use this currency when it is a fungible asset matching any of the locations in
252
	// SelfReserveRepresentations
253
	IsConcrete<SelfReserve>,
254
	// We can convert the Locations with our converter above:
255
	LocationToAccountId,
256
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
257
	AccountId,
258
	// We dont allow teleport
259
	(),
260
>;
261

            
262
// We use all transactors
263
pub type AssetTransactors = (LocalAssetTransactor, ForeignFungiblesTransactor);
264
pub type XcmRouter = super::ParachainXcmRouter<MsgQueue>;
265

            
266
pub type XcmBarrier = (
267
	// Weight that is paid for may be consumed.
268
	TakeWeightCredit,
269
	// Expected responses are OK.
270
	AllowKnownQueryResponses<PolkadotXcm>,
271
	WithComputedOrigin<
272
		(
273
			// If the message is one that immediately attemps to pay for execution, then allow it.
274
			AllowTopLevelPaidExecutionFrom<Everything>,
275
			// Subscriptions for version tracking are OK.
276
			AllowSubscriptionsFrom<Everything>,
277
		),
278
		UniversalLocation,
279
		ConstU32<8>,
280
	>,
281
);
282

            
283
parameter_types! {
284
	/// Xcm fees will go to the treasury account
285
	pub XcmFeesAccount: AccountId = Treasury::account_id();
286
	/// Parachain token units per second of execution
287
	pub ParaTokensPerSecond: u128 = WEIGHT_REF_TIME_PER_SECOND as u128;
288
}
289

            
290
pub struct WeightToFee;
291
impl sp_weights::WeightToFee for WeightToFee {
292
	type Balance = Balance;
293

            
294
46
	fn weight_to_fee(weight: &Weight) -> Self::Balance {
295
		use sp_runtime::SaturatedConversion as _;
296
46
		Self::Balance::saturated_from(weight.ref_time())
297
46
			.saturating_mul(ParaTokensPerSecond::get())
298
46
			.saturating_div(frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND as u128)
299
46
	}
300
}
301

            
302
parameter_types! {
303
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
304
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
305
	pub UniversalLocation: InteriorLocation =
306
		[GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into();
307
	pub SelfReserve: Location = Location {
308
		parents:0,
309
		interior: [
310
			PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
311
		].into()
312
	};
313
	pub const MaxAssetsIntoHolding: u32 = 64;
314

            
315
	pub AssetHubLocation: Location = Location::new(1, [Parachain(1000)]);
316
	pub RelayLocationFilter: AssetFilter = Wild(AllOf {
317
		fun: WildFungible,
318
		id: xcm::prelude::AssetId(Location::parent()),
319
	});
320

            
321
	pub RelayChainNativeAssetFromAssetHub: (AssetFilter, Location) = (
322
		RelayLocationFilter::get(),
323
		AssetHubLocation::get()
324
	);
325
}
326

            
327
use frame_system::RawOrigin;
328
use sp_runtime::traits::PostDispatchInfoOf;
329
use sp_runtime::DispatchErrorWithPostInfo;
330
use xcm_executor::traits::CallDispatcher;
331
moonbeam_runtime_common::impl_moonbeam_xcm_call!();
332

            
333
type Reserves = (
334
	// Relaychain (DOT) from Asset Hub
335
	Case<RelayChainNativeAssetFromAssetHub>,
336
	// Assets which the reserve is the same as the origin.
337
	xcm_primitives::MultiNativeAsset<
338
		xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>,
339
	>,
340
);
341

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

            
375
impl cumulus_pallet_xcm::Config for Runtime {
376
	type RuntimeEvent = RuntimeEvent;
377
	type XcmExecutor = XcmExecutor<XcmConfig>;
378
}
379

            
380
// Our currencyId. We distinguish for now between SelfReserve, and Others, defined by their Id.
381
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
382
pub enum CurrencyId {
383
	SelfReserve,
384
	ForeignAsset(AssetId),
385
}
386

            
387
// How to convert from CurrencyId to Location
388
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
389
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
390
	for CurrencyIdToLocation<AssetXConverter>
391
where
392
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
393
{
394
23
	fn convert(currency: CurrencyId) -> Option<Location> {
395
23
		match currency {
396
			CurrencyId::SelfReserve => {
397
6
				let multi: Location = SelfReserve::get();
398
6
				Some(multi)
399
			}
400
17
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
401
		}
402
23
	}
403
}
404

            
405
parameter_types! {
406
	pub const BaseXcmWeight: Weight = Weight::from_parts(100u64, 100u64);
407
	pub const MaxAssetsForTransfer: usize = 2;
408
	pub SelfLocation: Location = Location::here();
409
	pub SelfLocationAbsolute: Location = Location {
410
		parents:1,
411
		interior: [
412
			Parachain(MsgQueue::parachain_id().into())
413
		].into()
414
	};
415
}
416

            
417
parameter_types! {
418
	pub const ProposalBond: Permill = Permill::from_percent(5);
419
	pub const ProposalBondMinimum: Balance = 0;
420
	pub const SpendPeriod: u32 = 0;
421
	pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
422
	pub const MaxApprovals: u32 = 100;
423
	pub TreasuryAccount: AccountId = Treasury::account_id();
424
}
425

            
426
impl pallet_treasury::Config for Runtime {
427
	type PalletId = TreasuryId;
428
	type Currency = Balances;
429
	type RejectOrigin = EnsureRoot<AccountId>;
430
	type RuntimeEvent = RuntimeEvent;
431
	type SpendPeriod = SpendPeriod;
432
	type Burn = ();
433
	type BurnDestination = ();
434
	type MaxApprovals = MaxApprovals;
435
	type WeightInfo = ();
436
	type SpendFunds = ();
437
	type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>; // Same as Polkadot
438
	type AssetKind = ();
439
	type Beneficiary = AccountId;
440
	type BeneficiaryLookup = IdentityLookup<AccountId>;
441
	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
442
	type BalanceConverter = UnityAssetBalanceConversion;
443
	type PayoutPeriod = ConstU32<0>;
444
	#[cfg(feature = "runtime-benchmarks")]
445
	type BenchmarkHelper = ArgumentsBenchmarkHelper;
446
	type BlockNumberProvider = System;
447
}
448

            
449
#[frame_support::pallet]
450
pub mod mock_msg_queue {
451
	use super::*;
452
	use frame_support::pallet_prelude::*;
453

            
454
	#[pallet::config]
455
	pub trait Config: frame_system::Config {
456
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
457
		type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
458
	}
459

            
460
	#[pallet::call]
461
	impl<T: Config> Pallet<T> {}
462

            
463
1
	#[pallet::pallet]
464
	pub struct Pallet<T>(_);
465

            
466
1092
	#[pallet::storage]
467
	#[pallet::getter(fn parachain_id)]
468
	pub(super) type ParachainId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
469

            
470
	impl<T: Config> Get<ParaId> for Pallet<T> {
471
43
		fn get() -> ParaId {
472
43
			Self::parachain_id()
473
43
		}
474
	}
475

            
476
	pub type MessageId = [u8; 32];
477

            
478
	#[pallet::event]
479
47
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
480
	pub enum Event<T: Config> {
481
		// XCMP
482
		/// Some XCM was executed OK.
483
		Success(Option<T::Hash>),
484
		/// Some XCM failed.
485
		Fail(Option<T::Hash>, XcmError),
486
		/// Bad XCM version used.
487
		BadVersion(Option<T::Hash>),
488
		/// Bad XCM format used.
489
		BadFormat(Option<T::Hash>),
490

            
491
		// DMP
492
		/// Downward message is invalid XCM.
493
		InvalidFormat(MessageId),
494
		/// Downward message is unsupported version of XCM.
495
		UnsupportedVersion(MessageId),
496
4
		/// Downward message executed with the given outcome.
497
		ExecutedDownward(MessageId, Outcome),
498
	}
499

            
500
	impl<T: Config> Pallet<T> {
501
234
		pub fn set_para_id(para_id: ParaId) {
502
234
			ParachainId::<T>::put(para_id);
503
234
		}
504

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

            
545
	impl<T: Config> XcmpMessageHandler for Pallet<T> {
546
27
		fn handle_xcmp_messages<'a, I: Iterator<Item = (ParaId, RelayBlockNumber, &'a [u8])>>(
547
27
			iter: I,
548
27
			max_weight: Weight,
549
27
		) -> Weight {
550
54
			for (sender, sent_at, data) in iter {
551
27
				let mut data_ref = data;
552
27
				let _ = XcmpMessageFormat::decode(&mut data_ref)
553
27
					.expect("Simulator encodes with versioned xcm format; qed");
554
27

            
555
27
				let mut remaining_fragments = &data_ref[..];
556
54
				while !remaining_fragments.is_empty() {
557
27
					if let Ok(xcm) =
558
27
						VersionedXcm::<T::RuntimeCall>::decode(&mut remaining_fragments)
559
27
					{
560
27
						let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight);
561
27
					} else {
562
						debug_assert!(false, "Invalid incoming XCMP message data");
563
					}
564
				}
565
			}
566
27
			max_weight
567
27
		}
568
	}
569

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

            
595
20
						Self::deposit_event(Event::ExecutedDownward(id, outcome));
596
20
					}
597
				}
598
			}
599
20
			limit
600
20
		}
601
	}
602
}
603

            
604
// Pallet to provide the version, used to test runtime upgrade version changes
605
#[frame_support::pallet]
606
pub mod mock_version_changer {
607
	use super::*;
608
	use frame_support::pallet_prelude::*;
609

            
610
	#[pallet::config]
611
	pub trait Config: frame_system::Config {
612
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
613
	}
614

            
615
	#[pallet::call]
616
	impl<T: Config> Pallet<T> {}
617

            
618
1
	#[pallet::pallet]
619
	pub struct Pallet<T>(_);
620

            
621
10
	#[pallet::storage]
622
	#[pallet::getter(fn current_version)]
623
	pub(super) type CurrentVersion<T: Config> = StorageValue<_, XcmVersion, ValueQuery>;
624

            
625
	impl<T: Config> Get<XcmVersion> for Pallet<T> {
626
2
		fn get() -> XcmVersion {
627
2
			Self::current_version()
628
2
		}
629
	}
630

            
631
	#[pallet::event]
632
2
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
633
	pub enum Event<T: Config> {
634
		// XCMP
635
2
		/// Some XCM was executed OK.
636
		VersionChanged(XcmVersion),
637
	}
638

            
639
	impl<T: Config> Pallet<T> {
640
2
		pub fn set_version(version: XcmVersion) {
641
2
			CurrentVersion::<T>::put(version);
642
2
			Self::deposit_event(Event::VersionChanged(version));
643
2
		}
644
	}
645
}
646

            
647
impl mock_msg_queue::Config for Runtime {
648
	type RuntimeEvent = RuntimeEvent;
649
	type XcmExecutor = XcmExecutor<XcmConfig>;
650
}
651

            
652
impl mock_version_changer::Config for Runtime {
653
	type RuntimeEvent = RuntimeEvent;
654
}
655

            
656
pub type LocalOriginToLocation =
657
	xcm_primitives::SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
658

            
659
parameter_types! {
660
	pub MatcherLocation: Location = Location::here();
661
}
662

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

            
691
// We instruct how to register the Assets
692
// In this case, we tell it to Create an Asset in pallet-assets
693
pub struct AssetRegistrar;
694
use frame_support::pallet_prelude::DispatchResult;
695
impl pallet_asset_manager::AssetRegistrar<Runtime> for AssetRegistrar {
696
33
	fn create_foreign_asset(
697
33
		asset: AssetId,
698
33
		min_balance: Balance,
699
33
		metadata: AssetMetadata,
700
33
		is_sufficient: bool,
701
33
	) -> DispatchResult {
702
33
		Assets::force_create(
703
33
			RuntimeOrigin::root(),
704
33
			asset,
705
33
			AssetManager::account_id(),
706
33
			is_sufficient,
707
33
			min_balance,
708
33
		)?;
709

            
710
33
		Assets::force_set_metadata(
711
33
			RuntimeOrigin::root(),
712
33
			asset,
713
33
			metadata.name,
714
33
			metadata.symbol,
715
33
			metadata.decimals,
716
33
			false,
717
33
		)
718
33
	}
719

            
720
	fn destroy_foreign_asset(asset: AssetId) -> DispatchResult {
721
		// Mark the asset as destroying
722
		Assets::start_destroy(RuntimeOrigin::root(), asset.into())?;
723

            
724
		Ok(())
725
	}
726

            
727
	fn destroy_asset_dispatch_info_weight(asset: AssetId) -> Weight {
728
		RuntimeCall::Assets(
729
			pallet_assets::Call::<Runtime, ForeignAssetInstance>::start_destroy {
730
				id: asset.into(),
731
			},
732
		)
733
		.get_dispatch_info()
734
		.total_weight()
735
	}
736
}
737

            
738
#[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
739
pub struct AssetMetadata {
740
	pub name: Vec<u8>,
741
	pub symbol: Vec<u8>,
742
	pub decimals: u8,
743
}
744

            
745
impl pallet_asset_manager::Config for Runtime {
746
	type RuntimeEvent = RuntimeEvent;
747
	type Balance = Balance;
748
	type AssetId = AssetId;
749
	type AssetRegistrarMetadata = AssetMetadata;
750
	type ForeignAssetType = AssetType;
751
	type AssetRegistrar = AssetRegistrar;
752
	type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
753
	type WeightInfo = ();
754
}
755

            
756
// 1 DOT should be enough
757
parameter_types! {
758
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
759
}
760

            
761
impl pallet_xcm_transactor::Config for Runtime {
762
	type RuntimeEvent = RuntimeEvent;
763
	type Balance = Balance;
764
	type Transactor = MockTransactors;
765
	type DerivativeAddressRegistrationOrigin = EnsureRoot<AccountId>;
766
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
767
	type CurrencyId = CurrencyId;
768
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
769
	type CurrencyIdToLocation = CurrencyIdToLocation<(
770
		EvmForeignAssets,
771
		AsAssetType<moonbeam_core_primitives::AssetId, AssetType, AssetManager>,
772
	)>;
773
	type SelfLocation = SelfLocation;
774
	type Weigher = xcm_builder::FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
775
	type UniversalLocation = UniversalLocation;
776
	type XcmSender = XcmRouter;
777
	type BaseXcmWeight = BaseXcmWeight;
778
	type AssetTransactor = AssetTransactors;
779
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
780
	type WeightInfo = ();
781
	type HrmpManipulatorOrigin = EnsureRoot<AccountId>;
782
	type HrmpOpenOrigin = EnsureRoot<AccountId>;
783
	type MaxHrmpFee = xcm_builder::Case<MaxHrmpRelayFee>;
784
}
785

            
786
parameter_types! {
787
	pub RelayLocation: Location = Location::parent();
788
}
789

            
790
impl pallet_xcm_weight_trader::Config for Runtime {
791
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
792
	type AddSupportedAssetOrigin = EnsureRoot<AccountId>;
793
	type AssetLocationFilter = Everything;
794
	type AssetTransactor = AssetTransactors;
795
	type Balance = Balance;
796
	type EditSupportedAssetOrigin = EnsureRoot<AccountId>;
797
	type NativeLocation = SelfReserve;
798
	type PauseSupportedAssetOrigin = EnsureRoot<AccountId>;
799
	type RemoveSupportedAssetOrigin = EnsureRoot<AccountId>;
800
	type RuntimeEvent = RuntimeEvent;
801
	type ResumeSupportedAssetOrigin = EnsureRoot<AccountId>;
802
	type WeightInfo = ();
803
	type WeightToFee = WeightToFee;
804
	type XcmFeesAccount = XcmFeesAccount;
805
	#[cfg(feature = "runtime-benchmarks")]
806
	type NotFilteredLocation = RelayLocation;
807
}
808

            
809
parameter_types! {
810
	pub const MinimumPeriod: u64 = 1000;
811
}
812
impl pallet_timestamp::Config for Runtime {
813
	type Moment = u64;
814
	type OnTimestampSet = ();
815
	type MinimumPeriod = MinimumPeriod;
816
	type WeightInfo = ();
817
}
818

            
819
use sp_core::U256;
820

            
821
parameter_types! {
822
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
823
	pub WeightPerGas: Weight = Weight::from_parts(1, 0);
824
	pub GasLimitPovSizeRatio: u64 = {
825
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
826
		block_gas_limit.saturating_div(MAX_POV_SIZE as u64)
827
	};
828
	pub GasLimitStorageGrowthRatio: u64 =
829
		BlockGasLimit::get().min(u64::MAX.into()).low_u64().saturating_div(BLOCK_STORAGE_LIMIT);
830
}
831

            
832
impl pallet_evm::Config for Runtime {
833
	type FeeCalculator = ();
834
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
835
	type WeightPerGas = WeightPerGas;
836

            
837
	type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
838
	type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
839

            
840
	type AddressMapping = pallet_evm::IdentityAddressMapping;
841
	type Currency = Balances;
842
	type Runner = pallet_evm::runner::stack::Runner<Self>;
843

            
844
	type RuntimeEvent = RuntimeEvent;
845
	type PrecompilesType = ();
846
	type PrecompilesValue = ();
847
	type ChainId = ();
848
	type BlockGasLimit = BlockGasLimit;
849
	type OnChargeTransaction = ();
850
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
851
	type FindAuthor = ();
852
	type OnCreate = ();
853
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
854
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
855
	type Timestamp = Timestamp;
856
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
857
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
858
}
859

            
860
#[allow(dead_code)]
861
pub struct NormalFilter;
862

            
863
impl frame_support::traits::Contains<RuntimeCall> for NormalFilter {
864
	fn contains(c: &RuntimeCall) -> bool {
865
		match c {
866
			_ => true,
867
		}
868
	}
869
}
870

            
871
// We need to use the encoding from the relay mock runtime
872
#[derive(Encode, Decode)]
873
pub enum RelayCall {
874
	#[codec(index = 5u8)]
875
	// the index should match the position of the module in `construct_runtime!`
876
	Utility(UtilityCall),
877
	#[codec(index = 6u8)]
878
	// the index should match the position of the module in `construct_runtime!`
879
	Hrmp(HrmpCall),
880
}
881

            
882
#[derive(Encode, Decode)]
883
pub enum UtilityCall {
884
	#[codec(index = 1u8)]
885
	AsDerivative(u16),
886
}
887

            
888
// HRMP call encoding, needed for xcm transactor pallet
889
#[derive(Encode, Decode)]
890
pub enum HrmpCall {
891
	#[codec(index = 0u8)]
892
	InitOpenChannel(ParaId, u32, u32),
893
	#[codec(index = 1u8)]
894
	AcceptOpenChannel(ParaId),
895
	#[codec(index = 2u8)]
896
	CloseChannel(HrmpChannelId),
897
	#[codec(index = 6u8)]
898
	CancelOpenRequest(HrmpChannelId, u32),
899
}
900

            
901
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
902
pub enum MockTransactors {
903
	Relay,
904
}
905

            
906
impl xcm_primitives::XcmTransact for MockTransactors {
907
3
	fn destination(self) -> Location {
908
3
		match self {
909
3
			MockTransactors::Relay => Location::parent(),
910
3
		}
911
3
	}
912
}
913

            
914
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
915
7
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
916
7
		match self {
917
7
			MockTransactors::Relay => match call {
918
7
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
919
7
					let mut call =
920
7
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
921
7
					call.append(&mut b.clone());
922
7
					call
923
7
				}
924
7
			},
925
7
		}
926
7
	}
927
}
928

            
929
#[allow(dead_code)]
930
pub struct MockHrmpEncoder;
931

            
932
impl xcm_primitives::HrmpEncodeCall for MockHrmpEncoder {
933
	fn hrmp_encode_call(
934
		call: xcm_primitives::HrmpAvailableCalls,
935
	) -> Result<Vec<u8>, xcm::latest::Error> {
936
		match call {
937
			xcm_primitives::HrmpAvailableCalls::InitOpenChannel(a, b, c) => Ok(RelayCall::Hrmp(
938
				HrmpCall::InitOpenChannel(a.clone(), b.clone(), c.clone()),
939
			)
940
			.encode()),
941
			xcm_primitives::HrmpAvailableCalls::AcceptOpenChannel(a) => {
942
				Ok(RelayCall::Hrmp(HrmpCall::AcceptOpenChannel(a.clone())).encode())
943
			}
944
			xcm_primitives::HrmpAvailableCalls::CloseChannel(a) => {
945
				Ok(RelayCall::Hrmp(HrmpCall::CloseChannel(a.clone())).encode())
946
			}
947
			xcm_primitives::HrmpAvailableCalls::CancelOpenRequest(a, b) => {
948
				Ok(RelayCall::Hrmp(HrmpCall::CancelOpenRequest(a.clone(), b.clone())).encode())
949
			}
950
		}
951
	}
952
}
953

            
954
parameter_types! {
955
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
956
}
957

            
958
impl pallet_ethereum::Config for Runtime {
959
	type RuntimeEvent = RuntimeEvent;
960
	type StateRoot =
961
		pallet_ethereum::IntermediateStateRoot<<Runtime as frame_system::Config>::Version>;
962
	type PostLogContent = PostBlockAndTxnHashes;
963
	type ExtraDataLength = ConstU32<30>;
964
}
965
parameter_types! {
966
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 0);
967
}
968

            
969
#[derive(
970
	Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
971
)]
972
pub enum ProxyType {
973
	NotAllowed = 0,
974
1
	Any = 1,
975
}
976

            
977
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
978

            
979
impl InstanceFilter<RuntimeCall> for ProxyType {
980
	fn filter(&self, _c: &RuntimeCall) -> bool {
981
		match self {
982
			ProxyType::NotAllowed => false,
983
			ProxyType::Any => true,
984
		}
985
	}
986
	fn is_superset(&self, _o: &Self) -> bool {
987
		false
988
	}
989
}
990

            
991
impl Default for ProxyType {
992
	fn default() -> Self {
993
		Self::NotAllowed
994
	}
995
}
996

            
997
parameter_types! {
998
	pub const ProxyCost: u64 = 1;
999
}
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>;
9360
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
	}
9539
);
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::tokens::{PayFromAccount, UnityAssetBalanceConversion};
use frame_support::traits::{OnFinalize, OnInitialize, UncheckedOnRuntimeUpgrade};
use moonbeam_runtime::{EvmForeignAssets, 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
}