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

            
19
use super::*;
20
use crate as pallet_xcm_transactor;
21
use cumulus_primitives_core::Assets;
22
use frame_support::traits::PalletInfo as PalletInfoTrait;
23
use frame_support::{construct_runtime, parameter_types, weights::Weight};
24
use frame_system::EnsureRoot;
25
use parity_scale_codec::{Decode, Encode};
26

            
27
use sp_core::{H160, H256};
28
use sp_io;
29
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
30
use sp_runtime::BuildStorage;
31
use xcm::latest::{
32
	opaque, Asset, Error as XcmError, Instruction, InteriorLocation,
33
	Junction::{AccountKey20, GlobalConsensus, PalletInstance, Parachain},
34
	Location, NetworkId, Result as XcmResult, SendError, SendResult, SendXcm, Xcm, XcmContext,
35
	XcmHash,
36
};
37
use xcm::{IntoVersion, VersionedXcm, WrapVersion};
38
use xcm_primitives::{UtilityAvailableCalls, UtilityEncodeCall, XcmTransact};
39

            
40
use sp_std::cell::RefCell;
41
use xcm_executor::{
42
	traits::{TransactAsset, WeightBounds, WeightTrader},
43
	AssetsInHolding,
44
};
45
type Block = frame_system::mocking::MockBlock<Test>;
46

            
47
// Configure a mock runtime to test the pallet.
48
710
construct_runtime!(
49
	pub enum Test
50
	{
51
		System: frame_system,
52
		Balances: pallet_balances,
53
		Timestamp: pallet_timestamp,
54
		XcmTransactor: pallet_xcm_transactor,
55
	}
56
1239
);
57

            
58
pub type Balance = u128;
59
pub type AccountId = u64;
60

            
61
parameter_types! {
62
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
63
}
64
parameter_types! {
65
	pub const BlockHashCount: u32 = 250;
66
	pub BlockWeights: frame_system::limits::BlockWeights =
67
		frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, 1));
68
}
69

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

            
120
parameter_types! {
121
	pub const MinimumPeriod: u64 = 5;
122
}
123

            
124
impl pallet_timestamp::Config for Test {
125
	type Moment = u64;
126
	type OnTimestampSet = ();
127
	type MinimumPeriod = MinimumPeriod;
128
	type WeightInfo = ();
129
}
130

            
131
const XCM_VERSION_ROOT_KEY: &'static [u8] = b"XCM_VERSION_ROOT_KEY";
132

            
133
pub struct CustomVersionWrapper;
134
impl WrapVersion for CustomVersionWrapper {
135
17
	fn wrap_version<RuntimeCall>(
136
17
		_dest: &xcm::latest::Location,
137
17
		xcm: impl Into<VersionedXcm<RuntimeCall>>,
138
17
	) -> Result<VersionedXcm<RuntimeCall>, ()> {
139
17
		let xcm_version: u32 =
140
17
			frame_support::storage::unhashed::get(XCM_VERSION_ROOT_KEY).unwrap_or(2);
141
17
		let xcm_converted = xcm.into().into_version(xcm_version)?;
142
16
		Ok(xcm_converted)
143
17
	}
144
}
145

            
146
impl CustomVersionWrapper {
147
3
	pub fn set_version(version: u32) {
148
3
		frame_support::storage::unhashed::put(XCM_VERSION_ROOT_KEY, &version);
149
3
	}
150
}
151

            
152
pub struct DoNothingRouter;
153
impl SendXcm for DoNothingRouter {
154
	type Ticket = ();
155

            
156
	fn validate(
157
		_destination: &mut Option<Location>,
158
		_message: &mut Option<opaque::Xcm>,
159
	) -> SendResult<Self::Ticket> {
160
		Ok(((), Assets::new()))
161
	}
162

            
163
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
164
		Ok(XcmHash::default())
165
	}
166
}
167

            
168
pub struct DummyAssetTransactor;
169
impl TransactAsset for DummyAssetTransactor {
170
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
171
		Ok(())
172
	}
173

            
174
6
	fn withdraw_asset(
175
6
		_what: &Asset,
176
6
		_who: &Location,
177
6
		_context: Option<&XcmContext>,
178
6
	) -> Result<AssetsInHolding, XcmError> {
179
6
		Ok(AssetsInHolding::default())
180
6
	}
