1
// Copyright 2019-2025 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::{
24
	construct_runtime, dispatch::GetDispatchInfo, parameter_types, weights::Weight,
25
};
26
use frame_system::EnsureRoot;
27
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
28

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

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

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

            
60
pub type Balance = u128;
61
pub type AccountId = u64;
62

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

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

            
124
parameter_types! {
125
	pub const MinimumPeriod: u64 = 5;
126
}
127

            
128
impl pallet_timestamp::Config for Test {
129
	type Moment = u64;
130
	type OnTimestampSet = ();
131
	type MinimumPeriod = MinimumPeriod;
132
	type WeightInfo = ();
133
}
134

            
135
const XCM_VERSION_ROOT_KEY: &'static [u8] = b"XCM_VERSION_ROOT_KEY";
136

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

            
150
impl CustomVersionWrapper {
151
3
	pub fn set_version(version: u32) {
152
3
		frame_support::storage::unhashed::put(XCM_VERSION_ROOT_KEY, &version);
153
3
	}
154
}
155

            
156
pub struct DoNothingRouter;
157
impl SendXcm for DoNothingRouter {
158
	type Ticket = ();
159

            
160
	fn validate(
161
		_destination: &mut Option<Location>,
162
		_message: &mut Option<opaque::Xcm>,
163
	) -> SendResult<Self::Ticket> {
164
		Ok(((), Assets::new()))
165
	}
166

            
167
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
168
		Ok(XcmHash::default())
169
	}
170
}
171

            
172
pub struct DummyAssetTransactor;
173
impl TransactAsset for DummyAssetTransactor {
174
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
175
		Ok(())
176
	}
177

            
178
6
	fn withdraw_asset(
179
6
		_what: &Asset,
180
6
		_who: &Location,
181
6
		_context: Option<&XcmContext>,
182
6
	) -> Result<AssetsInHolding, XcmError> {
183
6
		Ok(AssetsInHolding::default())
184
6
	}
185
}
186

            
187
pub struct DummyWeightTrader;
188
impl WeightTrader for DummyWeightTrader {
189
	fn new() -> Self {
190
		DummyWeightTrader
191
	}
192

            
193
	fn buy_weight(
194
		&mut self,
195
		_weight: Weight,
196
		_payment: AssetsInHolding,
197
		_context: &XcmContext,
198
	) -> Result<AssetsInHolding, XcmError> {
199
		Ok(AssetsInHolding::default())
200
	}
201
}
202

            
203
use sp_std::marker::PhantomData;
204
pub struct DummyWeigher<C>(PhantomData<C>);
205

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

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

            
229
parameter_types! {
230
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
231

            
232
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
233
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
234

            
235
	pub SelfLocation: Location = Location::here();
236

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

            
247
	pub UniversalLocation: InteriorLocation =
248
		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainId::get().into())].into();
249
}
250

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

            
261
#[derive(Encode, Decode)]
262
pub enum UtilityCall {
263
	#[codec(index = 0u8)]
264
	AsDerivative(u16),
265
}
266

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

            
279
// Transactors for the mock runtime. Only relay chain
280
#[derive(
281
	Clone,
282
	Eq,
283
	Debug,
284
	PartialEq,
285
	Ord,
286
	PartialOrd,
287
	Encode,
288
	Decode,
289
	scale_info::TypeInfo,
290
	DecodeWithMemTracking,
291
)]
292
pub enum Transactors {
293
	Relay,
294
}
295

            
296
#[cfg(feature = "runtime-benchmarks")]
297
impl Default for Transactors {
298
	fn default() -> Self {
299
		Transactors::Relay
300
	}
301
}
302

            
303
impl XcmTransact for Transactors {
304
9
	fn destination(self) -> Location {
305
9
		match self {
306
9
			Transactors::Relay => Location::parent(),
307
9
		}
308
9
	}
309
}
310

            
311
impl UtilityEncodeCall for Transactors {
312
14
	fn encode_call(self, call: UtilityAvailableCalls) -> Vec<u8> {
313
14
		match self {
314
14
			Transactors::Relay => match call {
315
14
				UtilityAvailableCalls::AsDerivative(a, b) => {
316
14
					let mut call =
317
14
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
318
14
					call.append(&mut b.clone());
319
14
					call
320
14
				}
321
14
			},
322
14
		}
323
14
	}
324
}
325

            
326
pub type AssetId = u128;
327
#[derive(
328
	Clone,
329
	Eq,
330
	Debug,
331
	PartialEq,
332
	Ord,
333
	PartialOrd,
334
	Encode,
335
	Decode,
336
	scale_info::TypeInfo,
337
	DecodeWithMemTracking,
