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
//! Relay chain runtime mock.
18

            
19
use frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{AsEnsureOriginWithArg, Contains, ContainsPair, Everything, Get, Nothing},
22
	weights::Weight,
23
};
24
use frame_system::{EnsureRoot, EnsureSigned};
25
use polkadot_core_primitives::BlockNumber as RelayBlockNumber;
26
use sp_core::H256;
27
use sp_runtime::{
28
	traits::{ConstU32, Hash, IdentityLookup},
29
	AccountId32,
30
};
31

            
32
use polkadot_parachain::primitives::Id as ParaId;
33
use polkadot_parachain::primitives::Sibling;
34
use sp_std::convert::TryFrom;
35
use xcm::latest::prelude::*;
36
use xcm::VersionedXcm;
37
use xcm_builder::{
38
	AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
39
	AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, AsPrefixedGeneralIndex,
40
	ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungibleAdapter,
41
	FungiblesAdapter, IsConcrete, NoChecking, ParentAsSuperuser, ParentIsPreset,
42
	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
43
	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
44
};
45
use xcm_executor::{traits::JustTry, Config, XcmExecutor};
46
use xcm_simulator::{
47
	DmpMessageHandlerT as DmpMessageHandler, XcmpMessageFormat,
48
	XcmpMessageHandlerT as XcmpMessageHandler,
49
};
50
pub type AccountId = AccountId32;
51
pub type Balance = u128;
52
pub type AssetId = u128;
53

            
54
parameter_types! {
55
	pub const BlockHashCount: u32 = 250;
56
}
57

            
58
impl frame_system::Config for Runtime {
59
	type RuntimeOrigin = RuntimeOrigin;
60
	type RuntimeCall = RuntimeCall;
61
	type RuntimeTask = RuntimeTask;
62
	type Nonce = u64;
63
	type Block = Block;
64
	type Hash = H256;
65
	type Hashing = ::sp_runtime::traits::BlakeTwo256;
66
	type AccountId = AccountId;
67
	type Lookup = IdentityLookup<Self::AccountId>;
68
	type RuntimeEvent = RuntimeEvent;
69
	type BlockHashCount = BlockHashCount;
70
	type BlockWeights = ();
71
	type BlockLength = ();
72
	type Version = ();
73
	type PalletInfo = PalletInfo;
74
	type AccountData = pallet_balances::AccountData<Balance>;
75
	type OnNewAccount = ();
76
	type OnKilledAccount = ();
77
	type DbWeight = ();
78
	type BaseCallFilter = Everything;
79
	type SystemWeightInfo = ();
80
	type SS58Prefix = ();
81
	type OnSetCode = ();
82
	type MaxConsumers = frame_support::traits::ConstU32<16>;
83
	type SingleBlockMigrations = ();
84
	type MultiBlockMigrator = ();
85
	type PreInherents = ();
86
	type PostInherents = ();
87
	type PostTransactions = ();
88
	type ExtensionsWeightInfo = ();
89
}
90

            
91
parameter_types! {
92
	pub ExistentialDeposit: Balance = 1;
93
	pub const MaxLocks: u32 = 50;
94
	pub const MaxReserves: u32 = 50;
95
}
96

            
97
impl pallet_balances::Config for Runtime {
98
	type MaxLocks = MaxLocks;
99
	type Balance = Balance;
100
	type RuntimeEvent = RuntimeEvent;
101
	type DustRemoval = ();
102
	type ExistentialDeposit = ExistentialDeposit;
103
	type AccountStore = System;
104
	type WeightInfo = ();
105
	type MaxReserves = MaxReserves;
106
	type ReserveIdentifier = [u8; 8];
107
	type RuntimeHoldReason = ();
108
	type FreezeIdentifier = ();
109
	type MaxFreezes = ();
110
	type RuntimeFreezeReason = ();
111
	type DoneSlashHandler = ();
112
}
113

            
114
// Required for runtime benchmarks
115
pallet_assets::runtime_benchmarks_enabled! {
116
	pub struct BenchmarkHelper;
117
	impl<AssetIdParameter> pallet_assets::BenchmarkHelper<AssetIdParameter> for BenchmarkHelper
118
	where
119
		AssetIdParameter: From<u128>,
120
	{
121
		fn create_asset_id_parameter(id: u32) -> AssetIdParameter {
122
			(id as u128).into()
123
		}
124
	}
125
}
126

            
127
parameter_types! {
128
	pub const AssetDeposit: Balance = 0; // 1 UNIT deposit to create asset
129
	pub const ApprovalDeposit: Balance = 0;
130
	pub const AssetsStringLimit: u32 = 50;
131
	/// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1)
132
	// https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271
133
	pub const MetadataDepositBase: Balance = 0;
134
	pub const MetadataDepositPerByte: Balance = 0;
135
	pub const ExecutiveBody: BodyId = BodyId::Executive;
136
	pub const AssetAccountDeposit: Balance = 0;
137
}
138

            
139
impl pallet_assets::Config for Runtime {
140
	type RuntimeEvent = RuntimeEvent;
141
	type Balance = Balance;
142
	type AssetId = AssetId;
143
	type Currency = Balances;
144
	type ForceOrigin = EnsureRoot<AccountId>;
145
	type AssetDeposit = AssetDeposit;
146
	type MetadataDepositBase = MetadataDepositBase;
147
	type MetadataDepositPerByte = MetadataDepositPerByte;
148
	type ApprovalDeposit = ApprovalDeposit;
149
	type StringLimit = AssetsStringLimit;
150
	type Freezer = ();
151
	type Extra = ();
152
	type AssetAccountDeposit = AssetAccountDeposit;
153
	type WeightInfo = ();
154
	type RemoveItemsLimit = ConstU32<656>;
155
	type AssetIdParameter = AssetId;
156
	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
157
	type CallbackHandle = ();
158
	pallet_assets::runtime_benchmarks_enabled! {
159
		type BenchmarkHelper = BenchmarkHelper;
160
	}
161
}
162

            
163
parameter_types! {
164
	pub const KsmLocation: Location = Location::parent();
165
	pub const RelayNetwork: NetworkId = NetworkId::Kusama;
166
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
167
	pub UniversalLocation: InteriorLocation =
168
		[GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into();
169
	pub Local: Location = Here.into();
170
	pub CheckingAccount: AccountId = PolkadotXcm::check_account();
171
	pub KsmPerSecond: (xcm::latest::prelude::AssetId, u128, u128) =
172
		(AssetId(KsmLocation::get()), 1, 1);
173
}
174

            
175
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
176
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
177
/// `Transact` in order to determine the dispatch Origin.
178
pub type LocationToAccountId = (
179
	// The parent (Relay-chain) origin converts to the default `AccountId`.
180
	ParentIsPreset<AccountId>,
181
	// Sibling parachain origins convert to AccountId via the `ParaId::into`.
182
	SiblingParachainConvertsVia<Sibling, AccountId>,
183
	// Straight up local `AccountId32` origins just alias directly to `AccountId`.
184
	AccountId32Aliases<RelayNetwork, AccountId>,
185
);
186

            
187
/// Means for transacting the native currency on this chain.
188
pub type CurrencyTransactor = FungibleAdapter<
189
	// Use this currency:
190
	Balances,
191
	// Use this currency when it is a fungible asset matching the given location or name:
192
	IsConcrete<KsmLocation>,
193
	// Convert an XCM Location into a local account id:
194
	LocationToAccountId,
195
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
196
	AccountId,
197
	// We don't track any teleports of `Balances`.
198
	(),
199
>;
200

            
201
/// Means for transacting assets besides the native currency on this chain.
202
pub type FungiblesTransactor = FungiblesAdapter<
203
	// Use this fungibles implementation:
204
	Assets,
205
	// Use this currency when it is a fungible asset matching the given location or name:
206
	ConvertedConcreteId<
207
		AssetId,
208
		Balance,
209
		AsPrefixedGeneralIndex<PrefixChanger, AssetId, JustTry>,
210
		JustTry,
211
	>,
212
	// Convert an XCM Location into a local account id:
213
	LocationToAccountId,
214
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
215
	AccountId,
216
	// We only want to allow teleports of known assets. We use non-zero issuance as an indication
217
	// that this asset is known.
218
	NoChecking,
219
	// The account to use for tracking teleports.
220
	CheckingAccount,
221
>;
222
/// Means for transacting assets on this chain.
223
pub type AssetTransactors = (CurrencyTransactor, FungiblesTransactor);
224

            
225
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
226
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
227
/// biases the kind of local `Origin` it will become.
228
pub type XcmOriginToTransactDispatchOrigin = (
229
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
230
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
231
	// foreign chains who want to have a local sovereign account on this chain which they control.
232
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
233
	// Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
234
	// recognised.
235
	RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
236
	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
237
	// recognised.
238
	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
239
	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
240
	// transaction from the Root origin.
241
	ParentAsSuperuser<RuntimeOrigin>,
242
	// Native signed account converter; this just converts an `AccountId32` origin into a normal
243
	// `RuntimeOrigin::signed` origin of the same 32-byte value.
244
	SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
245
	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
246
	pallet_xcm::XcmPassthrough<RuntimeOrigin>,
247
);
248

            
249
parameter_types! {
250
	// One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
251
	pub UnitWeightCost: Weight = Weight::from_parts(100u64, 100u64);
252
	pub const MaxInstructions: u32 = 100;
253
}
254

            
255
pub struct ParentOrParentsExecutivePlurality;
256
impl Contains<Location> for ParentOrParentsExecutivePlurality {
257
	fn contains(location: &Location) -> bool {
258
		matches!(
259
			location.unpack(),
260
			(1, [])
261
				| (
262
					1,
263
					[Plurality {
264
						id: BodyId::Executive,
265
						..
266
					}]
267
				)
268
		)
269
	}
270
}
271

            
272
pub struct ParentOrSiblings;
273
impl Contains<Location> for ParentOrSiblings {
274
	fn contains(location: &Location) -> bool {
275
		matches!(location.unpack(), (1, []) | (1, [_]))
276
	}
277
}
278

            
279
pub type Barrier = (
280
	TakeWeightCredit,
281
	AllowTopLevelPaidExecutionFrom<Everything>,
282
	// Parent and its exec plurality get free execution
283
	AllowUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
284
	// Expected responses are OK.
285
	AllowKnownQueryResponses<PolkadotXcm>,
286
	// Subscriptions for version tracking are OK.
287
	AllowSubscriptionsFrom<ParentOrSiblings>,
288
);
289

            
290
parameter_types! {
291
	pub MatcherLocation: Location = Location::here();
292
	pub const MaxAssetsIntoHolding: u32 = 64;
293
	pub const RelayTokenLocation: Location = Location::parent();
294
}
295

            
296
// Copied from:
297
//
298
// https://github.com/paritytech/polkadot-sdk/blob/f4eb41773611008040c9d4d8a8e6b7323eccfca1/cumulus
299
// /parachains/common/src/xcm_config.rs#L118
300
//
301
// The difference with the original "ConcreteAssetFromSystem" (which is used by AssetHub),
302
// is that in our tests we only need to check if the asset matches the relay one.
303
pub struct ConcreteAssetFromRelay<AssetLocation>(sp_std::marker::PhantomData<AssetLocation>);
304
impl<AssetLocation: Get<Location>> ContainsPair<Asset, Location>
305
	for ConcreteAssetFromRelay<AssetLocation>
306
{
307
29
	fn contains(asset: &Asset, origin: &Location) -> bool {
308
29
		let is_relay = match origin.unpack() {
309
			// The Relay Chain
310
29
			(1, []) => true,
311
			// Others
312
14
			_ => false,
313
		};
314
29
		asset.id.0 == AssetLocation::get() && is_relay
315
29
	}
316
}
317

            
318
pub type TrustedTeleporters = (ConcreteAssetFromRelay<RelayTokenLocation>,);
319

            
320
pub struct XcmConfig;
321
impl Config for XcmConfig {
322
	type RuntimeCall = RuntimeCall;
323
	type XcmSender = XcmRouter;
324
	type AssetTransactor = AssetTransactors;
325
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
326
	type IsReserve = xcm_primitives::MultiNativeAsset<xcm_primitives::RelativeReserveProvider>;
327
	type IsTeleporter = TrustedTeleporters;
328
	type UniversalLocation = UniversalLocation;
329
	type Barrier = Barrier;
330
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
331
	type Trader = FixedRateOfFungible<KsmPerSecond, ()>;
332
	type ResponseHandler = PolkadotXcm;
333
	type AssetTrap = PolkadotXcm;
334
	type AssetClaims = PolkadotXcm;
335
	type SubscriptionService = PolkadotXcm;
336
	type CallDispatcher = RuntimeCall;
337
	type AssetLocker = ();
338
	type AssetExchanger = ();
339
	type PalletInstancesInfo = ();
340
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
341
	type FeeManager = ();
342
	type MessageExporter = ();
343
	type UniversalAliases = Nothing;
344
	type SafeCallFilter = Everything;
345
	type Aliasers = Nothing;
346
	type TransactionalProcessor = ();
347
	type HrmpNewChannelOpenRequestHandler = ();
348
	type HrmpChannelAcceptedHandler = ();
349
	type HrmpChannelClosingHandler = ();
350
	type XcmRecorder = PolkadotXcm;
351
}
352

            
353
/// No local origins on this chain are allowed to dispatch XCM sends/executions.
354
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
355

            
356
pub type XcmRouter = super::ParachainXcmRouter<MsgQueue>;
357

            
358
impl pallet_xcm::Config for Runtime {
359
	type RuntimeEvent = RuntimeEvent;
360
	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
361
	type XcmRouter = XcmRouter;
362
	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
363
	type XcmExecuteFilter = Nothing;
364
	type XcmExecutor = XcmExecutor<XcmConfig>;
365
	type XcmTeleportFilter = Everything;
366
	type XcmReserveTransferFilter = Everything;
367
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
368
	type UniversalLocation = UniversalLocation;
369
	type RuntimeOrigin = RuntimeOrigin;
370
	type RuntimeCall = RuntimeCall;
371
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
372
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
373
	type Currency = Balances;
374
	type CurrencyMatcher = IsConcrete<MatcherLocation>;
375
	type TrustedLockers = ();
376
	type SovereignAccountOf = ();
377
	type MaxLockers = ConstU32<8>;
378
	type WeightInfo = pallet_xcm::TestWeightInfo;
379
	type MaxRemoteLockConsumers = ConstU32<0>;
380
	type RemoteLockConsumerIdentifier = ();
381
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
382
}
383

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

            
389
#[frame_support::pallet]
390
pub mod mock_msg_queue {
391
	use super::*;
392
	use frame_support::pallet_prelude::*;
393

            
394
	#[pallet::config]
395
	pub trait Config: frame_system::Config {
396
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
397
		type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
398
	}
399

            
400
	#[pallet::call]
401
	impl<T: Config> Pallet<T> {}
402

            
403
1
	#[pallet::pallet]
404
	pub struct Pallet<T>(_);
405

            
406
290
	#[pallet::storage]
407
	#[pallet::getter(fn parachain_id)]
408
	pub(super) type ParachainId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
409

            
410
	impl<T: Config> Get<ParaId> for Pallet<T> {
411
14
		fn get() -> ParaId {
412
14
			Self::parachain_id()
413
14
		}
414
	}
415

            
416
	pub type MessageId = [u8; 32];
417

            
418
	#[pallet::event]
419
11
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
420
	pub enum Event<T: Config> {
421
		// XCMP
422
		/// Some XCM was executed OK.
423
		Success(Option<T::Hash>),
424
		/// Some XCM failed.
425
		Fail(Option<T::Hash>, XcmError),
426
		/// Bad XCM version used.
427
		BadVersion(Option<T::Hash>),
428
		/// Bad XCM format used.
429
		BadFormat(Option<T::Hash>),
430

            
431
		// DMP
432
		/// Downward message is invalid XCM.
433
		InvalidFormat(MessageId),
434
		/// Downward message is unsupported version of XCM.
435
		UnsupportedVersion(MessageId),
436
		/// Downward message executed with the given outcome.
437
		ExecutedDownward(MessageId, Outcome),
438
	}
439

            
440
	impl<T: Config> Pallet<T> {
441
82
		pub fn set_para_id(para_id: ParaId) {
442
82
			ParachainId::<T>::put(para_id);
443
82
		}
444

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

            
485
	impl<T: Config> XcmpMessageHandler for Pallet<T> {
486
6
		fn handle_xcmp_messages<'a, I: Iterator<Item = (ParaId, RelayBlockNumber, &'a [u8])>>(
487
6
			iter: I,
488
6
			max_weight: Weight,
489
6
		) -> Weight {
490
12
			for (sender, sent_at, data) in iter {
491
6
				let mut data_ref = data;
492
6
				let _ = XcmpMessageFormat::decode(&mut data_ref)
493
6
					.expect("Simulator encodes with versioned xcm format; qed");
494
6

            
495
6
				let mut remaining_fragments = &data_ref[..];
496
12
				while !remaining_fragments.is_empty() {
497
6
					if let Ok(xcm) =
498
6
						VersionedXcm::<T::RuntimeCall>::decode(&mut remaining_fragments)
499
6
					{
500
6
						let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight);
501
6
					} else {
502
						debug_assert!(false, "Invalid incoming XCMP message data");
503
					}
504
				}
505
			}
506
6
			max_weight
507
6
		}
508
	}
509

            
510
	impl<T: Config> DmpMessageHandler for Pallet<T> {
511
5
		fn handle_dmp_messages(
512
5
			iter: impl Iterator<Item = (RelayBlockNumber, Vec<u8>)>,
513
5
			limit: Weight,
514
5
		) -> Weight {
515
5
			for (_i, (_sent_at, data)) in iter.enumerate() {
516
5
				let mut id = sp_io::hashing::blake2_256(&data[..]);
517
5
				let maybe_msg = VersionedXcm::<T::RuntimeCall>::decode(&mut &data[..])
518
5
					.map(Xcm::<T::RuntimeCall>::try_from);
519
5
				match maybe_msg {
520
					Err(_) => {
521
						Self::deposit_event(Event::InvalidFormat(id));
522
					}
523
					Ok(Err(())) => {
524
						Self::deposit_event(Event::UnsupportedVersion(id));
525
					}
526
5
					Ok(Ok(x)) => {
527
5
						let outcome = T::XcmExecutor::prepare_and_execute(
528
5
							Parent,
529
5
							x,
530
5
							&mut id,
531
5
							limit,
532
5
							Weight::zero(),
533
5
						);
534
5

            
535
5
						Self::deposit_event(Event::ExecutedDownward(id, outcome));
536
5
					}
537
				}
538
			}
539
5
			limit
540
5
		}
541
	}
542
}
543
impl mock_msg_queue::Config for Runtime {
544
	type RuntimeEvent = RuntimeEvent;
545
	type XcmExecutor = XcmExecutor<XcmConfig>;
546
}
547

            
548
// Pallet to cover test cases for change https://github.com/paritytech/cumulus/pull/831
549
#[frame_support::pallet]
550
pub mod mock_statemint_prefix {
551
	use super::*;
552
	use frame_support::pallet_prelude::*;
553

            
554
	#[pallet::config]
555
	pub trait Config: frame_system::Config {
556
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
557
	}
558

            
559
	#[pallet::call]
560
	impl<T: Config> Pallet<T> {}
561

            
562
1
	#[pallet::pallet]
563
	#[pallet::without_storage_info]
564
	pub struct Pallet<T>(_);
565

            
566
53
	#[pallet::storage]
567
	#[pallet::getter(fn current_prefix)]
568
	pub(super) type CurrentPrefix<T: Config> = StorageValue<_, Location, ValueQuery>;
569

            
570
	impl<T: Config> Get<Location> for Pallet<T> {
571
15
		fn get() -> Location {
572
15
			Self::current_prefix()
573
15
		}
574
	}
575

            
576
	#[pallet::event]
577
4
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
578
	pub enum Event<T: Config> {
579
		// Changed Prefix
580
		PrefixChanged(Location),
581
	}
582

            
583
	impl<T: Config> Pallet<T> {
584
4
		pub fn set_prefix(prefix: Location) {
585
4
			CurrentPrefix::<T>::put(&prefix);
586
4
			Self::deposit_event(Event::PrefixChanged(prefix));
587
4
		}
588
	}
589
}
590

            
591
impl mock_statemint_prefix::Config for Runtime {
592
	type RuntimeEvent = RuntimeEvent;
593
}
594

            
595
type Block = frame_system::mocking::MockBlockU32<Runtime>;
596
3061
construct_runtime!(
597
435
	pub enum Runtime	{
598
435
		System: frame_system,
599
435
		Balances: pallet_balances,
600
435
		PolkadotXcm: pallet_xcm,
601
435
		CumulusXcm: cumulus_pallet_xcm,
602
435
		MsgQueue: mock_msg_queue,
603
435
		Assets: pallet_assets,
604
435
		PrefixChanger: mock_statemint_prefix,
605
435

            
606
435
	}
607
3091
);