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
	ConstBool, Disabled, EnsureOrigin, Everything, Nothing, OriginTrait,
22
	PalletInfo as PalletInfoTrait,
23
};
24
use frame_support::{construct_runtime, parameter_types, weights::Weight};
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
6
construct_runtime!(
51
6
	pub enum Runtime	{
52
6
		System: frame_system,
53
6
		Balances: pallet_balances,
54
6
		Evm: pallet_evm,
55
6
		Timestamp: pallet_timestamp,
56
6
		PolkadotXcm: pallet_xcm,
57
6
		XcmTransactor: pallet_xcm_transactor,
58
6
	}
59
6
);
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
	type AssetHubMigrationStarted = ConstBool<false>;
170
}
171

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

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

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

            
218
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
219

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

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

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

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

            
251
pub type PCall = GmpPrecompileCall<Runtime>;
252

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
462
pub struct CurrencyIdToMultiLocation;
463

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

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

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

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

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

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

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