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, 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
742
construct_runtime!(
51
416
	pub enum Test
52
416
	{
53
416
		System: frame_system,
54
416
		Balances: pallet_balances,
55
416
		Timestamp: pallet_timestamp,
56
416
		XcmTransactor: pallet_xcm_transactor,
57
416
	}
58
816
);
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(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, scale_info::TypeInfo)]
281
pub enum Transactors {
282
	Relay,
283
}
284

            
285
#[cfg(feature = "runtime-benchmarks")]
286
impl Default for Transactors {
287
	fn default() -> Self {
288
		Transactors::Relay
289
	}
290
}
291

            
292
impl XcmTransact for Transactors {
293
9
	fn destination(self) -> Location {
294
9
		match self {
295
9
			Transactors::Relay => Location::parent(),
296
9
		}
297
9
	}
298
}
299

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

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

            
322
pub struct CurrencyIdToLocation;
323

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

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

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

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

            
380
16
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
381
16
		Ok(XcmHash::default())
382
16
	}
383
}
384

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

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

            
416
pub(crate) struct ExtBuilder {
417
	// endowed accounts with balances
418
	balances: Vec<(AccountId, Balance)>,
419
}
420

            
421
impl Default for ExtBuilder {
422
31
	fn default() -> ExtBuilder {
423
31
		ExtBuilder { balances: vec![] }
424
31
	}
425
}
426

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

            
437
31
		pallet_balances::GenesisConfig::<Test> {
438
31
			balances: self.balances,
439
31
		}
440
31
		.assimilate_storage(&mut t)
441
31
		.expect("Pallet balances storage can be assimilated");
442
31

            
443
31
		let mut ext = sp_io::TestExternalities::new(t);
444
31
		ext.execute_with(|| System::set_block_number(1));
445
31
		ext
446
31
	}
447
}
448

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