338
)]
339
pub enum CurrencyId {
340
	SelfReserve,
341
	OtherReserve(AssetId),
342
}
343

            
344
pub struct CurrencyIdToLocation;
345

            
346
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToLocation {
347
11
	fn convert(currency: CurrencyId) -> Option<Location> {
348
11
		match currency {
349
			CurrencyId::SelfReserve => {
350
				let multi: Location = SelfReserve::get();
351
				Some(multi)
352
			}
353
			// To distinguish between relay and others, specially for reserve asset
354
11
			CurrencyId::OtherReserve(asset) => {
355
11
				if asset == 0 {
356
11
					Some(Location::parent())
357
				} else {
358
					Some(Location::new(1, [Parachain(2)]))
359
				}
360
			}
361
		}
362
11
	}
363
}
364

            
365
#[cfg(feature = "runtime-benchmarks")]
366
impl From<Location> for CurrencyId {
367
	fn from(location: Location) -> CurrencyId {
368
		if location == SelfReserve::get() {
369
			CurrencyId::SelfReserve
370
		} else if location == Location::parent() {
371
			CurrencyId::OtherReserve(0)
372
		} else {
373
			CurrencyId::OtherReserve(1)
374
		}
375
	}
376
}
377

            
378
// Simulates sending a XCM message
379
thread_local! {
380
	pub static SENT_XCM: RefCell<Vec<(Location, opaque::Xcm)>> = RefCell::new(Vec::new());
381
}
382
13
pub fn sent_xcm() -> Vec<(Location, opaque::Xcm)> {
383
13
	SENT_XCM.with(|q| (*q.borrow()).clone())
384
13
}
385
pub struct TestSendXcm;
386
impl SendXcm for TestSendXcm {
387
	type Ticket = ();
388

            
389
17
	fn validate(
390
17
		destination: &mut Option<Location>,
391
17
		message: &mut Option<opaque::Xcm>,
392
17
	) -> SendResult<Self::Ticket> {
393
17
		SENT_XCM.with(|q| {
394
17
			q.borrow_mut()
395
17
				.push((destination.clone().unwrap(), message.clone().unwrap()))
396
17
		});
397
17
		CustomVersionWrapper::wrap_version(&destination.clone().unwrap(), message.clone().unwrap())
398
17
			.map_err(|()| SendError::DestinationUnsupported)?;
399
16
		Ok(((), Assets::new()))
400
17
	}
401

            
402
16
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
403
16
		Ok(XcmHash::default())
404
16
	}
405
}
406

            
407
parameter_types! {
408
	pub MaxFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
409
	pub SelfLocationAbsolute: Location = Location {
410
		parents: 1,
411
		interior: [Parachain(ParachainId::get().into())].into(),
412
	};
413
}
414
pub type MaxHrmpRelayFee = xcm_builder::Case<MaxFee>;
415

            
416
impl Config for Test {
417
	type RuntimeEvent = RuntimeEvent;
418
	type Balance = Balance;
419
	type Transactor = Transactors;
420
	type DerivativeAddressRegistrationOrigin = EnsureRoot<u64>;
421
	type SovereignAccountDispatcherOrigin = EnsureRoot<u64>;
422
	type AssetTransactor = DummyAssetTransactor;
423
	type CurrencyId = CurrencyId;
424
	type CurrencyIdToLocation = CurrencyIdToLocation;
425
	type AccountIdToLocation = AccountIdToLocation;
426
	type SelfLocation = SelfLocation;
427
	type Weigher = DummyWeigher<RuntimeCall>;
428
	type UniversalLocation = UniversalLocation;
429
	type BaseXcmWeight = BaseXcmWeight;
430
	type XcmSender = TestSendXcm;
431
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
432
	type WeightInfo = ();
433
	type HrmpManipulatorOrigin = EnsureRoot<u64>;
434
	type HrmpOpenOrigin = EnsureRoot<u64>;
435
	type MaxHrmpFee = MaxHrmpRelayFee;
436
}
437

            
438
pub(crate) struct ExtBuilder {
439
	// endowed accounts with balances
440
	balances: Vec<(AccountId, Balance)>,
441
}
442

            
443
impl Default for ExtBuilder {
444
31
	fn default() -> ExtBuilder {
445
31
		ExtBuilder { balances: vec![] }
446
31
	}
447
}
448

            
449
impl ExtBuilder {
450
31
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
451
31
		self.balances = balances;
452
31
		self
453
31
	}
454
31
	pub(crate) fn build(self) -> sp_io::TestExternalities {
455
31
		let mut t = frame_system::GenesisConfig::<Test>::default()
456
31
			.build_storage()
457
31
			.expect("Frame system builds valid default genesis config");
458
31

            
459
31
		pallet_balances::GenesisConfig::<Test> {
460
31
			balances: self.balances,
461
31
			dev_accounts: None,
462
31
		}
463
31
		.assimilate_storage(&mut t)
464
31
		.expect("Pallet balances storage can be assimilated");
465
31

            
466
31
		let mut ext = sp_io::TestExternalities::new(t);
467
31
		ext.execute_with(|| System::set_block_number(1));
468
31
		ext
469
31
	}
470
}
471

            
472
13
pub(crate) fn events() -> Vec<super::Event<Test>> {
473
13
	System::events()
474
13
		.into_iter()
475
32
		.map(|r| r.event)
476
32
		.filter_map(|e| {
477
32
			if let RuntimeEvent::XcmTransactor(inner) = e {
478
32
				Some(inner)
479
			} else {
480
				None
481
			}
482
32
		})
483
13
		.collect::<Vec<_>>()
484
13
}