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

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

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

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

            
72
pub type AccountId = moonbeam_core_primitives::AccountId;
73
pub type Balance = u128;
74
pub type AssetId = u128;
75
pub type BlockNumber = BlockNumberFor<Runtime>;
76

            
77
parameter_types! {
78
	pub const BlockHashCount: u32 = 250;
79
}
80

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

            
114
parameter_types! {
115
	pub ExistentialDeposit: Balance = 0;
116
	pub const MaxLocks: u32 = 50;
117
	pub const MaxReserves: u32 = 50;
118
}
119

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

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

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

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

            
184
parameter_types! {
185
	pub const UnitWeightCost: Weight = Weight::from_parts(1u64, 1u64);
186
	pub MaxInstructions: u32 = 100;
187
}
188

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

            
204
// These will be our transactors
205
// We use both transactors
206
pub type AssetTransactors = (LocalAssetTransactor, EvmForeignAssets);
207

            
208
pub type XcmRouter = super::ParachainXcmRouter<MsgQueue>;
209

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

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

            
234
pub struct WeightToFee;
235
impl sp_weights::WeightToFee for WeightToFee {
236
	type Balance = Balance;
237

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

            
246
parameter_types! {
247
	pub RelayNetwork: NetworkId = moonbase_runtime::xcm_config::RelayNetwork::get();
248
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
249
	pub UniversalLocation: InteriorLocation =
250
		[GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into();
251

            
252
	// New Self Reserve location, defines the multilocation identifying the self-reserve currency
253
	// This is used to match it also against our Balances pallet when we receive such
254
	// a Location: (Self Balances pallet index)
255
	pub SelfReserve: Location = Location {
256
		parents:0,
257
		interior: [
258
			PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
259
		].into()
260
	};
261
	pub const MaxAssetsIntoHolding: u32 = 64;
262

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

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

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

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

            
290
pub struct XcmConfig;
291
impl Config for XcmConfig {
292
	type RuntimeCall = RuntimeCall;
293
	type XcmSender = XcmRouter;
294
	type AssetTransactor = AssetTransactors;
295
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
296
	type IsReserve = Reserves;
297
	type IsTeleporter = ();
298
	type UniversalLocation = UniversalLocation;
299
	type Barrier = XcmBarrier;
300
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
301
	type Trader = pallet_xcm_weight_trader::Trader<Runtime>;
302

            
303
	type ResponseHandler = PolkadotXcm;
304
	type SubscriptionService = PolkadotXcm;
305
	type AssetTrap = PolkadotXcm;
306
	type AssetClaims = PolkadotXcm;
307
	type CallDispatcher = MoonbeamCall;
308
	type AssetLocker = ();
309
	type AssetExchanger = ();
310
	type PalletInstancesInfo = ();
311
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
312
	type FeeManager = ();
313
	type MessageExporter = ();
314
	type UniversalAliases = Nothing;
315
	type SafeCallFilter = Everything;
316
	type Aliasers = Nothing;
317
	type TransactionalProcessor = ();
318
	type HrmpNewChannelOpenRequestHandler = ();
319
	type HrmpChannelAcceptedHandler = ();
320
	type HrmpChannelClosingHandler = ();
321
	type XcmRecorder = PolkadotXcm;
322
	type XcmEventEmitter = ();
323
}
324

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

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

            
339
// How to convert from CurrencyId to Location
340
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
341
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
342
	for CurrencyIdToLocation<AssetXConverter>
343
where
344
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
345
{
346
25
	fn convert(currency: CurrencyId) -> Option<Location> {
347
25
		match currency {
348
			CurrencyId::SelfReserve => {
349
				// For now and until Xtokens is adapted to handle 0.9.16 version we use
350
				// the old anchoring here
351
				// This is not a problem in either cases, since the view of the destination
352
				// chain does not change
353
				// TODO! change this to NewAnchoringSelfReserve once xtokens is adapted for it
354
8
				let multi: Location = SelfReserve::get();
355
8
				Some(multi)
356
			}
357
17
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
358
		}
359
25
	}
360
}
361

            
362
parameter_types! {
363
	pub const BaseXcmWeight: Weight = Weight::from_parts(100u64, 100u64);
364
	pub const MaxAssetsForTransfer: usize = 2;
365
	pub SelfLocation: Location = Location::here();
366
	pub SelfLocationAbsolute: Location = Location {
367
		parents:1,
368
		interior: [
369
			Parachain(MsgQueue::parachain_id().into())
370
		].into()
371
	};
372
}
373

            
374
parameter_types! {
375
	pub const ProposalBond: Permill = Permill::from_percent(5);
376
	pub const ProposalBondMinimum: Balance = 0;
377
	pub const SpendPeriod: u32 = 0;
378
	pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
379
	pub const MaxApprovals: u32 = 100;
380
	pub TreasuryAccount: AccountId = Treasury::account_id();
381
}
382

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

            
406
#[frame_support::pallet]
407
pub mod mock_msg_queue {
408
	use super::*;
409
	use frame_support::pallet_prelude::*;
410

            
411
	#[pallet::config]
412
	pub trait Config: frame_system::Config {
413
		type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
414
	}
415

            
416
	#[pallet::call]
417
	impl<T: Config> Pallet<T> {}
418

            
419
	#[pallet::pallet]
420
	pub struct Pallet<T>(_);
421

            
422
	#[pallet::storage]
423
	#[pallet::getter(fn parachain_id)]
424
	pub(super) type ParachainId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
425

            
426
	impl<T: Config> Get<ParaId> for Pallet<T> {
427
49
		fn get() -> ParaId {
428
49
			Self::parachain_id()
429
49
		}
430
	}
431

            
432
	pub type MessageId = [u8; 32];
433

            
434
	#[pallet::event]
435
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
436
	pub enum Event<T: Config> {
437
		// XCMP
438
		/// Some XCM was executed OK.
439
		Success(Option<T::Hash>),
440
		/// Some XCM failed.
441
		Fail(Option<T::Hash>, InstructionError),
442
		/// Bad XCM version used.
443
		BadVersion(Option<T::Hash>),
444
		/// Bad XCM format used.
445
		BadFormat(Option<T::Hash>),
446

            
447
		// DMP
448
		/// Downward message is invalid XCM.
449
		InvalidFormat(MessageId),
450
		/// Downward message is unsupported version of XCM.
451
		UnsupportedVersion(MessageId),
452
		/// Downward message executed with the given outcome.
453
		ExecutedDownward(MessageId, Outcome),
454
	}
455

            
456
	impl<T: Config> Pallet<T> {
457
246
		pub fn set_para_id(para_id: ParaId) {
458
246
			ParachainId::<T>::put(para_id);
459
246
		}
460

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

            
504
	impl<T: Config> XcmpMessageHandler for Pallet<T> {
505
33
		fn handle_xcmp_messages<'a, I: Iterator<Item = (ParaId, RelayBlockNumber, &'a [u8])>>(
506
33
			iter: I,
507
33
			max_weight: Weight,
508
33
		) -> Weight {
509
66
			for (sender, sent_at, data) in iter {
510
33
				let mut data_ref = data;
511
33
				let _ = XcmpMessageFormat::decode(&mut data_ref)
512
33
					.expect("Simulator encodes with versioned xcm format; qed");
513

            
514
33
				let mut remaining_fragments = &data_ref[..];
515
66
				while !remaining_fragments.is_empty() {
516
33
					if let Ok(xcm) =
517
33
						VersionedXcm::<T::RuntimeCall>::decode(&mut remaining_fragments)
518
33
					{
519
33
						let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight);
520
33
					} else {
521
						debug_assert!(false, "Invalid incoming XCMP message data");
522
					}
523
				}
524
			}
525
33
			max_weight
526
33
		}
527
	}
528

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

            
554
19
						Self::deposit_event(Event::ExecutedDownward(id, outcome));
555
19
					}
556
				}
557
			}
