1
// Copyright 2019-2022 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam 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
// Moonbeam 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 Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Test utilities
18
use super::*;
19
use cumulus_primitives_core::{relay_chain::HrmpChannelId, ParaId};
20
use frame_support::traits::{
21
	ConstU32, EnsureOrigin, Everything, Nothing, OriginTrait, PalletInfo as PalletInfoTrait,
22
};
23
use frame_support::{construct_runtime, parameter_types, weights::Weight};
24
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot};
25
use parity_scale_codec::{Decode, Encode};
26
use precompile_utils::{
27
	mock_account,
28
	precompile_set::*,
29
	testing::{AddressInPrefixedSet, MockAccount},
30
};
31
use scale_info::TypeInfo;
32
use sp_core::H256;
33
use sp_io;
34
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
35
use sp_runtime::BuildStorage;
36
use xcm::latest::{prelude::*, Error as XcmError};
37
use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds, IsConcrete};
38
use xcm_executor::{
39
	traits::{TransactAsset, WeightTrader},
40
	AssetsInHolding,
41
};
42

            
43
pub type AccountId = MockAccount;
44
pub type Balance = u128;
45
pub type AssetId = u128;
46

            
47
type Block = frame_system::mocking::MockBlockU32<Runtime>;
48

            
49
// Configure a mock runtime to test the pallet.
50
425
construct_runtime!(
51
	pub enum Runtime {
52
		System: frame_system,
53
		Balances: pallet_balances,
54
		Evm: pallet_evm,
55
		Timestamp: pallet_timestamp,
56
		PolkadotXcm: pallet_xcm,
57
		XcmTransactor: pallet_xcm_transactor,
58
	}
59
571
);
60

            
61
28
mock_account!(AssetAccount(u128), |v: AssetAccount| AddressInPrefixedSet(
62
28
	0xffffffff, v.0
63
28
)
64
28
.into());
65
2
mock_account!(SelfReserveAccount, |_| MockAccount::from_u64(2));
66

            
67
parameter_types! {
68
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
69
}
70

            
71
parameter_types! {
72
	pub const BlockHashCount: u32 = 250;
73
	pub const SS58Prefix: u8 = 42;
74
}
75
impl frame_system::Config for Runtime {
76
	type BaseCallFilter = Everything;
77
	type DbWeight = ();
78
	type RuntimeOrigin = RuntimeOrigin;
79
	type RuntimeTask = RuntimeTask;
80
	type Nonce = u64;
81
	type Block = Block;
82
	type RuntimeCall = RuntimeCall;
83
	type Hash = H256;
84
	type Hashing = BlakeTwo256;
85
	type AccountId = AccountId;
86
	type Lookup = IdentityLookup<Self::AccountId>;
87
	type RuntimeEvent = RuntimeEvent;
88
	type BlockHashCount = BlockHashCount;
89
	type Version = ();
90
	type PalletInfo = PalletInfo;
91
	type AccountData = pallet_balances::AccountData<Balance>;
92
	type OnNewAccount = ();
93
	type OnKilledAccount = ();
94
	type SystemWeightInfo = ();
95
	type BlockWeights = ();
96
	type BlockLength = ();
97
	type SS58Prefix = SS58Prefix;
98
	type OnSetCode = ();
99
	type MaxConsumers = frame_support::traits::ConstU32<16>;
100
	type SingleBlockMigrations = ();
101
	type MultiBlockMigrator = ();
102
	type PreInherents = ();
103
	type PostInherents = ();
104
	type PostTransactions = ();
105
}
106
parameter_types! {
107
	pub const ExistentialDeposit: u128 = 0;
108
}
109
impl pallet_balances::Config for Runtime {
110
	type MaxReserves = ();
111
	type ReserveIdentifier = ();
112
	type MaxLocks = ();
113
	type Balance = Balance;
114
	type RuntimeEvent = RuntimeEvent;
115
	type DustRemoval = ();
116
	type ExistentialDeposit = ExistentialDeposit;
117
	type AccountStore = System;
118
	type WeightInfo = ();
119
	type RuntimeHoldReason = ();
120
	type FreezeIdentifier = ();
121
	type MaxFreezes = ();
122
	type RuntimeFreezeReason = ();
123
}
124

            
125
// These parameters dont matter much as this will only be called by root with the forced arguments
126
// No deposit is substracted with those methods
127
parameter_types! {
128
	pub const AssetDeposit: Balance = 0;
129
	pub const ApprovalDeposit: Balance = 0;
130
	pub const AssetsStringLimit: u32 = 50;
131
	pub const MetadataDepositBase: Balance = 0;
132
	pub const MetadataDepositPerByte: Balance = 0;
133
}
134

            
135
pub type Precompiles<R> =
136
	PrecompileSetBuilder<R, (PrecompileAt<AddressU64<1>, XtokensPrecompile<R>>,)>;
