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
use super::*;
19
use cumulus_primitives_core::{relay_chain::HrmpChannelId, ParaId};
20
use frame_support::traits::{
21
	ConstU32, EnsureOrigin, Everything, Nothing, OriginTrait, PalletInfo as PalletInfoTrait,
22
};
23
use frame_support::{construct_runtime, parameter_types, weights::Weight};
24
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
25
use parity_scale_codec::{Decode, Encode};
26
use precompile_utils::{
27
	mock_account,
28
	precompile_set::*,
29
	testing::{AddressInPrefixedSet, MockAccount},
30
};
31
use scale_info::TypeInfo;
32
use sp_core::H256;
33
use sp_io;
34
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
35
use sp_runtime::BuildStorage;
36
use xcm::latest::{prelude::*, Error as XcmError};
37
use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds, IsConcrete};
38
use xcm_executor::{
39
	traits::{TransactAsset, WeightTrader},
40
	AssetsInHolding,
41
};
42

            
43
pub type AccountId = MockAccount;
44
pub type Balance = u128;
45
pub type AssetId = u128;
46

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

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

            
61
28
mock_account!(AssetAccount(u128), |v: AssetAccount| AddressInPrefixedSet(
62
28
	0xffffffff, v.0
63
28
)
64
28
.into());
65
2
mock_account!(SelfReserveAccount, |_| MockAccount::from_u64(2));
66

            
67
parameter_types! {
68
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
69
}
70

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

            
127
// These parameters dont matter much as this will only be called by root with the forced arguments
128
// No deposit is substracted with those methods
129
parameter_types! {
130
	pub const AssetDeposit: Balance = 0;
131
	pub const ApprovalDeposit: Balance = 0;
132
	pub const AssetsStringLimit: u32 = 50;
133
	pub const MetadataDepositBase: Balance = 0;
134
	pub const MetadataDepositPerByte: Balance = 0;
135
}
136

            
137
pub type Precompiles<R> =
138
	PrecompileSetBuilder<R, (PrecompileAt<AddressU64<1>, XtokensPrecompile<R>>,)>;
139

            
140
pub type PCall = XtokensPrecompileCall<Runtime>;
141

            
142
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
143
/// Block storage limit in bytes. Set to 40 KB.
144
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
145

            
146
parameter_types! {
147
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
148
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
149
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
150
	pub GasLimitPovSizeRatio: u64 = {
151
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
152
		block_gas_limit.saturating_div(MAX_POV_SIZE)
153
	};
154
	pub GasLimitStorageGrowthRatio: u64 = {
155
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
156
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
157
	};
158
}
159

            
160
impl pallet_evm::Config for Runtime {
161
	type FeeCalculator = ();
162
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
163
	type WeightPerGas = WeightPerGas;
164
	type CallOrigin = EnsureAddressRoot<AccountId>;
165
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
166
	type AddressMapping = AccountId;
167
	type Currency = Balances;
168
	type RuntimeEvent = RuntimeEvent;
169
	type Runner = pallet_evm::runner::stack::Runner<Self>;
170
	type PrecompilesType = Precompiles<Self>;
171
	type PrecompilesValue = PrecompilesValue;
172
	type ChainId = ();
173
	type OnChargeTransaction = ();
174
	type BlockGasLimit = BlockGasLimit;
175
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
176
	type FindAuthor = ();
177
	type OnCreate = ();
178
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
179
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
180
	type Timestamp = Timestamp;
181
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
182
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
183
}
184

            
185
parameter_types! {
186
	pub const MinimumPeriod: u64 = 5;
187
}
188
impl pallet_timestamp::Config for Runtime {
189
	type Moment = u64;
190
	type OnTimestampSet = ();
191
	type MinimumPeriod = MinimumPeriod;
192
	type WeightInfo = ();
193
}
194
pub struct ConvertOriginToLocal;
195
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
196
	type Success = Location;
197

            
198
13
	fn try_origin(_: Origin) -> Result<Location, Origin> {
199
13
		Ok(Location::here())
200
13
	}
201

            
202
	#[cfg(feature = "runtime-benchmarks")]
203
	fn try_successful_origin() -> Result<Origin, ()> {
204
		Ok(Origin::root())
205
	}
