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
	Disabled, EnsureOrigin, Everything, Nothing, OriginTrait, PalletInfo as PalletInfoTrait,
22
};
23
use frame_support::{construct_runtime, parameter_types, weights::Weight};
24
use moonbeam_tests_primitives::MemoryFeeTrader;
25
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
26
use pallet_xcm_transactor::RelayIndices;
27
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
28
use precompile_utils::{mock_account, precompile_set::*, testing::MockAccount};
29
use scale_info::TypeInfo;
30
use sp_core::H256;
31
use sp_runtime::BuildStorage;
32
use sp_runtime::{
33
	traits::{BlakeTwo256, IdentityLookup},
34
	Perbill,
35
};
36
use xcm::latest::{prelude::*, Error as XcmError};
37
use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds};
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
type XcmV2Weight = u64;
47

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

            
50
construct_runtime!(
51
	pub enum Runtime	{
52
		System: frame_system,
53
		Balances: pallet_balances,
54
		Evm: pallet_evm,
55
		Timestamp: pallet_timestamp,
56
		PolkadotXcm: pallet_xcm,
57
		XcmTransactor: pallet_xcm_transactor,
58
	}
59
);
60

            
61
mock_account!(SelfReserveAccount, |_| MockAccount::from_u64(2));
62

            
63
parameter_types! {
64
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
65
	pub UniversalLocation: InteriorLocation = RelayNetwork::get().into();
66
}
67

            
68
parameter_types! {
69
	pub const BlockHashCount: u32 = 250;
70
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
71
	pub const MaximumBlockLength: u32 = 2 * 1024;
72
	pub const AvailableBlockRatio: Perbill = Perbill::one();
73
	pub const SS58Prefix: u8 = 42;
74
}
75

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

            
128
pub struct DoNothingRouter;
129
impl SendXcm for DoNothingRouter {
130
	type Ticket = ();
131

            
132
	fn validate(
133
		_destination: &mut Option<Location>,
134
		_message: &mut Option<Xcm<()>>,
135
	) -> SendResult<Self::Ticket> {
136
		Ok(((), Assets::new()))
137
	}
138

            
139
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
140
		Ok(XcmHash::default())
141
	}
142
}
143

            
144
impl pallet_xcm::Config for Runtime {
145
	type RuntimeEvent = RuntimeEvent;
146
	type ExecuteXcmOrigin = ConvertOriginToLocal;
147
	type XcmExecuteFilter = Everything;
148
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
149
	type XcmRouter = DoNothingRouter;
150
	type SendXcmOrigin = ConvertOriginToLocal;
151
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
152
	type UniversalLocation = UniversalLocation;
153
	type XcmTeleportFilter = frame_support::traits::Everything;
154
	type XcmReserveTransferFilter = frame_support::traits::Everything;
155
	type RuntimeOrigin = RuntimeOrigin;
156
	type RuntimeCall = RuntimeCall;
157
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
158
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
159
	type Currency = Balances;
160
	type CurrencyMatcher = ();
161
	type TrustedLockers = ();
162
	type SovereignAccountOf = ();
163
	type MaxLockers = ConstU32<8>;
164
	type WeightInfo = pallet_xcm::TestWeightInfo;
165
	type MaxRemoteLockConsumers = ConstU32<0>;
166
	type RemoteLockConsumerIdentifier = ();
167
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
168
	type AuthorizedAliasConsideration = Disabled;
169
}
170

            
171
parameter_types! {
172
	pub const MaxAssetsIntoHolding: u32 = 64;
173
}
174

            
175
pub struct XcmConfig;
176
impl xcm_executor::Config for XcmConfig {
177
	type RuntimeCall = RuntimeCall;
178
	type AssetTransactor = DummyAssetTransactor;
179
	type OriginConverter = pallet_xcm::XcmPassthrough<RuntimeOrigin>;
180
	type IsReserve = ();
181
	type IsTeleporter = ();
182
	type Barrier = Barrier;
183
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
184
	type Trader = DummyWeightTrader;
185
	type ResponseHandler = ();
186
	type SubscriptionService = ();
187
	type AssetTrap = ();
188
	type AssetClaims = ();
189
	type CallDispatcher = RuntimeCall;
190
	type XcmSender = DoNothingRouter;
191
	type UniversalLocation = UniversalLocation;
192
	type AssetLocker = ();
193
	type AssetExchanger = ();
194
	type PalletInstancesInfo = ();
195
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
196
	type FeeManager = ();
197
	type MessageExporter = ();
198
	type UniversalAliases = Nothing;
199
	type SafeCallFilter = Everything;
200
	type Aliasers = Nothing;
201
	type TransactionalProcessor = ();
202
	type HrmpNewChannelOpenRequestHandler = ();
203
	type HrmpChannelAcceptedHandler = ();
204
	type HrmpChannelClosingHandler = ();
205
	type XcmRecorder = ();
206
	type XcmEventEmitter = ();
207
}
208

            
209
pub type Precompiles<R> = PrecompileSetBuilder<
210
	R,