181
}
182

            
183
pub struct DummyWeightTrader;
184
impl WeightTrader for DummyWeightTrader {
185
	fn new() -> Self {
186
		DummyWeightTrader
187
	}
188

            
189
	fn buy_weight(
190
		&mut self,
191
		_weight: Weight,
192
		_payment: AssetsInHolding,
193
		_context: &XcmContext,
194
	) -> Result<AssetsInHolding, XcmError> {
195
		Ok(AssetsInHolding::default())
196
	}
197
}
198

            
199
use sp_std::marker::PhantomData;
200
pub struct DummyWeigher<C>(PhantomData<C>);
201

            
202
impl<C: Decode> WeightBounds<C> for DummyWeigher<C> {
203
	fn weight(_message: &mut Xcm<C>) -> Result<Weight, ()> {
204
		Ok(Weight::zero())
205
	}
206
	fn instr_weight(_instruction: &Instruction<C>) -> Result<Weight, ()> {
207
		Ok(Weight::zero())
208
	}
209
}
210

            
211
pub struct AccountIdToLocation;
212
impl sp_runtime::traits::Convert<u64, Location> for AccountIdToLocation {
213
11
	fn convert(_account: u64) -> Location {
214
11
		let as_h160: H160 = H160::repeat_byte(0xAA);
215
11
		Location::new(
216
11
			0,
217
11
			[AccountKey20 {
218
11
				network: None,
219
11
				key: as_h160.as_fixed_bytes().clone(),
220
11
			}],
221
11
		)
222
11
	}
223
}
224

            
225
parameter_types! {
226
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
227

            
228
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
229
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
230

            
231
	pub SelfLocation: Location = Location::here();
232

            
233
	pub SelfReserve: Location = Location::new(
234
		1,
235
		[
236
			Parachain(ParachainId::get().into()),
237
			PalletInstance(
238
				<Test as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
239
			)
240
		]);
241
	pub MaxInstructions: u32 = 100;
242

            
243
	pub UniversalLocation: InteriorLocation =
244
		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainId::get().into())].into();
245
}
246

            
247
#[derive(Encode, Decode)]
248
pub enum RelayCall {
249
	#[codec(index = 0u8)]
250
	// the index should match the position of the module in `construct_runtime!`
251
	Utility(UtilityCall),
252
	#[codec(index = 1u8)]
253
	// the index should match the position of the module in `construct_runtime!`
254
	Hrmp(HrmpCall),
255
}
256

            
257
#[derive(Encode, Decode)]
258
pub enum UtilityCall {
259
	#[codec(index = 0u8)]
260
	AsDerivative(u16),
261
}
262

            
263
#[derive(Encode, Decode)]
264
pub enum HrmpCall {
265
	#[codec(index = 0u8)]
266
	Init(),
267
	#[codec(index = 1u8)]
268
	Accept(),
269
	#[codec(index = 2u8)]
270
	Close(),
271
	#[codec(index = 6u8)]
272
	Cancel(),
273
}
274

            
275
// Transactors for the mock runtime. Only relay chain
276
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, scale_info::TypeInfo)]
277
pub enum Transactors {
278
	Relay,
279
}
280

            
281
#[cfg(feature = "runtime-benchmarks")]
282
impl Default for Transactors {
283
	fn default() -> Self {
284
		Transactors::Relay
285
	}
286
}
287

            
288
impl XcmTransact for Transactors {
289
9
	fn destination(self) -> Location {
290
9
		match self {
291
9
			Transactors::Relay => Location::parent(),
292
9
		}
293
9
	}
294
}
295

            
296
impl UtilityEncodeCall for Transactors {
297
14
	fn encode_call(self, call: UtilityAvailableCalls) -> Vec<u8> {
298
14
		match self {
299
14
			Transactors::Relay => match call {
300
14
				UtilityAvailableCalls::AsDerivative(a, b) => {
301
14
					let mut call =
302
14
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
303
14
					call.append(&mut b.clone());
304
14
					call
305
14
				}
306
14
			},
307
14
		}
308
14
	}
309
}
310

            
311
pub type AssetId = u128;
312
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, scale_info::TypeInfo)]
313
pub enum CurrencyId {
314
	SelfReserve,
315
	OtherReserve(AssetId),
316
}
317

            
318
pub struct CurrencyIdToLocation;
319

            
320
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToLocation {
321
11
	fn convert(currency: CurrencyId) -> Option<Location> {
322
11
		match currency {
323
			CurrencyId::SelfReserve => {
324
				let multi: Location = SelfReserve::get();
325
				Some(multi)
326
			}
327
			// To distinguish between relay and others, specially for reserve asset
328
11
			CurrencyId::OtherReserve(asset) => {
329
11
				if asset == 0 {
330
11
					Some(Location::parent())
331
				} else {
332
					Some(Location::new(1, [Parachain(2)]))
333
				}
334
			}
335
		}
336
11
	}
337
}
338

            
339
#[cfg(feature = "runtime-benchmarks")]
340
impl From<Location> for CurrencyId {
341
	fn from(location: Location) -> CurrencyId {
342
		if location == SelfReserve::get() {
343
			CurrencyId::SelfReserve
344
		} else if location == Location::parent() {
345
			CurrencyId::OtherReserve(0)
346
		} else {
347
			CurrencyId::OtherReserve(1)
348
		}
349
	}
350
}
351

            
352
// Simulates sending a XCM message
353
17
thread_local! {
354
17
	pub static SENT_XCM: RefCell<Vec<(Location, opaque::Xcm)>> = RefCell::new(Vec::new());
355
17
}
356
13
pub fn sent_xcm() -> Vec<(Location, opaque::Xcm)> {
357
13
	SENT_XCM.with(|q| (*q.borrow()).clone())
358
13
}
359
pub struct TestSendXcm;
360
impl SendXcm for TestSendXcm {
361
	type Ticket = ();
362

            
363
17
	fn validate(
364
17
		destination: &mut Option<Location>,
365
17
		message: &mut Option<opaque::Xcm>,
366
17
	) -> SendResult<Self::Ticket> {
367
17
		SENT_XCM.with(|q| {
368
17
			q.borrow_mut()
369
17
				.push((destination.clone().unwrap(), message.clone().unwrap()))
370
17
		});
371
17
		CustomVersionWrapper::wrap_version(&destination.clone().unwrap(), message.clone().unwrap())
372
17
			.map_err(|()| SendError::DestinationUnsupported)?;
373
16
		Ok(((), Assets::new()))
374
17
	}
375

            
376
16
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
377
16
		Ok(XcmHash::default())
378
16
	}