206
}
207

            
208
pub struct DoNothingRouter;
209
impl SendXcm for DoNothingRouter {
210
	type Ticket = ();
211

            
212
13
	fn validate(
213
13
		_destination: &mut Option<Location>,
214
13
		_message: &mut Option<Xcm<()>>,
215
13
	) -> SendResult<Self::Ticket> {
216
13
		Ok(((), Assets::new()))
217
13
	}
218

            
219
13
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
220
13
		Ok(XcmHash::default())
221
13
	}
222
}
223

            
224
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
225

            
226
pub struct DummyAssetTransactor;
227
impl TransactAsset for DummyAssetTransactor {
228
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
229
		Ok(())
230
	}
231

            
232
15
	fn withdraw_asset(
233
15
		_what: &Asset,
234
15
		_who: &Location,
235
15
		_maybe_context: Option<&XcmContext>,
236
15
	) -> Result<AssetsInHolding, XcmError> {
237
15
		Ok(AssetsInHolding::default())
238
15
	}
239
}
240

            
241
pub struct DummyWeightTrader;
242
impl WeightTrader for DummyWeightTrader {
243
13
	fn new() -> Self {
244
13
		DummyWeightTrader
245
13
	}
246

            
247
	fn buy_weight(
248
		&mut self,
249
		_weight: Weight,
250
		_payment: AssetsInHolding,
251
		_context: &XcmContext,
252
	) -> Result<AssetsInHolding, XcmError> {
253
		Ok(AssetsInHolding::default())
254
	}
255
}
256

            
257
parameter_types! {
258
	pub UniversalLocation: InteriorLocation = Here;
259
	pub MatcherLocation: Location = Location::here();
260
	pub const MaxAssetsIntoHolding: u32 = 64;
261
}
262

            
263
impl pallet_xcm::Config for Runtime {
264
	// The config types here are entirely configurable, since the only one that is sorely needed
265
	// is `XcmExecutor`, which will be used in unit tests located in xcm-executor.
266
	type RuntimeEvent = RuntimeEvent;
267
	type ExecuteXcmOrigin = ConvertOriginToLocal;
268
	type UniversalLocation = UniversalLocation;
269
	type SendXcmOrigin = ConvertOriginToLocal;
270
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
271
	type XcmRouter = DoNothingRouter;
272
	type XcmExecuteFilter = frame_support::traits::Everything;
273
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
274
	type XcmTeleportFilter = frame_support::traits::Everything;
275
	type XcmReserveTransferFilter = frame_support::traits::Everything;
276
	type RuntimeOrigin = RuntimeOrigin;
277
	type RuntimeCall = RuntimeCall;
278
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
279
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
280
	type Currency = Balances;
281
	type CurrencyMatcher = IsConcrete<MatcherLocation>;
282
	type TrustedLockers = ();
283
	type SovereignAccountOf = ();
284
	type MaxLockers = ConstU32<8>;
285
	type WeightInfo = pallet_xcm::TestWeightInfo;
286
	type MaxRemoteLockConsumers = ConstU32<0>;
287
	type RemoteLockConsumerIdentifier = ();
288
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
289
}
290

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

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

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

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

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

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

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

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

            
377
pub struct XcmConfig;
378
impl xcm_executor::Config for XcmConfig {
379
	type RuntimeCall = RuntimeCall;
380
	type XcmSender = DoNothingRouter;
381
	type AssetTransactor = DummyAssetTransactor;
382
	type OriginConverter = pallet_xcm::XcmPassthrough<RuntimeOrigin>;
383
	type IsReserve = xcm_primitives::MultiNativeAsset<xcm_primitives::RelativeReserveProvider>;
384
	type IsTeleporter = ();
385
	type UniversalLocation = UniversalLocation;
386
	type Barrier = Barrier;
387
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
388
	type Trader = DummyWeightTrader;
389
	type ResponseHandler = ();
390
	type SubscriptionService = ();
391
	type AssetTrap = ();
392
	type AssetClaims = ();
393
	type CallDispatcher = RuntimeCall;
394
	type AssetLocker = ();
395
	type AssetExchanger = ();
396
	type PalletInstancesInfo = ();
397
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
398
	type FeeManager = ();
399
	type MessageExporter = ();
400
	type UniversalAliases = Nothing;
401
	type SafeCallFilter = Everything;
402
	type Aliasers = Nothing;
403
	type TransactionalProcessor = ();
404
	type HrmpNewChannelOpenRequestHandler = ();
405
	type HrmpChannelAcceptedHandler = ();
406
	type HrmpChannelClosingHandler = ();
407
	type XcmRecorder = ();
408
}
409

            
410
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
411
pub enum CurrencyId {
412
	SelfReserve,
413
	OtherReserve(AssetId),
414
}
415

            
416
// Implement the trait, where we convert AccountId to AssetID
417
impl AccountIdToCurrencyId<AccountId, CurrencyId> for Runtime {
418
	/// The way to convert an account to assetId is by ensuring that the prefix is 0XFFFFFFFF
419
	/// and by taking the lowest 128 bits as the assetId
420
8
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
421
8
		match account {
422
8
			a if a.has_prefix_u32(0xffffffff) => Some(CurrencyId::OtherReserve(a.without_prefix())),
423
1
			a if a == AccountId::from(SelfReserveAccount) => Some(CurrencyId::SelfReserve),
424
			_ => None,
425
		}
426
8
	}
