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,
331
	Eq,
332
	Debug,
333
	PartialEq,
334
	Ord,
335
	PartialOrd,
336
	Encode,
337
	Decode,
338
	TypeInfo,
339
	DecodeWithMemTracking,
340
	serde::Serialize,
341
	serde::Deserialize,
342
)]
343
pub enum MockTransactors {
344
	Relay,
345
	AssetHub,
346
}
347

            
348
impl xcm_primitives::XcmTransact for MockTransactors {
349
	fn destination(self) -> Location {
350
		match self {
351
			MockTransactors::Relay => Location::parent(),
352
			MockTransactors::AssetHub => Location::new(1, [Parachain(1000)]),
353
		}
354
	}
355
}
356

            
357
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
358
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
359
		match self {
360
			MockTransactors::Relay | MockTransactors::AssetHub => match call {
361
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
362
					let mut call =
363
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
364
					call.append(&mut b.clone());
365
					call
366
				}
367
			},
368
		}
369
	}
370
}
371

            
372
impl xcm_primitives::RelayChainTransactor for MockTransactors {
373
1
	fn relay() -> Self {
374
1
		MockTransactors::Relay
375
1
	}
376
}
377

            
378
impl xcm_primitives::AssetHubTransactor for MockTransactors {
379
1
	fn asset_hub() -> Self {
380
1
		MockTransactors::AssetHub
381
1
	}
382
}
383

            
384
parameter_types! {
385
	pub SelfLocationAbsolute: Location = Location {
386
		parents: 1,
387
		interior: [Parachain(ParachainId::get().into())].into(),
388
	};
389
}
390

            
391
impl pallet_xcm_transactor::Config for Runtime {
392
	type RuntimeEvent = RuntimeEvent;
393
	type Balance = Balance;
394
	type Transactor = MockTransactors;
395
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
396
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
397
	type CurrencyId = CurrencyId;
398
	type AccountIdToLocation = AccountIdToLocation;
399
	type CurrencyIdToLocation = CurrencyIdToMultiLocation;
400
	type SelfLocation = SelfLocation;
401
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
402
	type UniversalLocation = UniversalLocation;
403
	type BaseXcmWeight = BaseXcmWeight;
404
	type XcmSender = DoNothingRouter;
405
	type AssetTransactor = DummyAssetTransactor;
406
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
407
	type WeightInfo = ();
408
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
409
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
410
	type MaxHrmpFee = ();
411
}
412

            
413
parameter_types! {
414
	pub const MinimumPeriod: u64 = 5;
415
}
416
impl pallet_timestamp::Config for Runtime {
417
	type Moment = u64;
418
	type OnTimestampSet = ();
419
	type MinimumPeriod = MinimumPeriod;
420
	type WeightInfo = ();
421
}
422

            
423
pub struct ConvertOriginToLocal;
424
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
425
	type Success = Location;
426

            
427
	fn try_origin(_: Origin) -> Result<Location, Origin> {
428
		Ok(Location::here())
429
	}
430

            
431
	#[cfg(feature = "runtime-benchmarks")]
432
	fn try_successful_origin() -> Result<Origin, ()> {
433
		Ok(Origin::root())
434
	}
435
}
436

            
437
#[derive(
438
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
439
)]
440
pub enum CurrencyId {
441
	SelfReserve,
442
	OtherReserve(AssetId),
443
}
444

            
445
// Implement the trait, where we convert AccountId to AssetID
446
impl AccountIdToCurrencyId<AccountId, CurrencyId> for Runtime {
447
	/// The way to convert an account to assetId is by ensuring that the prefix is 0XFFFFFFFF
448
	/// and by taking the lowest 128 bits as the assetId
449
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
450
		match account {
451
			a if a.has_prefix_u32(0xffffffff) => Some(CurrencyId::OtherReserve(a.without_prefix())),
452
			a if a == AccountId::from(SelfReserveAccount) => Some(CurrencyId::SelfReserve),
453
			_ => None,
454
		}
455
	}
456
}
457

            
458
pub struct AccountIdToLocation;
459
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
460
	fn convert(account: AccountId) -> Location {
461
		let as_h160: H160 = account.into();
462
		Location::new(
463
			1,
464
			[AccountKey20 {
465
				network: None,
466
				key: as_h160.as_fixed_bytes().clone(),
467
			}],
468
		)
469
	}
470
}
471

            
472
parameter_types! {
473
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
474

            
475
	pub const BaseXcmWeight: XcmV2Weight = 1000;
476
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
477
	pub const MaxAssetsForTransfer: usize = 2;
478

            
479
	pub SelfLocation: Location =
480
		Location::new(1, [Parachain(ParachainId::get().into())]);
481

            
482
	pub SelfReserve: Location = Location::new(
483
		1,
484
		[
485
			Parachain(ParachainId::get().into()),
486
			PalletInstance(
487
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
488
			)
489
		]);
490
	pub MaxInstructions: u32 = 100;
491
}
492

            
493
pub struct CurrencyIdToMultiLocation;
494

            
495
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToMultiLocation {
496
	fn convert(currency: CurrencyId) -> Option<Location> {
497
		match currency {
498
			CurrencyId::SelfReserve => {
499
				let multi: Location = SelfReserve::get();
500
				Some(multi)
501
			}
502
			// To distinguish between relay and others, specially for reserve asset
503
			CurrencyId::OtherReserve(asset) => {
504
				if asset == 0 {
505
					Some(Location::parent())
506
				} else {
507
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
508
				}
509
			}
510
		}
511
	}
512
}
513

            
514
pub(crate) struct ExtBuilder {
515
	/// Endowed accounts with balances
516
	balances: Vec<(AccountId, Balance)>,
517
}
518

            
519
impl Default for ExtBuilder {
520
3
	fn default() -> ExtBuilder {
521
3
		ExtBuilder { balances: vec![] }
522
3
	}
523
}
524

            
525
impl ExtBuilder {
526
	/// Fund some accounts before starting the test
527
3
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
528
3
		self.balances = balances;
529
3
		self
530
3
	}
531

            
532
	/// Build the test externalities for use in tests
533
3
	pub(crate) fn build(self) -> sp_io::TestExternalities {
534
3
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
535
3
			.build_storage()
536
3
			.expect("Frame system builds valid default genesis config");
537
3

            
538
3
		pallet_balances::GenesisConfig::<Runtime> {
539
3
			balances: self.balances.clone(),
540
3
			dev_accounts: None,
541
3
		}
542
3
		.assimilate_storage(&mut t)
543
3
		.expect("Pallet balances storage can be assimilated");
544
3

            
545
3
		let mut ext = sp_io::TestExternalities::new(t);
546
3
		ext.execute_with(|| {
547
3
			System::set_block_number(1);
548
3
		});
549
3
		ext
550
3
	}
551
}