1
// Copyright 2021 Parity Technologies (UK) Ltd.
2
// This file is part of Polkadot.
3

            
4
// Polkadot is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Polkadot is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Parachain runtime mock.
18

            
19
use frame_support::{
20
	construct_runtime, ensure, parameter_types,
21
	traits::{
22
		fungible::NativeOrWithId, ConstU32, EitherOf, Everything, Get, InstanceFilter, Nothing,
23
		PalletInfoAccess,
24
	},
25
	weights::Weight,
26
	PalletId,
27
};
28
pub use moonbeam_runtime::xcm_config::AssetType;
29

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
404
	#[pallet::config]
405
	pub trait Config: frame_system::Config {
406
		type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
407
	}
408

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
562
	#[pallet::config]
563
	pub trait Config: frame_system::Config {}
564

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

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

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

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

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

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

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

            
601
impl mock_version_changer::Config for Runtime {}
602

            
603
pub type LocalOriginToLocation =
604
	xcm_primitives::SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
605

            
606
parameter_types! {
607
	pub MatcherLocation: Location = Location::here();
608
}
609

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

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

            
658
pub struct AccountIdToH160;
659
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
660
238
	fn convert(account_id: AccountId) -> H160 {
661
238
		account_id.into()
662
238
	}
663
}
664

            
665
pub type ForeignAssetManagerOrigin = EitherOf<
666
	MapSuccessToXcm<EnsureXcm<AllowSiblingParachains>>,
667
	MapSuccessToGovernance<EnsureRoot<AccountId>>,
