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

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

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

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

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

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

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

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

            
131
pub type ForeignAssetInstance = ();
132

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

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

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

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

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

            
217
parameter_types! {
218
	pub const UnitWeightCost: Weight = Weight::from_parts(1u64, 1u64);
219
	pub MaxInstructions: u32 = 100;
220
}
221

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

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

            
259
// We use both transactors
260
pub type AssetTransactors = (LocalAssetTransactor, ForeignFungiblesTransactor);
261

            
262
pub type XcmRouter = super::ParachainXcmRouter<MsgQueue>;
263

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

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

            
288
pub struct WeightToFee;
289
impl sp_weights::WeightToFee for WeightToFee {
290
	type Balance = Balance;
291

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

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

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

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

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

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

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

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

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

            
385
// How to convert from CurrencyId to Location
386
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
387
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
388
	for CurrencyIdToLocation<AssetXConverter>
389
where
390
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
391
{
392
25
	fn convert(currency: CurrencyId) -> Option<Location> {
393
25
		match currency {
394
			CurrencyId::SelfReserve => {
395
				// For now and until Xtokens is adapted to handle 0.9.16 version we use
396
				// the old anchoring here
397
				// This is not a problem in either cases, since the view of the destination
398
				// chain does not change
399
				// TODO! change this to NewAnchoringSelfReserve once xtokens is adapted for it
400
8
				let multi: Location = SelfReserve::get();
401
8
				Some(multi)
402
			}
403
17
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
404
		}
405
25
	}
406
}
407

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

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

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

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

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

            
462
	#[pallet::call]
463
	impl<T: Config> Pallet<T> {}
464

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

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

            
472
	impl<T: Config> Get<ParaId> for Pallet<T> {
473
50
		fn get() -> ParaId {
474
50
			Self::parachain_id()
475
50
		}
476
	}
477

            
478
	pub type MessageId = [u8; 32];
479

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

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

            
502
	impl<T: Config> Pallet<T> {
503
246
		pub fn set_para_id(para_id: ParaId) {
504
246
			ParachainId::<T>::put(para_id);
505
246
		}
506

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

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

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

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

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

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

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

            
617
	#[pallet::call]
618
	impl<T: Config> Pallet<T> {}
619

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

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

            
627
	impl<T: Config> Get<XcmVersion> for Pallet<T> {
628
4
		fn get() -> XcmVersion {
629
4
			Self::current_version()
630
4
		}
631
	}
632

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

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

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

            
654
impl mock_version_changer::Config for Runtime {
655
	type RuntimeEvent = RuntimeEvent;
656
}
657

            
658
pub type LocalOriginToLocation =
659
	xcm_primitives::SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
660

            
661
parameter_types! {
662
	pub MatcherLocation: Location = Location::here();
663
}
664

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

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

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

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

            
726
		Ok(())
727
	}
728

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

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

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

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

            
763
impl pallet_xcm_transactor::Config for Runtime {
764
	type RuntimeEvent = RuntimeEvent;
765
	type Balance = Balance;
766
	type Transactor = MockTransactors;
767
	type DerivativeAddressRegistrationOrigin = EnsureRoot<AccountId>;
768
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
769
	type CurrencyId = CurrencyId;
770
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
771
	type CurrencyIdToLocation =
772
		CurrencyIdToLocation<xcm_primitives::AsAssetType<AssetId, AssetType, AssetManager>>;
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
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
822
/// Block storage limit in bytes. Set to 160 KB.
823
const BLOCK_STORAGE_LIMIT: u64 = 160 * 1024;
824

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

            
836
impl pallet_evm::Config for Runtime {
837
	type FeeCalculator = ();
838
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
839
	type WeightPerGas = WeightPerGas;
840

            
841
	type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
842
	type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
843

            
844
	type AddressMapping = pallet_evm::IdentityAddressMapping;
845
	type Currency = Balances;
846
	type Runner = pallet_evm::runner::stack::Runner<Self>;
847

            
848
	type RuntimeEvent = RuntimeEvent;
849
	type PrecompilesType = ();
850
	type PrecompilesValue = ();
851
	type ChainId = ();
852
	type BlockGasLimit = BlockGasLimit;
853
	type OnChargeTransaction = ();
854
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
855
	type FindAuthor = ();
856
	type OnCreate = ();
857
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
858
	type SuicideQuickClearLimit = ConstU32<0>;
859
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
860
	type Timestamp = Timestamp;
861
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
862
}
863

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

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

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

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

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

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

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

            
931
pub struct MockHrmpEncoder;
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 = pallet_ethereum::IntermediateStateRoot<Self>;
961
	type PostLogContent = PostBlockAndTxnHashes;
962
	type ExtraDataLength = ConstU32<30>;
963
}
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>;
10704
construct_runtime!(
	pub enum Runtime	{
		System: frame_system,
		Balances: pallet_balances,
		MsgQueue: mock_msg_queue,
		XcmVersioner: mock_version_changer,
		PolkadotXcm: pallet_xcm,
		Assets: pallet_assets,
		CumulusXcm: cumulus_pallet_xcm,
		AssetManager: pallet_asset_manager,
		XcmTransactor: pallet_xcm_transactor,
		XcmWeightTrader: pallet_xcm_weight_trader,
		Treasury: pallet_treasury,
		Proxy: pallet_proxy,
		Timestamp: pallet_timestamp,
		EVM: pallet_evm,
		Ethereum: pallet_ethereum,
		EthereumXcm: pallet_ethereum_xcm,
	}
35433
);
6
pub(crate) fn para_events() -> Vec<RuntimeEvent> {
6
	System::events()
6
		.into_iter()
62
		.map(|r| r.event)
62
		.filter_map(|e| Some(e))
6
		.collect::<Vec<_>>()
6
}
use frame_support::traits::tokens::{PayFromAccount, UnityAssetBalanceConversion};
use frame_support::traits::{OnFinalize, OnInitialize, UncheckedOnRuntimeUpgrade};
2
pub(crate) fn on_runtime_upgrade() {
2
	VersionUncheckedMigrateToV1::<Runtime>::on_runtime_upgrade();
2
}
3
pub(crate) fn para_roll_to(n: BlockNumber) {
6
	while System::block_number() < n {
3
		PolkadotXcm::on_finalize(System::block_number());
3
		Balances::on_finalize(System::block_number());
3
		System::on_finalize(System::block_number());
3
		System::set_block_number(System::block_number() + 1);
3
		System::on_initialize(System::block_number());
3
		Balances::on_initialize(System::block_number());
3
		PolkadotXcm::on_initialize(System::block_number());
3
	}
3
}