558
19
			limit
559
19
		}
560
	}
561
}
562

            
563
// Pallet to provide the version, used to test runtime upgrade version changes
564
#[frame_support::pallet]
565
pub mod mock_version_changer {
566
	use super::*;
567
	use frame_support::pallet_prelude::*;
568

            
569
	#[pallet::config]
570
	pub trait Config: frame_system::Config {}
571

            
572
	#[pallet::call]
573
	impl<T: Config> Pallet<T> {}
574

            
575
	#[pallet::pallet]
576
	pub struct Pallet<T>(_);
577

            
578
	#[pallet::storage]
579
	#[pallet::getter(fn current_version)]
580
	pub(super) type CurrentVersion<T: Config> = StorageValue<_, XcmVersion, ValueQuery>;
581

            
582
	impl<T: Config> Get<XcmVersion> for Pallet<T> {
583
4
		fn get() -> XcmVersion {
584
4
			Self::current_version()
585
4
		}
586
	}
587

            
588
	#[pallet::event]
589
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
590
	pub enum Event<T: Config> {
591
		// XCMP
592
		/// Some XCM was executed OK.
593
		VersionChanged(XcmVersion),
594
	}
595

            
596
	impl<T: Config> Pallet<T> {
597
5
		pub fn set_version(version: XcmVersion) {
598
5
			CurrentVersion::<T>::put(version);
599
5
			Self::deposit_event(Event::VersionChanged(version));
600
5
		}
601
	}
602
}
603

            
604
impl mock_msg_queue::Config for Runtime {
605
	type XcmExecutor = XcmExecutor<XcmConfig>;
606
}
607

            
608
impl mock_version_changer::Config for Runtime {}
609

            
610
pub type LocalOriginToLocation =
611
	xcm_primitives::SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
