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 moonbeam_tests_primitives::MemoryFeeTrader;
28
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
29

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

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

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

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

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

            
73
impl frame_system::Config for Test {
74
	type BaseCallFilter = frame_support::traits::Nothing;
75
	type BlockWeights = ();
76
	type BlockLength = ();
77
	type RuntimeOrigin = RuntimeOrigin;
78
	type Nonce = u64;
79
	type RuntimeCall = RuntimeCall;
80
	type RuntimeTask = RuntimeTask;
81
	type Block = Block;
82
	type Hash = H256;
83
	type Hashing = BlakeTwo256;
84
	type AccountId = u64;
85
	type Lookup = IdentityLookup<Self::AccountId>;
86
	type RuntimeEvent = RuntimeEvent;
87
	type BlockHashCount = BlockHashCount;
88
	type DbWeight = ();
89
	type Version = ();
90
	type PalletInfo = PalletInfo;
91
	type AccountData = pallet_balances::AccountData<Balance>;
92
	type OnNewAccount = ();
93
	type OnKilledAccount = ();
94
	type OnSetCode = ();
95
	type SystemWeightInfo = ();
96
	type SS58Prefix = ();
97
	type MaxConsumers = frame_support::traits::ConstU32<16>;
98
	type SingleBlockMigrations = ();
99
	type MultiBlockMigrator = ();
100
	type PreInherents = ();
101
	type PostInherents = ();
102
	type PostTransactions = ();
103
	type ExtensionsWeightInfo = ();
104
}
105
parameter_types! {
106
	pub const ExistentialDeposit: u128 = 0;
107
}
108
impl pallet_balances::Config for Test {
109
	type MaxReserves = ();
110
	type ReserveIdentifier = ();
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
	type DoneSlashHandler = ();
123
}
124

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
311
14
	fn utility_pallet_index(&self) -> u8 {
312
14
		RelayIndices::<Test>::get().utility
313
14
	}
314

            
315
	fn staking_pallet_index(&self) -> u8 {
316
		RelayIndices::<Test>::get().staking
317
	}
318
}
319

            
320
pub type AssetId = u128;
321
#[derive(
322
	Clone,
323
	Eq,
324
	Debug,
325
	PartialEq,
326
	Ord,
327
	PartialOrd,
328
	Encode,
329
	Decode,
330
	scale_info::TypeInfo,
331
	DecodeWithMemTracking,
332
)]
333
pub enum CurrencyId {
334
	SelfReserve,
335
	OtherReserve(AssetId),
336
}
337

            
338
pub struct CurrencyIdToLocation;
339

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

            
359
#[cfg(feature = "runtime-benchmarks")]
360
impl From<Location> for CurrencyId {
361
	fn from(location: Location) -> CurrencyId {
362
		if location == SelfReserve::get() {
363
			CurrencyId::SelfReserve
364
		} else if location == Location::parent() {
365
			CurrencyId::OtherReserve(0)
366
		} else {
367
			CurrencyId::OtherReserve(1)
368
		}
369
	}
370
}
371

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

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

            
396
16
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
397
16
		Ok(XcmHash::default())
398
16
	}
399
}
400

            
401
parameter_types! {
402
	pub MaxFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
403
	pub SelfLocationAbsolute: Location = Location {
404
		parents: 1,
405
		interior: [Parachain(ParachainId::get().into())].into(),
406
	};
407
}
408
pub type MaxHrmpRelayFee = xcm_builder::Case<MaxFee>;
409

            
410
impl Config for Test {
411
	type Balance = Balance;
412
	type Transactor = Transactors;
413
	type DerivativeAddressRegistrationOrigin = EnsureRoot<u64>;
414
	type SovereignAccountDispatcherOrigin = EnsureRoot<u64>;
415
	type AssetTransactor = DummyAssetTransactor;
416
	type CurrencyId = CurrencyId;
417
	type CurrencyIdToLocation = CurrencyIdToLocation;
418
	type AccountIdToLocation = AccountIdToLocation;
419
	type SelfLocation = SelfLocation;
420
	type Weigher = DummyWeigher<RuntimeCall>;
421
	type UniversalLocation = UniversalLocation;
422
	type BaseXcmWeight = BaseXcmWeight;
423
	type XcmSender = TestSendXcm;
424
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
425
	type WeightInfo = ();
426
	type HrmpManipulatorOrigin = EnsureRoot<u64>;
427
	type HrmpOpenOrigin = EnsureRoot<u64>;
428
	type MaxHrmpFee = MaxHrmpRelayFee;
429
	type FeeTrader = MemoryFeeTrader;
430
}
431

            
432
pub(crate) struct ExtBuilder {
433
	// endowed accounts with balances
434
	balances: Vec<(AccountId, Balance)>,
435
}
436

            
437
impl Default for ExtBuilder {
438
29
	fn default() -> ExtBuilder {
439
29
		ExtBuilder { balances: vec![] }
440
29
	}
441
}
442

            
443
impl ExtBuilder {
444
29
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
445
29
		self.balances = balances;
446
29
		self
447
29
	}
448
29
	pub(crate) fn build(self) -> sp_io::TestExternalities {
449
29
		let mut t = frame_system::GenesisConfig::<Test>::default()
450
29
			.build_storage()
451
29
			.expect("Frame system builds valid default genesis config");
452

            
453
29
		pallet_balances::GenesisConfig::<Test> {
454
29
			balances: self.balances,
455
29
			dev_accounts: None,
456
29
		}
457
29
		.assimilate_storage(&mut t)
458
29
		.expect("Pallet balances storage can be assimilated");
459

            
460
29
		let mut ext = sp_io::TestExternalities::new(t);
461
29
		ext.execute_with(|| System::set_block_number(1));
462
29
		ext
463
29
	}
464
}
465

            
466
13
pub(crate) fn events() -> Vec<super::Event<Test>> {
467
13
	System::events()
468
13
		.into_iter()
469
13
		.map(|r| r.event)
470
26
		.filter_map(|e| {
471
26
			if let RuntimeEvent::XcmTransactor(inner) = e {
472
26
				Some(inner)
473
			} else {
474
				None
475
			}
476
26
		})
477
13
		.collect::<Vec<_>>()
478
13
}