211
	(
212
		PrecompileAt<AddressU64<1>, GmpPrecompile<R>, (SubcallWithMaxNesting<1>,)>,
213
		RevertPrecompile<AddressU64<2>>,
214
	),
215
>;
216

            
217
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
218

            
219
pub struct DummyAssetTransactor;
220
impl TransactAsset for DummyAssetTransactor {
221
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
222
		Ok(())
223
	}
224

            
225
	fn withdraw_asset(
226
		_what: &Asset,
227
		_who: &Location,
228
		_maybe_context: Option<&XcmContext>,
229
	) -> Result<AssetsInHolding, XcmError> {
230
		Ok(AssetsInHolding::default())
231
	}
232
}
233

            
234
pub struct DummyWeightTrader;
235
impl WeightTrader for DummyWeightTrader {
236
	fn new() -> Self {
237
		DummyWeightTrader
238
	}
239

            
240
	fn buy_weight(
241
		&mut self,
242
		_weight: Weight,
243
		_payment: AssetsInHolding,
244
		_context: &XcmContext,
245
	) -> Result<AssetsInHolding, XcmError> {
246
		Ok(AssetsInHolding::default())
247
	}
248
}
249

            
250
pub type PCall = GmpPrecompileCall<Runtime>;
251

            
252
mock_account!(Batch, |_| MockAccount::from_u64(1));
253
mock_account!(Revert, |_| MockAccount::from_u64(2));
254

            
255
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
256
/// Block storage limit in bytes. Set to 40 KB.
257
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
258

            
259
parameter_types! {
260
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
261
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
262
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
263
	pub GasLimitPovSizeRatio: u64 = {
264
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
265
		block_gas_limit.saturating_div(MAX_POV_SIZE)
266
	};
267
	pub GasLimitStorageGrowthRatio: u64 = {
268
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
269
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
270
	};
271
}
272

            
273
impl pallet_evm::Config for Runtime {
274
	type FeeCalculator = ();
275
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
276
	type WeightPerGas = WeightPerGas;
277
	type CallOrigin = EnsureAddressRoot<AccountId>;
278
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
279
	type AddressMapping = AccountId;
280
	type Currency = Balances;
281
	type Runner = pallet_evm::runner::stack::Runner<Self>;
282
	type PrecompilesType = Precompiles<Runtime>;
283
	type PrecompilesValue = PrecompilesValue;
284
	type ChainId = ();
285
	type OnChargeTransaction = ();
286
	type BlockGasLimit = BlockGasLimit;
287
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
288
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
289
	type FindAuthor = ();
290
	type OnCreate = ();
291
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
292
	type Timestamp = Timestamp;
293
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
294
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
295
	type CreateOriginFilter = ();
296
	type CreateInnerOriginFilter = ();
297
}
298

            
299
#[derive(Encode, Decode)]
300
pub enum RelayCall {
301
	#[codec(index = 5u8)]
302
	// the index should match the position of the module in `construct_runtime!`
303
	Utility(UtilityCall),
304
	#[codec(index = 6u8)]
305
	// the index should match the position of the module in `construct_runtime!`
306
	Hrmp(HrmpCall),
307
}
308

            
309
#[derive(Encode, Decode)]
310
pub enum UtilityCall {
311
	#[codec(index = 1u8)]
312
	AsDerivative(u16),
313
}
314

            
315
// HRMP call encoding, needed for xcm transactor pallet
316
#[derive(Encode, Decode)]
317
pub enum HrmpCall {
318
	#[codec(index = 0u8)]
319
	InitOpenChannel(ParaId, u32, u32),
320
	#[codec(index = 1u8)]
321
	AcceptOpenChannel(ParaId),
322
	#[codec(index = 2u8)]
323
	CloseChannel(HrmpChannelId),
324
	#[codec(index = 6u8)]
325
	CancelOpenRequest(HrmpChannelId, u32),
326
}
327

            
328
#[derive(
329
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
330
)]
331
pub enum MockTransactors {
332
	Relay,
333
}
334

            
335
impl xcm_primitives::XcmTransact for MockTransactors {
336
	fn destination(self) -> Location {
337
		match self {
338
			MockTransactors::Relay => Location::parent(),
339
		}
340
	}
341

            
342
	fn utility_pallet_index(&self) -> u8 {
343
		RelayIndices::<Runtime>::get().utility
344
	}
345

            
346
	fn staking_pallet_index(&self) -> u8 {
347
		RelayIndices::<Runtime>::get().staking
348
	}
349
}
350

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

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

            
380
parameter_types! {
381
	pub const MinimumPeriod: u64 = 5;
382
}
383
impl pallet_timestamp::Config for Runtime {
384
	type Moment = u64;
385
	type OnTimestampSet = ();
386
	type MinimumPeriod = MinimumPeriod;
387
	type WeightInfo = ();
388
}
389

            
390
pub struct ConvertOriginToLocal;
391
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
392
	type Success = Location;
