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

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

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

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

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

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

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

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

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

            
141
pub type PCall = XtokensPrecompileCall<Runtime>;
142

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

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

            
161
impl pallet_evm::Config for Runtime {
162
	type FeeCalculator = ();
163
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
164
	type WeightPerGas = WeightPerGas;
165
	type CallOrigin = EnsureAddressRoot<AccountId>;
166
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
167
	type AddressMapping = AccountId;
168
	type Currency = Balances;
169
	type RuntimeEvent = RuntimeEvent;
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
	type AssetHubMigrationStarted = ConstBool<false>;
294
}
295

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

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

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

            
325
#[derive(
326
	Clone,
327
	Eq,
328
	Debug,
329
	PartialEq,
330
	Ord,
331
	PartialOrd,
332
	Encode,
333
	Decode,
334
	TypeInfo,
335
	DecodeWithMemTracking,
336
	serde::Serialize,
337
	serde::Deserialize,
338
)]
339
pub enum MockTransactors {
340
	Relay,
341
	AssetHub,
342
}
343

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

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

            
368
impl xcm_primitives::RelayChainTransactor for MockTransactors {
369
1
	fn relay() -> Self {
370
1
		MockTransactors::Relay
371
1
	}
372
}
373

            
374
impl xcm_primitives::AssetHubTransactor for MockTransactors {
375
1
	fn asset_hub() -> Self {
376
1
		MockTransactors::AssetHub
377
1
	}
378
}
379

            
380
parameter_types! {
381
	pub SelfLocationAbsolute: Location = Location {
382
		parents: 1,
383
		interior: [Parachain(ParachainId::get().into())].into(),
384
	};
385
}
386

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

            
409
pub struct XcmConfig;
410
impl xcm_executor::Config for XcmConfig {
411
	type RuntimeCall = RuntimeCall;
412
	type XcmSender = DoNothingRouter;
413
	type AssetTransactor = DummyAssetTransactor;
414
	type OriginConverter = pallet_xcm::XcmPassthrough<RuntimeOrigin>;
415
	type IsReserve = xcm_primitives::MultiNativeAsset<xcm_primitives::RelativeReserveProvider>;
416
	type IsTeleporter = ();
417
	type UniversalLocation = UniversalLocation;
418
	type Barrier = Barrier;
419
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
420
	type Trader = DummyWeightTrader;
421
	type ResponseHandler = ();
422
	type SubscriptionService = ();
423
	type AssetTrap = ();
424
	type AssetClaims = ();
425
	type CallDispatcher = RuntimeCall;
426
	type AssetLocker = ();
427
	type AssetExchanger = ();
428
	type PalletInstancesInfo = ();
429
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
430
	type FeeManager = ();
431
	type MessageExporter = ();
432
	type UniversalAliases = Nothing;
433
	type SafeCallFilter = Everything;
434
	type Aliasers = Nothing;
435
	type TransactionalProcessor = ();
436
	type HrmpNewChannelOpenRequestHandler = ();
437
	type HrmpChannelAcceptedHandler = ();
438
	type HrmpChannelClosingHandler = ();
439
	type XcmRecorder = ();
440
	type XcmEventEmitter = ();
441
}
442

            
443
#[derive(
444
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
445
)]
446
pub enum CurrencyId {
447
	SelfReserve,
448
	OtherReserve(AssetId),
449
}
450

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

            
464
pub struct CurrencyIdToMultiLocation;
465

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

            
485
pub struct AccountIdToLocation;
486
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
487
	fn convert(account: AccountId) -> Location {
488
		let as_h160: H160 = account.into();
489
		Location::new(
490
			1,
491
			[AccountKey20 {
492
				network: None,
493
				key: as_h160.as_fixed_bytes().clone(),
494
			}],
495
		)
496
	}
497
}
498

            
499
parameter_types! {
500
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
501

            
502
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
503
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
504
	pub const MaxAssetsForTransfer: usize = 2;
505

            
506
	pub SelfLocation: Location =
507
		Location::new(1, [Parachain(ParachainId::get().into())]);
508

            
509
	pub SelfReserve: Location = Location::new(
510
		1,
511
		[
512
			Parachain(ParachainId::get().into()),
513
			PalletInstance(
514
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
515
			)
516
		]);
517
	pub MaxInstructions: u32 = 100;
518
}
519

            
520
pub(crate) struct ExtBuilder {
521
	// endowed accounts with balances
522
	balances: Vec<(AccountId, Balance)>,
523
}
524

            
525
impl Default for ExtBuilder {
526
19
	fn default() -> ExtBuilder {
527
19
		ExtBuilder { balances: vec![] }
528
19
	}
529
}
530

            
531
impl ExtBuilder {
532
16
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
533
16
		self.balances = balances;
534
16
		self
535
16
	}
536
19
	pub(crate) fn build(self) -> sp_io::TestExternalities {
537
19
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
538
19
			.build_storage()
539
19
			.expect("Frame system builds valid default genesis config");
540
19

            
541
19
		pallet_balances::GenesisConfig::<Runtime> {
542
19
			balances: self.balances,
543
19
			dev_accounts: None,
544
19
		}
545
19
		.assimilate_storage(&mut t)
546
19
		.expect("Pallet balances storage can be assimilated");
547
19

            
548
19
		let mut ext = sp_io::TestExternalities::new(t);
549
19
		ext.execute_with(|| System::set_block_number(1));
550
19
		ext
551
19
	}
552
}
553

            
554
14
pub(crate) fn events() -> Vec<RuntimeEvent> {
555
14
	System::events()
556
14
		.into_iter()
557
20
		.map(|r| r.event)
558
14
		.collect::<Vec<_>>()
559
14
}