668
>;
669

            
670
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
671

            
672
parameter_types! {
673
	pub ForeignAssetCreationDeposit: u128 = 100 * currency::GLMR;
674
}
675

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

            
695
// 1 DOT should be enough
696
parameter_types! {
697
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
698
}
699

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

            
721
parameter_types! {
722
	pub RelayLocation: Location = Location::parent();
723
}
724

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

            
743
parameter_types! {
744
	pub const MinimumPeriod: u64 = 1000;
745
}
746
impl pallet_timestamp::Config for Runtime {
747
	type Moment = u64;
748
	type OnTimestampSet = ();
749
	type MinimumPeriod = MinimumPeriod;
750
	type WeightInfo = ();
751
}
752

            
753
parameter_types! {
754
	pub BlockGasLimit: U256 = moonbeam_runtime::BlockGasLimit::get();
755
	pub WeightPerGas: Weight = moonbeam_runtime::WeightPerGas::get();
756
	pub const GasLimitPovSizeRatio: u64 = moonbeam_runtime::GasLimitPovSizeRatio::get();
757
	pub GasLimitStorageGrowthRatio: u64 = moonbeam_runtime::GasLimitStorageGrowthRatio::get();
758
}
759

            
760
impl pallet_evm::Config for Runtime {
761
	type FeeCalculator = ();
762
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
763
	type WeightPerGas = WeightPerGas;
764

            
765
	type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
766
	type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
767

            
768
	type AddressMapping = pallet_evm::IdentityAddressMapping;
769
	type Currency = Balances;
770
	type Runner = pallet_evm::runner::stack::Runner<Self>;
771

            
772
	type PrecompilesType = ();
773
	type PrecompilesValue = ();
774
	type ChainId = ();
775
	type BlockGasLimit = BlockGasLimit;
776
	type OnChargeTransaction = ();
777
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
778
	type FindAuthor = ();
779
	type OnCreate = ();
780
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
781
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
782
	type Timestamp = Timestamp;
783
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
784
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
785
	type CreateOriginFilter = ();
786
	type CreateInnerOriginFilter = ();
787
}
788

            
789
#[allow(dead_code)]
790
pub struct NormalFilter;
791

            
792
impl frame_support::traits::Contains<RuntimeCall> for NormalFilter {
793
	fn contains(c: &RuntimeCall) -> bool {
794
		match c {
795
			_ => true,
796
		}
797
	}
798
}
799

            
800
// We need to use the encoding from the relay mock runtime
801
#[derive(Encode, Decode)]
802
pub enum RelayCall {
803
	#[codec(index = 5u8)]
804
	// the index should match the position of the module in `construct_runtime!`
805
	Utility(UtilityCall),
806
	#[codec(index = 6u8)]
807
	// the index should match the position of the module in `construct_runtime!`
808
	Hrmp(HrmpCall),
809
}
810

            
811
#[derive(Encode, Decode)]
812
pub enum UtilityCall {
813
	#[codec(index = 1u8)]
814
	AsDerivative(u16),
815
}
816

            
817
// HRMP call encoding, needed for xcm transactor pallet
818
#[derive(Encode, Decode)]
819
pub enum HrmpCall {
820
	#[codec(index = 0u8)]
821
	InitOpenChannel(ParaId, u32, u32),
822
	#[codec(index = 1u8)]
823
	AcceptOpenChannel(ParaId),
824
	#[codec(index = 2u8)]
825
	CloseChannel(HrmpChannelId),
826
	#[codec(index = 6u8)]
827
	CancelOpenRequest(HrmpChannelId, u32),
828
}
829

            
830
#[derive(
831
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
832
)]
833
pub enum MockTransactors {
834
	Relay,
835
}
836

            
837
impl xcm_primitives::XcmTransact for MockTransactors {
838
3
	fn destination(self) -> Location {
839
3
		match self {
840
3
			MockTransactors::Relay => Location::parent(),
841
		}
842
3
	}
843

            
844
7
	fn utility_pallet_index(&self) -> u8 {
845
7
		RelayIndices::<Runtime>::get().utility
846
7
	}
847

            
848
	fn staking_pallet_index(&self) -> u8 {
849
		RelayIndices::<Runtime>::get().staking
850
	}
851
}
852

            
853
#[allow(dead_code)]
854
pub struct MockHrmpEncoder;
855

            
856
impl xcm_primitives::HrmpEncodeCall for MockHrmpEncoder {
857
	fn hrmp_encode_call(
858
		call: xcm_primitives::HrmpAvailableCalls,
859
	) -> Result<Vec<u8>, xcm::latest::Error> {
860
		match call {
861
			xcm_primitives::HrmpAvailableCalls::InitOpenChannel(a, b, c) => Ok(RelayCall::Hrmp(
862
				HrmpCall::InitOpenChannel(a.clone(), b.clone(), c.clone()),
863
			)
864
			.encode()),
865
			xcm_primitives::HrmpAvailableCalls::AcceptOpenChannel(a) => {
866
				Ok(RelayCall::Hrmp(HrmpCall::AcceptOpenChannel(a.clone())).encode())
867
			}
868
			xcm_primitives::HrmpAvailableCalls::CloseChannel(a) => {
869
				Ok(RelayCall::Hrmp(HrmpCall::CloseChannel(a.clone())).encode())
870
			}
871
			xcm_primitives::HrmpAvailableCalls::CancelOpenRequest(a, b) => {
872
				Ok(RelayCall::Hrmp(HrmpCall::CancelOpenRequest(a.clone(), b.clone())).encode())
873
			}
874
		}
875
	}
876
}
877

            
878
parameter_types! {
879
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
880
}
881

            
882
impl pallet_ethereum::Config for Runtime {
883
	type StateRoot =
884
		pallet_ethereum::IntermediateStateRoot<<Runtime as frame_system::Config>::Version>;
885
	type PostLogContent = PostBlockAndTxnHashes;
886
	type ExtraDataLength = ConstU32<30>;
887
}
888
parameter_types! {
889
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 0);
890
}
891

            
892
#[derive(
893
	Copy,
894
	Clone,
895
	Eq,
896
	PartialEq,
897
	Ord,
898
	PartialOrd,
899
	Encode,
900
	Decode,
901
	Debug,
902
	MaxEncodedLen,
903
	TypeInfo,
904
	DecodeWithMemTracking,
