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, ConstU32, 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::{
29
	mock_account,
30
	precompile_set::*,
31
	testing::{AddressInPrefixedSet, MockAccount},
32
};
33
use scale_info::TypeInfo;
34
use sp_core::H256;
35
use sp_io;
36
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
37
use sp_runtime::BuildStorage;
38
use xcm::latest::{prelude::*, Error as XcmError};
39
use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds, IsConcrete};
40
use xcm_executor::{
41
	traits::{TransactAsset, WeightTrader},
42
	AssetsInHolding,
43
};
44

            
45
pub type AccountId = MockAccount;
46
pub type Balance = u128;
47
pub type AssetId = u128;
48

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

            
51
// Configure a mock runtime to test the pallet.
52
115
construct_runtime!(
53
115
	pub enum Runtime {
54
115
		System: frame_system,
55
115
		Balances: pallet_balances,
56
115
		Evm: pallet_evm,
57
115
		Timestamp: pallet_timestamp,
58
115
		PolkadotXcm: pallet_xcm,
59
115
		XcmTransactor: pallet_xcm_transactor,
60
115
	}
61
115
);
62

            
63
28
mock_account!(AssetAccount(u128), |v: AssetAccount| AddressInPrefixedSet(
64
28
	0xffffffff, v.0
65
28
)
66
28
.into());
67
2
mock_account!(SelfReserveAccount, |_| MockAccount::from_u64(2));
68

            
69
parameter_types! {
70
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
71
}
72

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

            
129
// These parameters dont matter much as this will only be called by root with the forced arguments
130
// No deposit is substracted with those methods
131
parameter_types! {
132
	pub const AssetDeposit: Balance = 0;
133
	pub const ApprovalDeposit: Balance = 0;
134
	pub const AssetsStringLimit: u32 = 50;
135
	pub const MetadataDepositBase: Balance = 0;
136
	pub const MetadataDepositPerByte: Balance = 0;
137
}
138

            
139
pub type Precompiles<R> =
140
	PrecompileSetBuilder<R, (PrecompileAt<AddressU64<1>, XtokensPrecompile<R>>,)>;
141

            
142
pub type PCall = XtokensPrecompileCall<Runtime>;
143

            
144
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
145
/// Block storage limit in bytes. Set to 40 KB.
146
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
147

            
148
parameter_types! {
149
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
150
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
151
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
152
	pub GasLimitPovSizeRatio: u64 = {
153
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
154
		block_gas_limit.saturating_div(MAX_POV_SIZE)
155
	};
156
	pub GasLimitStorageGrowthRatio: u64 = {
157
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
158
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
159
	};
160
}
161

            
162
impl pallet_evm::Config for Runtime {
163
	type FeeCalculator = ();
164
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
165
	type WeightPerGas = WeightPerGas;
166
	type CallOrigin = EnsureAddressRoot<AccountId>;
167
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
168
	type AddressMapping = AccountId;
169
	type Currency = Balances;
170
	type RuntimeEvent = RuntimeEvent;
171
	type Runner = pallet_evm::runner::stack::Runner<Self>;
172
	type PrecompilesType = Precompiles<Self>;
173
	type PrecompilesValue = PrecompilesValue;
174
	type ChainId = ();
175
	type OnChargeTransaction = ();
176
	type BlockGasLimit = BlockGasLimit;
177
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
178
	type FindAuthor = ();
179
	type OnCreate = ();
180
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
181
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
182
	type Timestamp = Timestamp;
183
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
184
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
185
	type CreateOriginFilter = ();
186
	type CreateInnerOriginFilter = ();
187
}
188

            
189
parameter_types! {
190
	pub const MinimumPeriod: u64 = 5;
191
}
192
impl pallet_timestamp::Config for Runtime {
193
	type Moment = u64;
194
	type OnTimestampSet = ();
195
	type MinimumPeriod = MinimumPeriod;
196
	type WeightInfo = ();
197
}
198
pub struct ConvertOriginToLocal;
199
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
200
	type Success = Location;