137

            
138
pub type PCall = XtokensPrecompileCall<Runtime>;
139

            
140
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
141
/// Block storage limit in bytes. Set to 40 KB.
142
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
143

            
144
parameter_types! {
145
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
146
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
147
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
148
	pub GasLimitPovSizeRatio: u64 = {
149
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
150
		block_gas_limit.saturating_div(MAX_POV_SIZE)
151
	};
152
	pub GasLimitStorageGrowthRatio: u64 = {
153
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
154
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
155
	};
156
}
157

            
158
impl pallet_evm::Config for Runtime {
159
	type FeeCalculator = ();
160
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
161
	type WeightPerGas = WeightPerGas;
162
	type CallOrigin = EnsureAddressRoot<AccountId>;
163
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
164
	type AddressMapping = AccountId;
165
	type Currency = Balances;
166
	type RuntimeEvent = RuntimeEvent;
167
	type Runner = pallet_evm::runner::stack::Runner<Self>;
168
	type PrecompilesType = Precompiles<Self>;
169
	type PrecompilesValue = PrecompilesValue;
170
	type ChainId = ();
171
	type OnChargeTransaction = ();
172
	type BlockGasLimit = BlockGasLimit;
173
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
174
	type FindAuthor = ();
175
	type OnCreate = ();
176
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
177
	type SuicideQuickClearLimit = ConstU32<0>;
178
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
179
	type Timestamp = Timestamp;
180
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
181
}
182

            
183
parameter_types! {
184
	pub const MinimumPeriod: u64 = 5;
185
}
186
impl pallet_timestamp::Config for Runtime {
187
	type Moment = u64;
188
	type OnTimestampSet = ();
189
	type MinimumPeriod = MinimumPeriod;
190
	type WeightInfo = ();
191
}
192
pub struct ConvertOriginToLocal;
193
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
194
	type Success = Location;
195

            
196
13
	fn try_origin(_: Origin) -> Result<Location, Origin> {
197
13
		Ok(Location::here())
198
13
	}
199

            
200
	#[cfg(feature = "runtime-benchmarks")]
201
	fn try_successful_origin() -> Result<Origin, ()> {
202
		Ok(Origin::root())
203
	}
204
}
205

            
206
pub struct DoNothingRouter;
207
impl SendXcm for DoNothingRouter {
208
	type Ticket = ();
209

            
210
13
	fn validate(
211
13
		_destination: &mut Option<Location>,
212
13
		_message: &mut Option<Xcm<()>>,
213
13
	) -> SendResult<Self::Ticket> {
214
13
		Ok(((), Assets::new()))
215
13
	}
216

            
217
13
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
218
13
		Ok(XcmHash::default())
219
13
	}
220
}
221

            
222
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
223

            
224
pub struct DummyAssetTransactor;
225
impl TransactAsset for DummyAssetTransactor {
226
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
227
		Ok(())
228
	}
229

            
230
15
	fn withdraw_asset(
231
15
		_what: &Asset,
232
15
		_who: &Location,
233
15
		_maybe_context: Option<&XcmContext>,
234
15
	) -> Result<AssetsInHolding, XcmError> {
235
15
		Ok(AssetsInHolding::default())
236
15
	}