612

            
613
parameter_types! {
614
	pub MatcherLocation: Location = Location::here();
615
}
616

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

            
646
#[derive(
647
	Clone,
648
	Default,
649
	Eq,
650
	Debug,
651
	PartialEq,
652
	Ord,
653
	PartialOrd,
654
	Encode,
655
	Decode,
656
	TypeInfo,
657
	DecodeWithMemTracking,
658
)]
659
pub struct AssetMetadata {
660
	pub name: Vec<u8>,
661
	pub symbol: Vec<u8>,
662
	pub decimals: u8,
663
}
664

            
665
pub struct AccountIdToH160;
666
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
667
250
	fn convert(account_id: AccountId) -> H160 {
668
250
		account_id.into()
669
250
	}
670
}
671

            
672
pub type ForeignAssetManagerOrigin = EitherOf<
673
	MapSuccessToXcm<EnsureXcm<AllowSiblingParachains>>,
674
	MapSuccessToGovernance<EnsureRoot<AccountId>>,
675
>;
676

            
677
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
678

            
679
parameter_types! {
680
	pub ForeignAssetCreationDeposit: u128 = 100 * currency::UNIT;
681
}
682

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

            
702
// 1 ROC/WND should be enough
703
parameter_types! {
704
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
705
}
706

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

            
728
parameter_types! {
729
	pub RelayLocation: Location = Location::parent();
730
}
731

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

            
750
parameter_types! {
751
	pub const MinimumPeriod: u64 = 1000;
752
}
753
impl pallet_timestamp::Config for Runtime {
754
	type Moment = u64;
755
	type OnTimestampSet = ();
756
	type MinimumPeriod = MinimumPeriod;
757
	type WeightInfo = ();
758
}
759

            
760
parameter_types! {
761
	pub BlockGasLimit: U256 = moonbase_runtime::BlockGasLimit::get();
762
	pub WeightPerGas: Weight = moonbase_runtime::WeightPerGas::get();
763
	pub const GasLimitPovSizeRatio: u64 = moonbase_runtime::GasLimitPovSizeRatio::get();
764
	pub GasLimitStorageGrowthRatio: u64 = moonbase_runtime::GasLimitStorageGrowthRatio::get();
765
}
766

            
767
impl pallet_evm::Config for Runtime {
768
	type FeeCalculator = ();
769
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
770
	type WeightPerGas = WeightPerGas;
771

            
772
	type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
773
	type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
774

            
775
	type AddressMapping = pallet_evm::IdentityAddressMapping;
776
	type Currency = Balances;
777
	type Runner = pallet_evm::runner::stack::Runner<Self>;
778

            
779
	type PrecompilesType = ();
780
	type PrecompilesValue = ();
781
	type ChainId = ();
782
	type BlockGasLimit = BlockGasLimit;
783
	type OnChargeTransaction = ();
784
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
785
	type FindAuthor = ();
786
	type OnCreate = ();
787
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
788
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
789
	type Timestamp = Timestamp;
790
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
791
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
792
	type CreateOriginFilter = ();
793
	type CreateInnerOriginFilter = ();
794
}
795

            
796
#[allow(dead_code)]
797
pub struct NormalFilter;
798

            
799
impl frame_support::traits::Contains<RuntimeCall> for NormalFilter {
800
	fn contains(c: &RuntimeCall) -> bool {
801
		match c {
802
			_ => true,
803
		}
804
	}
805
}
806

            
807
// We need to use the encoding from the relay mock runtime
808
#[derive(Encode, Decode)]
809
pub enum RelayCall {
810
	#[codec(index = 5u8)]
811
	// the index should match the position of the module in `construct_runtime!`
812
	Utility(UtilityCall),
813
	#[codec(index = 6u8)]
814
	// the index should match the position of the module in `construct_runtime!`
815
	Hrmp(HrmpCall),
816
}
817

            
818
#[derive(Encode, Decode)]
819
pub enum UtilityCall {
820
	#[codec(index = 1u8)]
821
	AsDerivative(u16),
822
}
823

            
824
// HRMP call encoding, needed for xcm transactor pallet
825
#[derive(Encode, Decode)]
826
pub enum HrmpCall {
827
	#[codec(index = 0u8)]
828
	InitOpenChannel(ParaId, u32, u32),
829
	#[codec(index = 1u8)]
830
	AcceptOpenChannel(ParaId),
831
	#[codec(index = 2u8)]
832
	CloseChannel(HrmpChannelId),
833
	#[codec(index = 6u8)]
834
	CancelOpenRequest(HrmpChannelId, u32),
835
}
836

            
837
#[derive(
838
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
839
)]
840
pub enum MockTransactors {
841
	Relay,
842
}
843

            
844
impl xcm_primitives::XcmTransact for MockTransactors {
845
3
	fn destination(self) -> Location {
846
3
		match self {
847
3
			MockTransactors::Relay => Location::parent(),
848
		}
849
3
	}
850

            
851
3
	fn utility_pallet_index(&self) -> u8 {
852
3
		XcmTransactor::relay_indices().utility
853
3
	}
854

            
855
	fn staking_pallet_index(&self) -> u8 {
856
		XcmTransactor::relay_indices().staking
857
	}
858
}
859

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

            
863
impl xcm_primitives::HrmpEncodeCall for MockHrmpEncoder {
864
	fn hrmp_encode_call(
865
		call: xcm_primitives::HrmpAvailableCalls,
866
	) -> Result<Vec<u8>, xcm::latest::Error> {
867
		match call {
868
			xcm_primitives::HrmpAvailableCalls::InitOpenChannel(a, b, c) => Ok(RelayCall::Hrmp(
869
				HrmpCall::InitOpenChannel(a.clone(), b.clone(), c.clone()),
870
			)
871
			.encode()),
872
			xcm_primitives::HrmpAvailableCalls::AcceptOpenChannel(a) => {
873
				Ok(RelayCall::Hrmp(HrmpCall::AcceptOpenChannel(a.clone())).encode())
874
			}
875
			xcm_primitives::HrmpAvailableCalls::CloseChannel(a) => {
876
				Ok(RelayCall::Hrmp(HrmpCall::CloseChannel(a.clone())).encode())
877
			}
878
			xcm_primitives::HrmpAvailableCalls::CancelOpenRequest(a, b) => {
879
				Ok(RelayCall::Hrmp(HrmpCall::CancelOpenRequest(a.clone(), b.clone())).encode())
880
			}
881
		}
882
	}
883
}
884

            
885
parameter_types! {
886
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
887
}
888

            
889
impl pallet_ethereum::Config for Runtime {
890
	type StateRoot =
891
		pallet_ethereum::IntermediateStateRoot<<Runtime as frame_system::Config>::Version>;
892
	type PostLogContent = PostBlockAndTxnHashes;
893
	type ExtraDataLength = ConstU32<30>;
894
}
895
parameter_types! {
896
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 0);
897
}
898

            
899
#[derive(
900
	Copy,
