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

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

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

            
60
pub use moonbase_runtime::xcm_config::AssetType;
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
}
109

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

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

            
132
pub type ForeignAssetInstance = ();
133

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

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

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

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

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

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

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

            
247
/// The transactor for our own chain currency.
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
// These will be our transactors
263
// We use both transactors
264
pub type AssetTransactors = (LocalAssetTransactor, ForeignFungiblesTransactor);
265

            
266
pub type XcmRouter = super::ParachainXcmRouter<MsgQueue>;
267

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

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

            
292
pub struct WeightToFee;
293
impl sp_weights::WeightToFee for WeightToFee {
294
	type Balance = Balance;
295

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

            
304
parameter_types! {
305
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
306
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
307
	pub UniversalLocation: InteriorLocation =
308
		[GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into();
309

            
310
	// New Self Reserve location, defines the multilocation identifiying the self-reserve currency
311
	// This is used to match it also against our Balances pallet when we receive such
312
	// a Location: (Self Balances pallet index)
313
	pub SelfReserve: Location = Location {
314
		parents:0,
315
		interior: [
316
			PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
317
		].into()
318
	};
319
	pub const MaxAssetsIntoHolding: u32 = 64;
320

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

            
327
	pub RelayChainNativeAssetFromAssetHub: (AssetFilter, Location) = (
328
		RelayLocationFilter::get(),
329
		AssetHubLocation::get()
330
	);
331
}
332

            
333
use frame_system::RawOrigin;
334
use sp_runtime::traits::PostDispatchInfoOf;
335
use sp_runtime::DispatchErrorWithPostInfo;
336
use xcm_executor::traits::CallDispatcher;
337
moonbeam_runtime_common::impl_moonbeam_xcm_call!();
338

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

            
348
pub struct XcmConfig;
349
impl Config for XcmConfig {
350
	type RuntimeCall = RuntimeCall;
351
	type XcmSender = XcmRouter;
352
	type AssetTransactor = AssetTransactors;
353
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
354
	type IsReserve = Reserves;
355
	type IsTeleporter = ();
356
	type UniversalLocation = UniversalLocation;
357
	type Barrier = XcmBarrier;
358
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
359
	type Trader = pallet_xcm_weight_trader::Trader<Runtime>;
360

            
361
	type ResponseHandler = PolkadotXcm;
362
	type SubscriptionService = PolkadotXcm;
363
	type AssetTrap = PolkadotXcm;
364
	type AssetClaims = PolkadotXcm;
365
	type CallDispatcher = MoonbeamCall;
366
	type AssetLocker = ();
367
	type AssetExchanger = ();
368
	type PalletInstancesInfo = ();
369
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
370
	type FeeManager = ();
371
	type MessageExporter = ();
372
	type UniversalAliases = Nothing;
373
	type SafeCallFilter = Everything;
374
	type Aliasers = Nothing;
375
	type TransactionalProcessor = ();
376
	type HrmpNewChannelOpenRequestHandler = ();
377
	type HrmpChannelAcceptedHandler = ();
378
	type HrmpChannelClosingHandler = ();
379
	type XcmRecorder = PolkadotXcm;
380
}
381

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

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

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

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

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

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

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

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

            
471
	#[pallet::call]
472
	impl<T: Config> Pallet<T> {}
473

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

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

            
481
	impl<T: Config> Get<ParaId> for Pallet<T> {
482
49
		fn get() -> ParaId {
483
49
			Self::parachain_id()
484
49
		}
485
	}
486

            
487
	pub type MessageId = [u8; 32];
488

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

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

            
511
	impl<T: Config> Pallet<T> {
512
246
		pub fn set_para_id(para_id: ParaId) {
513
246
			ParachainId::<T>::put(para_id);
514
246
		}
515

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

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

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

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

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

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

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

            
626
	#[pallet::call]
627
	impl<T: Config> Pallet<T> {}
628

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

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

            
636
	impl<T: Config> Get<XcmVersion> for Pallet<T> {
637
4
		fn get() -> XcmVersion {
638
4
			Self::current_version()
639
4
		}
640
	}
641

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

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

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

            
663
impl mock_version_changer::Config for Runtime {
664
	type RuntimeEvent = RuntimeEvent;
665
}
666

            
667
pub type LocalOriginToLocation =
668
	xcm_primitives::SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
669

            
670
parameter_types! {
671
	pub MatcherLocation: Location = Location::here();
672
}
673

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

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

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

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

            
735
		Ok(())
736
	}
737

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

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

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

            
767
// 1 ROC/WND should be enough
768
parameter_types! {
769
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
770
}
771

            
772
impl pallet_xcm_transactor::Config for Runtime {
773
	type RuntimeEvent = RuntimeEvent;
774
	type Balance = Balance;
775
	type Transactor = MockTransactors;
776
	type DerivativeAddressRegistrationOrigin = EnsureRoot<AccountId>;
777
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
778
	type CurrencyId = CurrencyId;
779
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
780
	type CurrencyIdToLocation =
781
		CurrencyIdToLocation<xcm_primitives::AsAssetType<AssetId, AssetType, AssetManager>>;
782
	type SelfLocation = SelfLocation;
783
	type Weigher = xcm_builder::FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
784
	type UniversalLocation = UniversalLocation;
785
	type XcmSender = XcmRouter;
786
	type BaseXcmWeight = BaseXcmWeight;
787
	type AssetTransactor = AssetTransactors;
788
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
789
	type WeightInfo = ();
790
	type HrmpManipulatorOrigin = EnsureRoot<AccountId>;
791
	type HrmpOpenOrigin = EnsureRoot<AccountId>;
792
	type MaxHrmpFee = xcm_builder::Case<MaxHrmpRelayFee>;
793
}
794

            
795
parameter_types! {
796
	pub RelayLocation: Location = Location::parent();
797
}
798

            
799
impl pallet_xcm_weight_trader::Config for Runtime {
800
	type AccountIdToLocation = xcm_primitives::AccountIdToLocation<AccountId>;
801
	type AddSupportedAssetOrigin = EnsureRoot<AccountId>;
802
	type AssetLocationFilter = Everything;
803
	type AssetTransactor = AssetTransactors;
804
	type Balance = Balance;
805
	type EditSupportedAssetOrigin = EnsureRoot<AccountId>;
806
	type NativeLocation = SelfReserve;
807
	type PauseSupportedAssetOrigin = EnsureRoot<AccountId>;
808
	type RemoveSupportedAssetOrigin = EnsureRoot<AccountId>;
809
	type RuntimeEvent = RuntimeEvent;
810
	type ResumeSupportedAssetOrigin = EnsureRoot<AccountId>;
811
	type WeightInfo = ();
812
	type WeightToFee = WeightToFee;
813
	type XcmFeesAccount = XcmFeesAccount;
814
	#[cfg(feature = "runtime-benchmarks")]
815
	type NotFilteredLocation = RelayLocation;
816
}
817

            
818
parameter_types! {
819
	pub const MinimumPeriod: u64 = 1000;
820
}
821
impl pallet_timestamp::Config for Runtime {
822
	type Moment = u64;
823
	type OnTimestampSet = ();
824
	type MinimumPeriod = MinimumPeriod;
825
	type WeightInfo = ();
826
}
827

            
828
use sp_core::U256;
829

            
830
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
831
/// Block storage limit in bytes. Set to 40 KB.
832
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
833

            
834
parameter_types! {
835
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
836
	pub WeightPerGas: Weight = Weight::from_parts(1, 0);
837
	pub GasLimitPovSizeRatio: u64 = {
838
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
839
		block_gas_limit.saturating_div(MAX_POV_SIZE)
840
	};
841
	pub GasLimitStorageGrowthRatio: u64 =
842
		BlockGasLimit::get().min(u64::MAX.into()).low_u64().saturating_div(BLOCK_STORAGE_LIMIT);
843
}
844

            
845
impl pallet_evm::Config for Runtime {
846
	type FeeCalculator = ();
847
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
848
	type WeightPerGas = WeightPerGas;
849

            
850
	type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
851
	type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
852

            
853
	type AddressMapping = pallet_evm::IdentityAddressMapping;
854
	type Currency = Balances;
855
	type Runner = pallet_evm::runner::stack::Runner<Self>;
856

            
857
	type RuntimeEvent = RuntimeEvent;
858
	type PrecompilesType = ();
859
	type PrecompilesValue = ();
860
	type ChainId = ();
861
	type BlockGasLimit = BlockGasLimit;
862
	type OnChargeTransaction = ();
863
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
864
	type FindAuthor = ();
865
	type OnCreate = ();
866
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
867
	type SuicideQuickClearLimit = ConstU32<0>;
868
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
869
	type Timestamp = Timestamp;
870
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
871
}
872

            
873
pub struct NormalFilter;
874
impl frame_support::traits::Contains<RuntimeCall> for NormalFilter {
875
	fn contains(c: &RuntimeCall) -> bool {
876
		match c {
877
			_ => true,
878
		}
879
	}
880
}
881

            
882
// We need to use the encoding from the relay mock runtime
883
#[derive(Encode, Decode)]
884
pub enum RelayCall {
885
	#[codec(index = 5u8)]
886
	// the index should match the position of the module in `construct_runtime!`
887
	Utility(UtilityCall),
888
	#[codec(index = 6u8)]
889
	// the index should match the position of the module in `construct_runtime!`
890
	Hrmp(HrmpCall),
891
}
892

            
893
#[derive(Encode, Decode)]
894
pub enum UtilityCall {
895
	#[codec(index = 1u8)]
896
	AsDerivative(u16),
897
}
898

            
899
// HRMP call encoding, needed for xcm transactor pallet
900
#[derive(Encode, Decode)]
901
pub enum HrmpCall {
902
	#[codec(index = 0u8)]
903
	InitOpenChannel(ParaId, u32, u32),
904
	#[codec(index = 1u8)]
905
	AcceptOpenChannel(ParaId),
906
	#[codec(index = 2u8)]
907
	CloseChannel(HrmpChannelId),
908
	#[codec(index = 6u8)]
909
	CancelOpenRequest(HrmpChannelId, u32),
910
}
911

            
912
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
913
pub enum MockTransactors {
914
	Relay,
915
}
916

            
917
impl xcm_primitives::XcmTransact for MockTransactors {
918
3
	fn destination(self) -> Location {
919
3
		match self {
920
3
			MockTransactors::Relay => Location::parent(),
921
3
		}
922
3
	}
923
}
924

            
925
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
926
7
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
927
7
		match self {
928
7
			MockTransactors::Relay => match call {
929
7
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
930
7
					let mut call =
931
7
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
932
7
					call.append(&mut b.clone());
933
7
					call
934
7
				}
935
7
			},
936
7
		}
937
7
	}