237
}
238

            
239
pub struct DummyWeightTrader;
240
impl WeightTrader for DummyWeightTrader {
241
13
	fn new() -> Self {
242
13
		DummyWeightTrader
243
13
	}
244

            
245
	fn buy_weight(
246
		&mut self,
247
		_weight: Weight,
248
		_payment: AssetsInHolding,
249
		_context: &XcmContext,
250
	) -> Result<AssetsInHolding, XcmError> {
251
		Ok(AssetsInHolding::default())
252
	}
253
}
254

            
255
parameter_types! {
256
	pub UniversalLocation: InteriorLocation = Here;
257
	pub MatcherLocation: Location = Location::here();
258
	pub const MaxAssetsIntoHolding: u32 = 64;
259
}
260

            
261
impl pallet_xcm::Config for Runtime {
262
	// The config types here are entirely configurable, since the only one that is sorely needed
263
	// is `XcmExecutor`, which will be used in unit tests located in xcm-executor.
264
	type RuntimeEvent = RuntimeEvent;
265
	type ExecuteXcmOrigin = ConvertOriginToLocal;
266
	type UniversalLocation = UniversalLocation;
267
	type SendXcmOrigin = ConvertOriginToLocal;
268
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
269
	type XcmRouter = DoNothingRouter;
270
	type XcmExecuteFilter = frame_support::traits::Everything;
271
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
272
	type XcmTeleportFilter = frame_support::traits::Everything;
273
	type XcmReserveTransferFilter = frame_support::traits::Everything;
274
	type RuntimeOrigin = RuntimeOrigin;
275
	type RuntimeCall = RuntimeCall;
276
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
277
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
278
	type Currency = Balances;
279
	type CurrencyMatcher = IsConcrete<MatcherLocation>;
280
	type TrustedLockers = ();
281
	type SovereignAccountOf = ();
282
	type MaxLockers = ConstU32<8>;
283
	type WeightInfo = pallet_xcm::TestWeightInfo;
284
	type MaxRemoteLockConsumers = ConstU32<0>;
285
	type RemoteLockConsumerIdentifier = ();
286
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
287
}
288

            
289
#[derive(Encode, Decode)]
290
pub enum RelayCall {
291
	#[codec(index = 5u8)]
292
	// the index should match the position of the module in `construct_runtime!`
293
	Utility(UtilityCall),
294
	#[codec(index = 6u8)]
295
	// the index should match the position of the module in `construct_runtime!`
296
	Hrmp(HrmpCall),
297
}
298

            
299
#[derive(Encode, Decode)]
300
pub enum UtilityCall {
301
	#[codec(index = 1u8)]
302
	AsDerivative(u16),
303
}
304

            
305
// HRMP call encoding, needed for xcm transactor pallet
306
#[derive(Encode, Decode)]
307
pub enum HrmpCall {
308
	#[codec(index = 0u8)]
309
	InitOpenChannel(ParaId, u32, u32),
310
	#[codec(index = 1u8)]
311
	AcceptOpenChannel(ParaId),
312
	#[codec(index = 2u8)]
313
	CloseChannel(HrmpChannelId),
314
	#[codec(index = 6u8)]
315
	CancelOpenRequest(HrmpChannelId, u32),
316
}
317

            
318
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
319
pub enum MockTransactors {
320
	Relay,
321
}
322

            
323
impl xcm_primitives::XcmTransact for MockTransactors {
324
	fn destination(self) -> Location {
325
		match self {
326
			MockTransactors::Relay => Location::parent(),
327
		}
328
	}
329
}
330

            
331
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
332
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
333
		match self {
334
			MockTransactors::Relay => match call {
335
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
336
					let mut call =
337
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
338
					call.append(&mut b.clone());
339
					call
340
				}
341
			},
342
		}
343
	}
344
}
345

            
346
parameter_types! {
347
	pub SelfLocationAbsolute: Location = Location {
348
		parents: 1,
349
		interior: [Parachain(ParachainId::get().into())].into(),
350
	};
351
}
352

            
353
impl pallet_xcm_transactor::Config for Runtime {
354
	type RuntimeEvent = RuntimeEvent;
355
	type Balance = Balance;
356
	type Transactor = MockTransactors;
357
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
358
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
359
	type CurrencyId = CurrencyId;
360
	type AccountIdToLocation = AccountIdToLocation;
361
	type CurrencyIdToLocation = CurrencyIdToMultiLocation;
362
	type SelfLocation = SelfLocation;
363
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
364
	type UniversalLocation = UniversalLocation;
365
	type BaseXcmWeight = BaseXcmWeight;
366
	type XcmSender = DoNothingRouter;
367
	type AssetTransactor = DummyAssetTransactor;
368
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
369
	type WeightInfo = ();
370
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
371
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
372
	type MaxHrmpFee = ();
373
}
374

            
375
pub struct XcmConfig;
376
impl xcm_executor::Config for XcmConfig {
377
	type RuntimeCall = RuntimeCall;
378
	type XcmSender = DoNothingRouter;
379
	type AssetTransactor = DummyAssetTransactor;
380
	type OriginConverter = pallet_xcm::XcmPassthrough<RuntimeOrigin>;
381
	type IsReserve = xcm_primitives::MultiNativeAsset<xcm_primitives::RelativeReserveProvider>;
382
	type IsTeleporter = ();
383
	type UniversalLocation = UniversalLocation;
384
	type Barrier = Barrier;
385
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
386
	type Trader = DummyWeightTrader;
387
	type ResponseHandler = ();
388
	type SubscriptionService = ();
389
	type AssetTrap = ();
390
	type AssetClaims = ();
391
	type CallDispatcher = RuntimeCall;
392
	type AssetLocker = ();
393
	type AssetExchanger = ();
394
	type PalletInstancesInfo = ();
395
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
396
	type FeeManager = ();
397
	type MessageExporter = ();
398
	type UniversalAliases = Nothing;
399
	type SafeCallFilter = Everything;
400
	type Aliasers = Nothing;
401
	type TransactionalProcessor = ();
402
	type HrmpNewChannelOpenRequestHandler = ();
403
	type HrmpChannelAcceptedHandler = ();
404
	type HrmpChannelClosingHandler = ();
405
	type XcmRecorder = ();
406
}
407

            
408
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
409
pub enum CurrencyId {
410
	SelfReserve,
411
	OtherReserve(AssetId),
412
}
413

            
414
// Implement the trait, where we convert AccountId to AssetID
415
impl AccountIdToCurrencyId<AccountId, CurrencyId> for Runtime {
416
	/// The way to convert an account to assetId is by ensuring that the prefix is 0XFFFFFFFF
417
	/// and by taking the lowest 128 bits as the assetId
418
8
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
419
8
		match account {
420
8
			a if a.has_prefix_u32(0xffffffff) => Some(CurrencyId::OtherReserve(a.without_prefix())),
421
1
			a if a == AccountId::from(SelfReserveAccount) => Some(CurrencyId::SelfReserve),
422
			_ => None,
423
		}
424
8
	}