201

            
202
13
	fn try_origin(_: Origin) -> Result<Location, Origin> {
203
13
		Ok(Location::here())
204
13
	}
205

            
206
	#[cfg(feature = "runtime-benchmarks")]
207
	fn try_successful_origin() -> Result<Origin, ()> {
208
		Ok(Origin::root())
209
	}
210
}
211

            
212
pub struct DoNothingRouter;
213
impl SendXcm for DoNothingRouter {
214
	type Ticket = ();
215

            
216
13
	fn validate(
217
13
		_destination: &mut Option<Location>,
218
13
		_message: &mut Option<Xcm<()>>,
219
13
	) -> SendResult<Self::Ticket> {
220
13
		Ok(((), Assets::new()))
221
13
	}
222

            
223
13
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
224
13
		Ok(XcmHash::default())
225
13
	}
226
}
227

            
228
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
229

            
230
pub struct DummyAssetTransactor;
231
impl TransactAsset for DummyAssetTransactor {
232
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
233
		Ok(())
234
	}
235

            
236
15
	fn withdraw_asset(
237
15
		_what: &Asset,
238
15
		_who: &Location,
239
15
		_maybe_context: Option<&XcmContext>,
240
15
	) -> Result<AssetsInHolding, XcmError> {
241
15
		Ok(AssetsInHolding::default())
242
15
	}