905
)]
906
pub enum ProxyType {
907
	NotAllowed = 0,
908
	Any = 1,
909
}
910

            
911
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
912

            
913
impl InstanceFilter<RuntimeCall> for ProxyType {
914
	fn filter(&self, _c: &RuntimeCall) -> bool {
915
		match self {
916
			ProxyType::NotAllowed => false,
917
			ProxyType::Any => true,
918
		}
919
	}
920
	fn is_superset(&self, _o: &Self) -> bool {
921
		false
922
	}
923
}
924

            
925
impl Default for ProxyType {
926
	fn default() -> Self {
927
		Self::NotAllowed
928
	}
929
}
930

            
931
parameter_types! {
932
	pub const ProxyCost: u64 = 1;
933
}
934

            
935
impl pallet_proxy::Config for Runtime {
936
	type RuntimeEvent = RuntimeEvent;
937
	type RuntimeCall = RuntimeCall;
938
	type Currency = Balances;
939
	type ProxyType = ProxyType;
940
	type ProxyDepositBase = ProxyCost;
941
	type ProxyDepositFactor = ProxyCost;
942
	type MaxProxies = ConstU32<32>;
943
	type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
944
	type MaxPending = ConstU32<32>;
945
	type CallHasher = BlakeTwo256;
946
	type AnnouncementDepositBase = ProxyCost;
947
	type AnnouncementDepositFactor = ProxyCost;
948
	type BlockNumberProvider = System;
949
}
950

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

            
968
impl pallet_ethereum_xcm::Config for Runtime {
969
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
970
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
971
	type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
972
	type ReservedXcmpWeight = ReservedXcmpWeight;
973
	type EnsureProxy = EthereumXcmEnsureProxy;
974
	type ControllerOrigin = EnsureRoot<AccountId>;
975
	type ForceOrigin = EnsureRoot<AccountId>;
976
}
977

            
978
type Block = frame_system::mocking::MockBlockU32<Runtime>;
979

            
980
construct_runtime!(
981
	pub enum Runtime	{
982
		System: frame_system,
983
		Balances: pallet_balances,
984
		MsgQueue: mock_msg_queue,
985
		XcmVersioner: mock_version_changer,
986

            
987
		PolkadotXcm: pallet_xcm,
988
		CumulusXcm: cumulus_pallet_xcm,
989
		XcmTransactor: pallet_xcm_transactor,
990
		XcmWeightTrader: pallet_xcm_weight_trader,
991
		Treasury: pallet_treasury,
992
		Proxy: pallet_proxy,
993

            
994
		Timestamp: pallet_timestamp,
995
		EVM: pallet_evm,
996
		Ethereum: pallet_ethereum,
997
		EthereumXcm: pallet_ethereum_xcm,
998
		EvmForeignAssets: pallet_moonbeam_foreign_assets,
999
	}
);
4
pub(crate) fn para_events() -> Vec<RuntimeEvent> {
4
	System::events()
4
		.into_iter()
4
		.map(|r| r.event)
56
		.filter_map(|e| Some(e))
4
		.collect::<Vec<_>>()
4
}
use frame_support::traits::{Disabled, OnFinalize, OnInitialize, UncheckedOnRuntimeUpgrade};
use moonbeam_runtime::{currency, xcm_config::LocationToH160};
use pallet_evm::FrameSystemAccountProvider;
use sp_weights::constants::WEIGHT_REF_TIME_PER_SECOND;
1
pub(crate) fn on_runtime_upgrade() {
1
	VersionUncheckedMigrateToV1::<Runtime>::on_runtime_upgrade();
1
}
1
pub(crate) fn para_roll_to(n: BlockNumber) {
2
	while System::block_number() < n {
1
		PolkadotXcm::on_finalize(System::block_number());
1
		Balances::on_finalize(System::block_number());
1
		System::on_finalize(System::block_number());
1
		System::set_block_number(System::block_number() + 1);
1
		System::on_initialize(System::block_number());
1
		Balances::on_initialize(System::block_number());
1
		PolkadotXcm::on_initialize(System::block_number());
1
	}
1
}