425
}
426

            
427
pub struct CurrencyIdToMultiLocation;
428

            
429
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToMultiLocation {
430
8
	fn convert(currency: CurrencyId) -> Option<Location> {
431
8
		match currency {
432
			CurrencyId::SelfReserve => {
433
1
				let multi: Location = SelfReserve::get();
434
1
				Some(multi)
435
			}
436
			// To distinguish between relay and others, specially for reserve asset
437
7
			CurrencyId::OtherReserve(asset) => {
438
7
				if asset == 0 {
439
3
					Some(Location::parent())
440
				} else {
441
4
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
442
				}
443
			}
444
		}
445
8
	}
446
}
447

            
448
pub struct AccountIdToLocation;
449
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
450
	fn convert(account: AccountId) -> Location {
451
		let as_h160: H160 = account.into();
452
		Location::new(
453
			1,
454
			[AccountKey20 {
455
				network: None,
456
				key: as_h160.as_fixed_bytes().clone(),
457
			}],
458
		)
459
	}
460
}
461

            
462
parameter_types! {
463
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
464

            
465
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
466
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
467
	pub const MaxAssetsForTransfer: usize = 2;
468

            
469
	pub SelfLocation: Location =
470
		Location::new(1, [Parachain(ParachainId::get().into())]);
471

            
472
	pub SelfReserve: Location = Location::new(
473
		1,
474
		[
475
			Parachain(ParachainId::get().into()),
476
			PalletInstance(
477
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
478
			)
479
		]);
480
	pub MaxInstructions: u32 = 100;
481
}
482

            
483
pub(crate) struct ExtBuilder {
484
	// endowed accounts with balances
485
	balances: Vec<(AccountId, Balance)>,
486
}
487

            
488
impl Default for ExtBuilder {
489
19
	fn default() -> ExtBuilder {
490
19
		ExtBuilder { balances: vec![] }
491
19
	}
492
}
493

            
494
impl ExtBuilder {
495
16
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
496
16
		self.balances = balances;
497
16
		self
498
16
	}
499
19
	pub(crate) fn build(self) -> sp_io::TestExternalities {
500
19
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
501
19
			.build_storage()
502
19
			.expect("Frame system builds valid default genesis config");
503
19

            
504
19
		pallet_balances::GenesisConfig::<Runtime> {
505
19
			balances: self.balances,
506
19
		}
507
19
		.assimilate_storage(&mut t)
508
19
		.expect("Pallet balances storage can be assimilated");
509
19

            
510
19
		let mut ext = sp_io::TestExternalities::new(t);
511
19
		ext.execute_with(|| System::set_block_number(1));
512
19
		ext
513
19
	}
514
}
515

            
516
14
pub(crate) fn events() -> Vec<RuntimeEvent> {
517
14
	System::events()
518
14
		.into_iter()
519
20
		.map(|r| r.event)
520
14
		.collect::<Vec<_>>()
521
14
}