243
}
244

            
245
pub struct DummyWeightTrader;
246
impl WeightTrader for DummyWeightTrader {
247
13
	fn new() -> Self {
248
13
		DummyWeightTrader
249
13
	}
250

            
251
	fn buy_weight(
252
		&mut self,
253
		_weight: Weight,
254
		_payment: AssetsInHolding,
255
		_context: &XcmContext,
256
	) -> Result<AssetsInHolding, XcmError> {
257
		Ok(AssetsInHolding::default())
258
	}
259
}
260

            
261
parameter_types! {
262
	pub UniversalLocation: InteriorLocation = Here;
263
	pub MatcherLocation: Location = Location::here();
264
	pub const MaxAssetsIntoHolding: u32 = 64;
265
}
266

            
267
impl pallet_xcm::Config for Runtime {
268
	// The config types here are entirely configurable, since the only one that is sorely needed
269
	// is `XcmExecutor`, which will be used in unit tests located in xcm-executor.
270
	type RuntimeEvent = RuntimeEvent;
271
	type ExecuteXcmOrigin = ConvertOriginToLocal;
272
	type UniversalLocation = UniversalLocation;
273
	type SendXcmOrigin = ConvertOriginToLocal;
274
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
275
	type XcmRouter = DoNothingRouter;
276
	type XcmExecuteFilter = frame_support::traits::Everything;
277
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
278
	type XcmTeleportFilter = frame_support::traits::Everything;
279
	type XcmReserveTransferFilter = frame_support::traits::Everything;
280
	type RuntimeOrigin = RuntimeOrigin;
281
	type RuntimeCall = RuntimeCall;
282
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
283
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
284
	type Currency = Balances;
285
	type CurrencyMatcher = IsConcrete<MatcherLocation>;
286
	type TrustedLockers = ();
287
	type SovereignAccountOf = ();
288
	type MaxLockers = ConstU32<8>;
289
	type WeightInfo = pallet_xcm::TestWeightInfo;
290
	type MaxRemoteLockConsumers = ConstU32<0>;
291
	type RemoteLockConsumerIdentifier = ();
292
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
293
	type AuthorizedAliasConsideration = Disabled;
294
	type AssetHubMigrationStarted = ConstBool<false>;
295
}
296

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

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

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

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

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

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

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

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

            
356
impl pallet_xcm_transactor::Config for Runtime {
357
	type RuntimeEvent = RuntimeEvent;
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 = xcm_builder::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
pub struct XcmConfig;
379
impl xcm_executor::Config for XcmConfig {
380
	type RuntimeCall = RuntimeCall;
381
	type XcmSender = DoNothingRouter;
382
	type AssetTransactor = DummyAssetTransactor;
383
	type OriginConverter = pallet_xcm::XcmPassthrough<RuntimeOrigin>;
384
	type IsReserve = xcm_primitives::MultiNativeAsset<xcm_primitives::RelativeReserveProvider>;
385
	type IsTeleporter = ();
386
	type UniversalLocation = UniversalLocation;
387
	type Barrier = Barrier;
388
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
389
	type Trader = DummyWeightTrader;
390
	type ResponseHandler = ();
391
	type SubscriptionService = ();
392
	type AssetTrap = ();
393
	type AssetClaims = ();
394
	type CallDispatcher = RuntimeCall;
395
	type AssetLocker = ();
396
	type AssetExchanger = ();
397
	type PalletInstancesInfo = ();
398
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
399
	type FeeManager = ();
400
	type MessageExporter = ();
401
	type UniversalAliases = Nothing;
402
	type SafeCallFilter = Everything;
403
	type Aliasers = Nothing;
404
	type TransactionalProcessor = ();
405
	type HrmpNewChannelOpenRequestHandler = ();
406
	type HrmpChannelAcceptedHandler = ();
407
	type HrmpChannelClosingHandler = ();
408
	type XcmRecorder = ();
409
	type XcmEventEmitter = ();
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
8
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
425
8
		match account {
426
8
			a if a.has_prefix_u32(0xffffffff) => Some(CurrencyId::OtherReserve(a.without_prefix())),
427
1
			a if a == AccountId::from(SelfReserveAccount) => Some(CurrencyId::SelfReserve),
428
			_ => None,
429
		}
430
8
	}
431
}
432

            
433
pub struct CurrencyIdToMultiLocation;
434

            
435
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToMultiLocation {
436
8
	fn convert(currency: CurrencyId) -> Option<Location> {
437
8
		match currency {
438
			CurrencyId::SelfReserve => {
439
1
				let multi: Location = SelfReserve::get();
440
1
				Some(multi)
441
			}
442
			// To distinguish between relay and others, specially for reserve asset
443
7
			CurrencyId::OtherReserve(asset) => {
444
7
				if asset == 0 {
445
3
					Some(Location::parent())
446
				} else {
447
4
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
448
				}
449
			}
450
		}
451
8
	}
452
}
453

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

            
468
parameter_types! {
469
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
470

            
471
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
472
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
473
	pub const MaxAssetsForTransfer: usize = 2;
474

            
475
	pub SelfLocation: Location =
476
		Location::new(1, [Parachain(ParachainId::get().into())]);
477

            
478
	pub SelfReserve: Location = Location::new(
479
		1,
480
		[
481
			Parachain(ParachainId::get().into()),
482
			PalletInstance(
483
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
484
			)
485
		]);
486
	pub MaxInstructions: u32 = 100;
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
19
	fn default() -> ExtBuilder {
496
19
		ExtBuilder { balances: vec![] }
497
19
	}
498
}
499

            
500
impl ExtBuilder {
501
16
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
502
16
		self.balances = balances;
503
16
		self
504
16
	}
505
19
	pub(crate) fn build(self) -> sp_io::TestExternalities {
506
19
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
507
19
			.build_storage()
508
19
			.expect("Frame system builds valid default genesis config");
509
19

            
510
19
		pallet_balances::GenesisConfig::<Runtime> {
511
19
			balances: self.balances,
512
19
			dev_accounts: None,
513
19
		}
514
19
		.assimilate_storage(&mut t)
515
19
		.expect("Pallet balances storage can be assimilated");
516
19

            
517
19
		let mut ext = sp_io::TestExternalities::new(t);
518
19
		ext.execute_with(|| System::set_block_number(1));
519
19
		ext
520
19
	}
521
}
522

            
523
14
pub(crate) fn events() -> Vec<RuntimeEvent> {
524
14
	System::events()
525
14
		.into_iter()
526
20
		.map(|r| r.event)
527
14
		.collect::<Vec<_>>()
528
14
}