393

            
394
	fn try_origin(_: Origin) -> Result<Location, Origin> {
395
		Ok(Location::here())
396
	}
397

            
398
	#[cfg(feature = "runtime-benchmarks")]
399
	fn try_successful_origin() -> Result<Origin, ()> {
400
		Ok(Origin::root())
401
	}
402
}
403

            
404
#[derive(
405
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
406
)]
407
pub enum CurrencyId {
408
	SelfReserve,
409
	OtherReserve(AssetId),
410
}
411

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

            
425
pub struct AccountIdToLocation;
426
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
427
	fn convert(account: AccountId) -> Location {
428
		let as_h160: H160 = account.into();
429
		Location::new(
430
			1,
431
			[AccountKey20 {
432
				network: None,
433
				key: as_h160.as_fixed_bytes().clone(),
434
			}],
435
		)
436
	}
437
}
438

            
439
parameter_types! {
440
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
441

            
442
	pub const BaseXcmWeight: XcmV2Weight = 1000;
443
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
444
	pub const MaxAssetsForTransfer: usize = 2;
445

            
446
	pub SelfLocation: Location =
447
		Location::new(1, [Parachain(ParachainId::get().into())]);
448

            
449
	pub SelfReserve: Location = Location::new(
450
		1,
451
		[
452
			Parachain(ParachainId::get().into()),
453
			PalletInstance(
454
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
455
			)
456
		]);
457
	pub MaxInstructions: u32 = 100;
458
}
459

            
460
pub struct CurrencyIdToMultiLocation;
461

            
462
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToMultiLocation {
463
	fn convert(currency: CurrencyId) -> Option<Location> {
464
		match currency {
465
			CurrencyId::SelfReserve => {
466
				let multi: Location = SelfReserve::get();
467
				Some(multi)
468
			}
469
			// To distinguish between relay and others, specially for reserve asset
470
			CurrencyId::OtherReserve(asset) => {
471
				if asset == 0 {
472
					Some(Location::parent())
473
				} else {
474
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
475
				}
476
			}
477
		}
478
	}
479
}
480

            
481
pub(crate) struct ExtBuilder {
482
	/// Endowed accounts with balances
483
	balances: Vec<(AccountId, Balance)>,
484
}
485

            
486
impl Default for ExtBuilder {
487
3
	fn default() -> ExtBuilder {
488
3
		ExtBuilder { balances: vec![] }
489
3
	}
490
}
491

            
492
impl ExtBuilder {
493
	/// Fund some accounts before starting the test
494
3
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
495
3
		self.balances = balances;
496
3
		self
497
3
	}
498

            
499
	/// Build the test externalities for use in tests
500
3
	pub(crate) fn build(self) -> sp_io::TestExternalities {
501
3
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
502
3
			.build_storage()
503
3
			.expect("Frame system builds valid default genesis config");
504

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

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