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
	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::{mock_account, precompile_set::*, testing::MockAccount};
27
use scale_info::TypeInfo;
28
use sp_core::H256;
29
use sp_runtime::BuildStorage;
30
use sp_runtime::{
31
	traits::{BlakeTwo256, IdentityLookup},
32
	Perbill,
33
};
34
use xcm::latest::{prelude::*, Error as XcmError};
35
use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds};
36
use xcm_executor::{
37
	traits::{TransactAsset, WeightTrader},
38
	AssetsInHolding,
39
};
40

            
41
pub type AccountId = MockAccount;
42
pub type Balance = u128;
43
pub type AssetId = u128;
44
type XcmV2Weight = u64;
45

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

            
48
53
construct_runtime!(
49
	pub enum Runtime	{
50
		System: frame_system,
51
		Balances: pallet_balances,
52
		Evm: pallet_evm,
53
		Timestamp: pallet_timestamp,
54
		PolkadotXcm: pallet_xcm,
55
		XcmTransactor: pallet_xcm_transactor,
56
	}
57
88
);
58

            
59
mock_account!(SelfReserveAccount, |_| MockAccount::from_u64(2));
60

            
61
parameter_types! {
62
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
63
	pub UniversalLocation: InteriorLocation = RelayNetwork::get().into();
64
}
65

            
66
parameter_types! {
67
	pub const BlockHashCount: u32 = 250;
68
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
69
	pub const MaximumBlockLength: u32 = 2 * 1024;
70
	pub const AvailableBlockRatio: Perbill = Perbill::one();
71
	pub const SS58Prefix: u8 = 42;
72
}
73

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

            
124
pub struct DoNothingRouter;
125
impl SendXcm for DoNothingRouter {
126
	type Ticket = ();
127

            
128
	fn validate(
129
		_destination: &mut Option<Location>,
130
		_message: &mut Option<Xcm<()>>,
131
	) -> SendResult<Self::Ticket> {
132
		Ok(((), Assets::new()))
133
	}
134

            
135
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
136
		Ok(XcmHash::default())
137
	}
138
}
139

            
140
impl pallet_xcm::Config for Runtime {
141
	type RuntimeEvent = RuntimeEvent;
142
	type ExecuteXcmOrigin = ConvertOriginToLocal;
143
	type XcmExecuteFilter = Everything;
144
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
145
	type XcmRouter = DoNothingRouter;
146
	type SendXcmOrigin = ConvertOriginToLocal;
147
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
148
	type UniversalLocation = UniversalLocation;
149
	type XcmTeleportFilter = frame_support::traits::Everything;
150
	type XcmReserveTransferFilter = frame_support::traits::Everything;
151
	type RuntimeOrigin = RuntimeOrigin;
152
	type RuntimeCall = RuntimeCall;
153
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
154
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
155
	type Currency = Balances;
156
	type CurrencyMatcher = ();
157
	type TrustedLockers = ();
158
	type SovereignAccountOf = ();
159
	type MaxLockers = ConstU32<8>;
160
	type WeightInfo = pallet_xcm::TestWeightInfo;
161
	type MaxRemoteLockConsumers = ConstU32<0>;
162
	type RemoteLockConsumerIdentifier = ();
163
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
164
}
165

            
166
parameter_types! {
167
	pub const MaxAssetsIntoHolding: u32 = 64;
168
}
169

            
170
pub struct XcmConfig;
171
impl xcm_executor::Config for XcmConfig {
172
	type RuntimeCall = RuntimeCall;
173
	type AssetTransactor = DummyAssetTransactor;
174
	type OriginConverter = pallet_xcm::XcmPassthrough<RuntimeOrigin>;
175
	type IsReserve = ();
176
	type IsTeleporter = ();
177
	type Barrier = Barrier;
178
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
179
	type Trader = DummyWeightTrader;
180
	type ResponseHandler = ();
181
	type SubscriptionService = ();
182
	type AssetTrap = ();
183
	type AssetClaims = ();
184
	type CallDispatcher = RuntimeCall;
185
	type XcmSender = DoNothingRouter;
186
	type UniversalLocation = UniversalLocation;
187
	type AssetLocker = ();
188
	type AssetExchanger = ();
189
	type PalletInstancesInfo = ();
190
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
191
	type FeeManager = ();
192
	type MessageExporter = ();
193
	type UniversalAliases = Nothing;
194
	type SafeCallFilter = Everything;
195
	type Aliasers = Nothing;
196
	type TransactionalProcessor = ();
197
	type HrmpNewChannelOpenRequestHandler = ();
198
	type HrmpChannelAcceptedHandler = ();
199
	type HrmpChannelClosingHandler = ();
200
	type XcmRecorder = ();
201
}
202

            
203
pub type Precompiles<R> = PrecompileSetBuilder<
204
	R,
205
	(
206
		PrecompileAt<AddressU64<1>, GmpPrecompile<R>, (SubcallWithMaxNesting<1>,)>,
207
		RevertPrecompile<AddressU64<2>>,
208
	),
209
>;
210

            
211
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
212

            
213
pub struct DummyAssetTransactor;
214
impl TransactAsset for DummyAssetTransactor {
215
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
216
		Ok(())
217
	}
218

            
219
	fn withdraw_asset(
220
		_what: &Asset,
221
		_who: &Location,
222
		_maybe_context: Option<&XcmContext>,
223
	) -> Result<AssetsInHolding, XcmError> {
224
		Ok(AssetsInHolding::default())
225
	}