938
}
939

            
940
pub struct MockHrmpEncoder;
941
impl xcm_primitives::HrmpEncodeCall for MockHrmpEncoder {
942
	fn hrmp_encode_call(
943
		call: xcm_primitives::HrmpAvailableCalls,
944
	) -> Result<Vec<u8>, xcm::latest::Error> {
945
		match call {
946
			xcm_primitives::HrmpAvailableCalls::InitOpenChannel(a, b, c) => Ok(RelayCall::Hrmp(
947
				HrmpCall::InitOpenChannel(a.clone(), b.clone(), c.clone()),
948
			)
949
			.encode()),
950
			xcm_primitives::HrmpAvailableCalls::AcceptOpenChannel(a) => {
951
				Ok(RelayCall::Hrmp(HrmpCall::AcceptOpenChannel(a.clone())).encode())
952
			}
953
			xcm_primitives::HrmpAvailableCalls::CloseChannel(a) => {
954
				Ok(RelayCall::Hrmp(HrmpCall::CloseChannel(a.clone())).encode())
955
			}
956
			xcm_primitives::HrmpAvailableCalls::CancelOpenRequest(a, b) => {
957
				Ok(RelayCall::Hrmp(HrmpCall::CancelOpenRequest(a.clone(), b.clone())).encode())
958
			}
959
		}
960
	}
961
}
962

            
963
parameter_types! {
964
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
965
}
966

            
967
impl pallet_ethereum::Config for Runtime {
968
	type RuntimeEvent = RuntimeEvent;
969
	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
970
	type PostLogContent = PostBlockAndTxnHashes;
971
	type ExtraDataLength = ConstU32<30>;
972
}
973
parameter_types! {
974
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 0);
975
}
976

            
977
#[derive(
978
	Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