427
}
428

            
429
pub struct CurrencyIdToMultiLocation;
430

            
431
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToMultiLocation {
432
8
	fn convert(currency: CurrencyId) -> Option<Location> {
433
8
		match currency {
434
			CurrencyId::SelfReserve => {
435
1
				let multi: Location = SelfReserve::get();
436
1
				Some(multi)
437
			}
438
			// To distinguish between relay and others, specially for reserve asset
439
7
			CurrencyId::OtherReserve(asset) => {
440
7
				if asset == 0 {
441
3
					Some(Location::parent())
442
				} else {
443
4
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
444
				}
445
			}
446
		}
447
8
	}
448
}
449

            
450
pub struct AccountIdToLocation;
451
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
452
	fn convert(account: AccountId) -> Location {
453
		let as_h160: H160 = account.into();
454
		Location::new(
455
			1,
456
			[AccountKey20 {
457
				network: None,
458
				key: as_h160.as_fixed_bytes().clone(),
459
			}],
460
		)
461
	}
462
}
463

            
464
parameter_types! {
465
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
466

            
467
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
468
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
469
	pub const MaxAssetsForTransfer: usize = 2;
470

            
471
	pub SelfLocation: Location =
472
		Location::new(1, [Parachain(ParachainId::get().into())]);
473

            
474
	pub SelfReserve: Location = Location::new(
475
		1,
476
		[
477
			Parachain(ParachainId::get().into()),
478
			PalletInstance(
479
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
480
			)
481
		]);
482
	pub MaxInstructions: u32 = 100;
483
}
484

            
485
pub(crate) struct ExtBuilder {
486
	// endowed accounts with balances
487
	balances: Vec<(AccountId, Balance)>,
488
}
489

            
490
impl Default for ExtBuilder {
491
19
	fn default() -> ExtBuilder {
492
19
		ExtBuilder { balances: vec![] }
493
19
	}
494
}
495

            
496
impl ExtBuilder {
497
16
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
498
16
		self.balances = balances;
499
16
		self
500
16
	}
501
19
	pub(crate) fn build(self) -> sp_io::TestExternalities {
502
19
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
503
19
			.build_storage()
504
19
			.expect("Frame system builds valid default genesis config");
505
19

            
506
19
		pallet_balances::GenesisConfig::<Runtime> {
507
19
			balances: self.balances,
508
19
		}
509
19
		.assimilate_storage(&mut t)
510
19
		.expect("Pallet balances storage can be assimilated");
511
19

            
512
19
		let mut ext = sp_io::TestExternalities::new(t);
513
19
		ext.execute_with(|| System::set_block_number(1));
514
19
		ext
515
19
	}
516
}
517

            
518
14
pub(crate) fn events() -> Vec<RuntimeEvent> {
519
14
	System::events()
520
14
		.into_iter()
521
20
		.map(|r| r.event)
522
14
		.collect::<Vec<_>>()
523
14
}