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 pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
25
use pallet_xcm_transactor::RelayIndices;
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
construct_runtime!(
50
	pub enum Runtime	{
51
		System: frame_system,
52
		Balances: pallet_balances,
53
		Evm: pallet_evm,
54
		Timestamp: pallet_timestamp,
55
		PolkadotXcm: pallet_xcm,
56
		XcmTransactor: pallet_xcm_transactor,
57
	}
58
);
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
}
169

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

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

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

            
216
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
217

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

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

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

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

            
249
pub type PCall = GmpPrecompileCall<Runtime>;
250

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
458
pub struct CurrencyIdToMultiLocation;
459

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

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

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

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

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

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

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