226
}
227

            
228
pub struct DummyWeightTrader;
229
impl WeightTrader for DummyWeightTrader {
230
	fn new() -> Self {
231
		DummyWeightTrader
232
	}
233

            
234
	fn buy_weight(
235
		&mut self,
236
		_weight: Weight,
237
		_payment: AssetsInHolding,
238
		_context: &XcmContext,
239
	) -> Result<AssetsInHolding, XcmError> {
240
		Ok(AssetsInHolding::default())
241
	}
242
}
243

            
244
pub type PCall = GmpPrecompileCall<Runtime>;
245

            
246
mock_account!(Batch, |_| MockAccount::from_u64(1));
247
mock_account!(Revert, |_| MockAccount::from_u64(2));
248

            
249
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
250
/// Block storage limit in bytes. Set to 40 KB.
251
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
252

            
253
parameter_types! {
254
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
255
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
256
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
257
	pub GasLimitPovSizeRatio: u64 = {
258
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
259
		block_gas_limit.saturating_div(MAX_POV_SIZE)
260
	};
261
	pub GasLimitStorageGrowthRatio: u64 = {
262
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
263
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
264
	};
265
}
266

            
267
impl pallet_evm::Config for Runtime {
268
	type FeeCalculator = ();
269
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
270
	type WeightPerGas = WeightPerGas;
271
	type CallOrigin = EnsureAddressRoot<AccountId>;
272
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
273
	type AddressMapping = AccountId;
274
	type Currency = Balances;
275
	type RuntimeEvent = RuntimeEvent;
276
	type Runner = pallet_evm::runner::stack::Runner<Self>;
277
	type PrecompilesType = Precompiles<Runtime>;
278
	type PrecompilesValue = PrecompilesValue;
279
	type ChainId = ();
280
	type OnChargeTransaction = ();
281
	type BlockGasLimit = BlockGasLimit;
282
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
283
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
284
	type FindAuthor = ();
285
	type OnCreate = ();
286
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
287
	type SuicideQuickClearLimit = ConstU32<0>;
288
	type Timestamp = Timestamp;
289
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
290
}
291

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

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

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

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

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

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

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

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

            
378
parameter_types! {
379
	pub const MinimumPeriod: u64 = 5;
380
}
381
impl pallet_timestamp::Config for Runtime {
382
	type Moment = u64;
383
	type OnTimestampSet = ();
384
	type MinimumPeriod = MinimumPeriod;
385
	type WeightInfo = ();
386
}
387

            
388
pub struct ConvertOriginToLocal;
389
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
390
	type Success = Location;
391

            
392
	fn try_origin(_: Origin) -> Result<Location, Origin> {
393
		Ok(Location::here())
394
	}
395

            
396
	#[cfg(feature = "runtime-benchmarks")]
397
	fn try_successful_origin() -> Result<Origin, ()> {
398
		Ok(Origin::root())
399
	}
400
}
401

            
402
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
403
pub enum CurrencyId {
404
	SelfReserve,
405
	OtherReserve(AssetId),
406
}
407

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

            
421
pub struct AccountIdToLocation;
422
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
423
	fn convert(account: AccountId) -> Location {
424
		let as_h160: H160 = account.into();
425
		Location::new(
426
			1,
427
			[AccountKey20 {
428
				network: None,
429
				key: as_h160.as_fixed_bytes().clone(),
430
			}],
431
		)
432
	}
433
}
434

            
435
parameter_types! {
436
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
437

            
438
	pub const BaseXcmWeight: XcmV2Weight = 1000;
439
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
440
	pub const MaxAssetsForTransfer: usize = 2;
441

            
442
	pub SelfLocation: Location =
443
		Location::new(1, [Parachain(ParachainId::get().into())]);
444

            
445
	pub SelfReserve: Location = Location::new(
446
		1,
447
		[
448
			Parachain(ParachainId::get().into()),
449
			PalletInstance(
450
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
451
			)
452
		]);
453
	pub MaxInstructions: u32 = 100;
454
}
455

            
456
pub struct CurrencyIdToMultiLocation;
457

            
458
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToMultiLocation {
459
	fn convert(currency: CurrencyId) -> Option<Location> {
460
		match currency {
461
			CurrencyId::SelfReserve => {
462
				let multi: Location = SelfReserve::get();
463
				Some(multi)
464
			}
465
			// To distinguish between relay and others, specially for reserve asset
466
			CurrencyId::OtherReserve(asset) => {
467
				if asset == 0 {
468
					Some(Location::parent())
469
				} else {
470
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
471
				}
472
			}
473
		}
474
	}
475
}
476

            
477
pub(crate) struct ExtBuilder {
478
	/// Endowed accounts with balances
479
	balances: Vec<(AccountId, Balance)>,
480
}
481

            
482
impl Default for ExtBuilder {
483
3
	fn default() -> ExtBuilder {
484
3
		ExtBuilder { balances: vec![] }
485
3
	}
486
}
487

            
488
impl ExtBuilder {
489
	/// Fund some accounts before starting the test
490
3
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
491
3
		self.balances = balances;
492
3
		self
493
3
	}
494

            
495
	/// Build the test externalities for use in tests
496
3
	pub(crate) fn build(self) -> sp_io::TestExternalities {
497
3
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
498
3
			.build_storage()
499
3
			.expect("Frame system builds valid default genesis config");
500
3

            
501
3
		pallet_balances::GenesisConfig::<Runtime> {
502
3
			balances: self.balances.clone(),
503
3
		}
504
3
		.assimilate_storage(&mut t)
505
3
		.expect("Pallet balances storage can be assimilated");
506
3

            
507
3
		let mut ext = sp_io::TestExternalities::new(t);
508
3
		ext.execute_with(|| {
509
3
			System::set_block_number(1);
510
3
		});
511
3
		ext
512
3
	}
513
}