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
	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
construct_runtime!(
53
	pub enum Runtime {
54
		System: frame_system,
55
		Balances: pallet_balances,
56
		Evm: pallet_evm,
57
		Timestamp: pallet_timestamp,
58
		PolkadotXcm: pallet_xcm,
59
		XcmTransactor: pallet_xcm_transactor,
60
	}
61
);
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 Runner = pallet_evm::runner::stack::Runner<Self>;
171
	type PrecompilesType = Precompiles<Self>;
172
	type PrecompilesValue = PrecompilesValue;
173
	type ChainId = ();
174
	type OnChargeTransaction = ();
175
	type BlockGasLimit = BlockGasLimit;
176
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
177
	type FindAuthor = ();
178
	type OnCreate = ();
179
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
180
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
181
	type Timestamp = Timestamp;
182
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
183
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
184
	type CreateOriginFilter = ();
185
	type CreateInnerOriginFilter = ();
186
}
187

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

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

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

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

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

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

            
227
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
228

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
375
pub struct XcmConfig;
376
impl xcm_executor::Config for XcmConfig {
377
	type RuntimeCall = RuntimeCall;
378
	type XcmSender = DoNothingRouter;
379
	type AssetTransactor = DummyAssetTransactor;
380
	type OriginConverter = pallet_xcm::XcmPassthrough<RuntimeOrigin>;
381
	type IsReserve = xcm_primitives::MultiNativeAsset<xcm_primitives::RelativeReserveProvider>;
382
	type IsTeleporter = ();
383
	type UniversalLocation = UniversalLocation;
384
	type Barrier = Barrier;
385
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
386
	type Trader = DummyWeightTrader;
387
	type ResponseHandler = ();
388
	type SubscriptionService = ();
389
	type AssetTrap = ();
390
	type AssetClaims = ();
391
	type CallDispatcher = RuntimeCall;
392
	type AssetLocker = ();
393
	type AssetExchanger = ();
394
	type PalletInstancesInfo = ();
395
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
396
	type FeeManager = ();
397
	type MessageExporter = ();
398
	type UniversalAliases = Nothing;
399
	type SafeCallFilter = Everything;
400
	type Aliasers = Nothing;
401
	type TransactionalProcessor = ();
402
	type HrmpNewChannelOpenRequestHandler = ();
403
	type HrmpChannelAcceptedHandler = ();
404
	type HrmpChannelClosingHandler = ();
405
	type XcmRecorder = ();
406
	type XcmEventEmitter = ();
407
}
408

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

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

            
430
pub struct CurrencyIdToMultiLocation;
431

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

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

            
465
parameter_types! {
466
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
467

            
468
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
469
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
470
	pub const MaxAssetsForTransfer: usize = 2;
471

            
472
	pub SelfLocation: Location =
473
		Location::new(1, [Parachain(ParachainId::get().into())]);
474

            
475
	pub SelfReserve: Location = Location::new(
476
		1,
477
		[
478
			Parachain(ParachainId::get().into()),
479
			PalletInstance(
480
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
481
			)
482
		]);
483
	pub MaxInstructions: u32 = 100;
484
}
485

            
486
pub(crate) struct ExtBuilder {
487
	// endowed accounts with balances
488
	balances: Vec<(AccountId, Balance)>,
489
}
490

            
491
impl Default for ExtBuilder {
492
19
	fn default() -> ExtBuilder {
493
19
		ExtBuilder { balances: vec![] }
494
19
	}
495
}
496

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

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

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

            
520
14
pub(crate) fn events() -> Vec<RuntimeEvent> {
521
14
	System::events()
522
14
		.into_iter()
523
14
		.map(|r| r.event)
524
14
		.collect::<Vec<_>>()
525
14
}