979
)]
980
pub enum ProxyType {
981
	NotAllowed = 0,
982
1
	Any = 1,
983
}
984

            
985
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
986

            
987
impl InstanceFilter<RuntimeCall> for ProxyType {
988
	fn filter(&self, _c: &RuntimeCall) -> bool {
989
		match self {
990
			ProxyType::NotAllowed => false,
991
			ProxyType::Any => true,
992
		}
993
	}
994
	fn is_superset(&self, _o: &Self) -> bool {
995
		false
996
	}
997
}
998

            
999
impl Default for ProxyType {
	fn default() -> Self {
		Self::NotAllowed
	}
}
parameter_types! {
	pub const ProxyCost: u64 = 1;
}
impl pallet_proxy::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeCall = RuntimeCall;
	type Currency = Balances;
	type ProxyType = ProxyType;
	type ProxyDepositBase = ProxyCost;
	type ProxyDepositFactor = ProxyCost;
	type MaxProxies = ConstU32<32>;
	type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
	type MaxPending = ConstU32<32>;
	type CallHasher = BlakeTwo256;
	type AnnouncementDepositBase = ProxyCost;
	type AnnouncementDepositFactor = ProxyCost;
}
pub struct EthereumXcmEnsureProxy;
impl xcm_primitives::EnsureProxy<AccountId> for EthereumXcmEnsureProxy {
2
	fn ensure_ok(delegator: AccountId, delegatee: AccountId) -> Result<(), &'static str> {
		// The EVM implicitely contains an Any proxy, so we only allow for "Any" proxies
1
		let def: pallet_proxy::ProxyDefinition<AccountId, ProxyType, BlockNumber> =
2
			pallet_proxy::Pallet::<Runtime>::find_proxy(
2
				&delegator,
2
				&delegatee,
2
				Some(ProxyType::Any),
2
			)
2
			.map_err(|_| "proxy error: expected `ProxyType::Any`")?;
		// We only allow to use it for delay zero proxies, as the call will iMmediatly be executed
1
		ensure!(def.delay.is_zero(), "proxy delay is Non-zero`");
1
		Ok(())
2
	}
}
impl pallet_ethereum_xcm::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
	type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
	type ReservedXcmpWeight = ReservedXcmpWeight;
	type EnsureProxy = EthereumXcmEnsureProxy;
	type ControllerOrigin = EnsureRoot<AccountId>;
	type ForceOrigin = EnsureRoot<AccountId>;
}
type Block = frame_system::mocking::MockBlockU32<Runtime>;
10689
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,
	}
35409
);
7
pub(crate) fn para_events() -> Vec<RuntimeEvent> {
7
	System::events()
7
		.into_iter()
76
		.map(|r| r.event)
76
		.filter_map(|e| Some(e))
7
		.collect::<Vec<_>>()
7
}
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
}