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 parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
27
use precompile_utils::{mock_account, precompile_set::*, testing::MockAccount};
28
use scale_info::TypeInfo;
29
use sp_core::H256;
30
use sp_runtime::BuildStorage;
31
use sp_runtime::{
32
	traits::{BlakeTwo256, IdentityLookup},
33
	Perbill,
34
};
35
use xcm::latest::{prelude::*, Error as XcmError};
36
use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds};
37
use xcm_executor::{
38
	traits::{TransactAsset, WeightTrader},
39
	AssetsInHolding,
40
};
41

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

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

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

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

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

            
67
parameter_types! {
68
	pub const BlockHashCount: u32 = 250;
69
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
70
	pub const MaximumBlockLength: u32 = 2 * 1024;
71
	pub const AvailableBlockRatio: Perbill = Perbill::one();
72
	pub const SS58Prefix: u8 = 42;
73
}
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 = [u8; 4];
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
pub struct DoNothingRouter;
128
impl SendXcm for DoNothingRouter {
129
	type Ticket = ();
130

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

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

            
143
impl pallet_xcm::Config for Runtime {
144
	type RuntimeEvent = RuntimeEvent;
145
	type ExecuteXcmOrigin = ConvertOriginToLocal;
146
	type XcmExecuteFilter = Everything;
147
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
148
	type XcmRouter = DoNothingRouter;
149
	type SendXcmOrigin = ConvertOriginToLocal;
150
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
151
	type UniversalLocation = UniversalLocation;
152
	type XcmTeleportFilter = frame_support::traits::Everything;
153
	type XcmReserveTransferFilter = frame_support::traits::Everything;
154
	type RuntimeOrigin = RuntimeOrigin;
155
	type RuntimeCall = RuntimeCall;
156
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
157
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
158
	type Currency = Balances;
159
	type CurrencyMatcher = ();
160
	type TrustedLockers = ();
161
	type SovereignAccountOf = ();
162
	type MaxLockers = ConstU32<8>;
163
	type WeightInfo = pallet_xcm::TestWeightInfo;
164
	type MaxRemoteLockConsumers = ConstU32<0>;
165
	type RemoteLockConsumerIdentifier = ();
166
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
167
	type AuthorizedAliasConsideration = Disabled;
168
	type AssetHubMigrationStarted = ConstBool<false>;
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 RuntimeEvent = RuntimeEvent;
282
	type Runner = pallet_evm::runner::stack::Runner<Self>;
283
	type PrecompilesType = Precompiles<Runtime>;
284
	type PrecompilesValue = PrecompilesValue;
285
	type ChainId = ();
286
	type OnChargeTransaction = ();
287
	type BlockGasLimit = BlockGasLimit;
288
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
289
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
290
	type FindAuthor = ();
291
	type OnCreate = ();
292
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
293
	type Timestamp = Timestamp;
294
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
295
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
296
	type CreateOriginFilter = ();
297
	type CreateInnerOriginFilter = ();
298
}
299

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

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

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

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

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

            
344
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
345
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
346
		match self {
347
			MockTransactors::Relay => match call {
348
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
349
					let mut call =
350
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
351
					call.append(&mut b.clone());
352
					call
353
				}
354
			},
355
		}
356
	}
357
}
358

            
359
parameter_types! {
360
	pub SelfLocationAbsolute: Location = Location {
361
		parents: 1,
362
		interior: [Parachain(ParachainId::get().into())].into(),
363
	};
364
}
365

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

            
388
parameter_types! {
389
	pub const MinimumPeriod: u64 = 5;
390
}
391
impl pallet_timestamp::Config for Runtime {
392
	type Moment = u64;
393
	type OnTimestampSet = ();
394
	type MinimumPeriod = MinimumPeriod;
395
	type WeightInfo = ();
396
}
397

            
398
pub struct ConvertOriginToLocal;
399
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
400
	type Success = Location;
401

            
402
	fn try_origin(_: Origin) -> Result<Location, Origin> {
403
		Ok(Location::here())
404
	}
405

            
406
	#[cfg(feature = "runtime-benchmarks")]
407
	fn try_successful_origin() -> Result<Origin, ()> {
408
		Ok(Origin::root())
409
	}
410
}
411

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

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

            
433
pub struct AccountIdToLocation;
434
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
435
	fn convert(account: AccountId) -> Location {
436
		let as_h160: H160 = account.into();
437
		Location::new(
438
			1,
439
			[AccountKey20 {
440
				network: None,
441
				key: as_h160.as_fixed_bytes().clone(),
442
			}],
443
		)
444
	}
445
}
446

            
447
parameter_types! {
448
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
449

            
450
	pub const BaseXcmWeight: XcmV2Weight = 1000;
451
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
452
	pub const MaxAssetsForTransfer: usize = 2;
453

            
454
	pub SelfLocation: Location =
455
		Location::new(1, [Parachain(ParachainId::get().into())]);
456

            
457
	pub SelfReserve: Location = Location::new(
458
		1,
459
		[
460
			Parachain(ParachainId::get().into()),
461
			PalletInstance(
462
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
463
			)
464
		]);
465
	pub MaxInstructions: u32 = 100;
466
}
467

            
468
pub struct CurrencyIdToMultiLocation;
469

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

            
489
pub(crate) struct ExtBuilder {
490
	/// Endowed accounts with balances
491
	balances: Vec<(AccountId, Balance)>,
492
}
493

            
494
impl Default for ExtBuilder {
495
3
	fn default() -> ExtBuilder {
496
3
		ExtBuilder { balances: vec![] }
497
3
	}
498
}
499

            
500
impl ExtBuilder {
501
	/// Fund some accounts before starting the test
502
3
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
503
3
		self.balances = balances;
504
3
		self
505
3
	}
506

            
507
	/// Build the test externalities for use in tests
508
3
	pub(crate) fn build(self) -> sp_io::TestExternalities {
509
3
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
510
3
			.build_storage()
511
3
			.expect("Frame system builds valid default genesis config");
512
3

            
513
3
		pallet_balances::GenesisConfig::<Runtime> {
514
3
			balances: self.balances.clone(),
515
3
			dev_accounts: None,
516
3
		}
517
3
		.assimilate_storage(&mut t)
518
3
		.expect("Pallet balances storage can be assimilated");
519
3

            
520
3
		let mut ext = sp_io::TestExternalities::new(t);
521
3
		ext.execute_with(|| {
522
3
			System::set_block_number(1);
523
3
		});
524
3
		ext
525
3
	}
526
}