379
}
380

            
381
parameter_types! {
382
	pub MaxFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
383
	pub SelfLocationAbsolute: Location = Location {
384
		parents: 1,
385
		interior: [Parachain(ParachainId::get().into())].into(),
386
	};
387
}
388
pub type MaxHrmpRelayFee = xcm_builder::Case<MaxFee>;
389

            
390
impl Config for Test {
391
	type RuntimeEvent = RuntimeEvent;
392
	type Balance = Balance;
393
	type Transactor = Transactors;
394
	type DerivativeAddressRegistrationOrigin = EnsureRoot<u64>;
395
	type SovereignAccountDispatcherOrigin = EnsureRoot<u64>;
396
	type AssetTransactor = DummyAssetTransactor;
397
	type CurrencyId = CurrencyId;
398
	type CurrencyIdToLocation = CurrencyIdToLocation;
399
	type AccountIdToLocation = AccountIdToLocation;
400
	type SelfLocation = SelfLocation;
401
	type Weigher = DummyWeigher<RuntimeCall>;
402
	type UniversalLocation = UniversalLocation;
403
	type BaseXcmWeight = BaseXcmWeight;
404
	type XcmSender = TestSendXcm;
405
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
406
	type WeightInfo = ();
407
	type HrmpManipulatorOrigin = EnsureRoot<u64>;
408
	type HrmpOpenOrigin = EnsureRoot<u64>;
409
	type MaxHrmpFee = MaxHrmpRelayFee;
410
}
411

            
412
pub(crate) struct ExtBuilder {
413
	// endowed accounts with balances
414
	balances: Vec<(AccountId, Balance)>,
415
}
416

            
417
impl Default for ExtBuilder {
418
31
	fn default() -> ExtBuilder {
419
31
		ExtBuilder { balances: vec![] }
420
31
	}
421
}
422

            
423
impl ExtBuilder {
424
31
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
425
31
		self.balances = balances;
426
31
		self
427
31
	}
428
31
	pub(crate) fn build(self) -> sp_io::TestExternalities {
429
31
		let mut t = frame_system::GenesisConfig::<Test>::default()
430
31
			.build_storage()
431
31
			.expect("Frame system builds valid default genesis config");
432
31

            
433
31
		pallet_balances::GenesisConfig::<Test> {
434
31
			balances: self.balances,
435
31
		}
436
31
		.assimilate_storage(&mut t)
437
31
		.expect("Pallet balances storage can be assimilated");
438
31

            
439
31
		let mut ext = sp_io::TestExternalities::new(t);
440
31
		ext.execute_with(|| System::set_block_number(1));
441
31
		ext
442
31
	}
443
}
444

            
445
13
pub(crate) fn events() -> Vec<super::Event<Test>> {
446
13
	System::events()
447
13
		.into_iter()
448
32
		.map(|r| r.event)
449
32
		.filter_map(|e| {
450
32
			if let RuntimeEvent::XcmTransactor(inner) = e {
451
32
				Some(inner)
452
			} else {
453
				None
454
			}
455
32
		})
456
13
		.collect::<Vec<_>>()
457
13
}