901
	Clone,
902
	Eq,
903
	PartialEq,
904
	Ord,
905
	PartialOrd,
906
	Encode,
907
	Decode,
908
	Debug,
909
	MaxEncodedLen,
910
	TypeInfo,
911
	DecodeWithMemTracking,
912
)]
913
pub enum ProxyType {
914
	NotAllowed = 0,
915
	Any = 1,
916
}
917

            
918
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
919

            
920
impl InstanceFilter<RuntimeCall> for ProxyType {
921
	fn filter(&self, _c: &RuntimeCall) -> bool {
922
		match self {
923
			ProxyType::NotAllowed => false,
924
			ProxyType::Any => true,
925
		}
926
	}
927
	fn is_superset(&self, _o: &Self) -> bool {
928
		false
929
	}
930
}
931

            
932
impl Default for ProxyType {
933
	fn default() -> Self {
934
		Self::NotAllowed
935
	}
936
}
937

            
938
parameter_types! {
939
	pub const ProxyCost: u64 = 1;
940
}
941

            
942
impl pallet_proxy::Config for Runtime {
943
	type RuntimeEvent = RuntimeEvent;
944
	type RuntimeCall = RuntimeCall;
945
	type Currency = Balances;
946
	type ProxyType = ProxyType;
947
	type ProxyDepositBase = ProxyCost;
948
	type ProxyDepositFactor = ProxyCost;
949
	type MaxProxies = ConstU32<32>;
950
	type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
951
	type MaxPending = ConstU32<32>;
952
	type CallHasher = BlakeTwo256;
953
	type AnnouncementDepositBase = ProxyCost;
954
	type AnnouncementDepositFactor = ProxyCost;
955
	type BlockNumberProvider = ();
956
}
957

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

            
975
impl pallet_ethereum_xcm::Config for Runtime {
976
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
977
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
978
	type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
979
	type ReservedXcmpWeight = ReservedXcmpWeight;
980
	type EnsureProxy = EthereumXcmEnsureProxy;
981
	type ControllerOrigin = EnsureRoot<AccountId>;
982
	type ForceOrigin = EnsureRoot<AccountId>;
983
}
984

            
985
type Block = frame_system::mocking::MockBlockU32<Runtime>;
986

            
987
construct_runtime!(
988
	pub enum Runtime	{
989
		System: frame_system,
990
		Balances: pallet_balances,
991
		MsgQueue: mock_msg_queue,
992
		XcmVersioner: mock_version_changer,
993

            
994
		PolkadotXcm: pallet_xcm,
995
		CumulusXcm: cumulus_pallet_xcm,
996
		XcmTransactor: pallet_xcm_transactor,
997
		XcmWeightTrader: pallet_xcm_weight_trader,
998
		Treasury: pallet_treasury,
999
		Proxy: pallet_proxy,
		Timestamp: pallet_timestamp,
		EVM: pallet_evm,
		Ethereum: pallet_ethereum,
		EthereumXcm: pallet_ethereum_xcm,
		EvmForeignAssets: pallet_moonbeam_foreign_assets,
	}
);
7
pub(crate) fn para_events() -> Vec<RuntimeEvent> {
7
	System::events()
7
		.into_iter()
7
		.map(|r| r.event)
99
		.filter_map(|e| Some(e))
7
		.collect::<Vec<_>>()
7
}
use frame_support::traits::{Disabled, OnFinalize, OnInitialize, UncheckedOnRuntimeUpgrade};
use moonbase_runtime::{currency, xcm_config::LocationToH160};
use pallet_evm::FrameSystemAccountProvider;
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
}