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

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

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

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

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

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

            
71
parameter_types! {
72
	pub const BlockHashCount: u32 = 250;
73
	pub const SS58Prefix: u8 = 42;
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
}
106
parameter_types! {
107
	pub const ExistentialDeposit: u128 = 0;
108
}
109
impl pallet_balances::Config for Runtime {
110
	type MaxReserves = ();
111
	type ReserveIdentifier = ();
112
	type MaxLocks = ();
113
	type Balance = Balance;
114
	type RuntimeEvent = RuntimeEvent;
115
	type DustRemoval = ();
116
	type ExistentialDeposit = ExistentialDeposit;
117
	type AccountStore = System;
118
	type WeightInfo = ();
119
	type RuntimeHoldReason = ();
120
	type FreezeIdentifier = ();
121
	type MaxFreezes = ();
122
	type RuntimeFreezeReason = ();
123
}
124

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

            
135
pub type Precompiles<R> =
136
	PrecompileSetBuilder<R, (PrecompileAt<AddressU64<1>, XtokensPrecompile<R>>,)>;
137

            
138
pub type PCall = XtokensPrecompileCall<Runtime>;
139

            
140
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
141
/// Block storage limit in bytes. Set to 40 KB.
142
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
143

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

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

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

            
197
13
	fn try_origin(_: Origin) -> Result<Location, Origin> {
198
13
		Ok(Location::here())
199
13
	}
200

            
201
	#[cfg(feature = "runtime-benchmarks")]
202
	fn try_successful_origin() -> Result<Origin, ()> {
203
		Ok(Origin::root())
204
	}
205
}
206

            
207
pub struct DoNothingRouter;
208
impl SendXcm for DoNothingRouter {
209
	type Ticket = ();
210

            
211
13
	fn validate(
212
13
		_destination: &mut Option<Location>,
213
13
		_message: &mut Option<Xcm<()>>,
214
13
	) -> SendResult<Self::Ticket> {
215
13
		Ok(((), Assets::new()))
216
13
	}
217

            
218
13
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
219
13
		Ok(XcmHash::default())
220
13
	}
221
}
222

            
223
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
224

            
225
pub struct DummyAssetTransactor;
226
impl TransactAsset for DummyAssetTransactor {
227
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
228
		Ok(())
229
	}
230

            
231
15
	fn withdraw_asset(
232
15
		_what: &Asset,
233
15
		_who: &Location,
234
15
		_maybe_context: Option<&XcmContext>,
235
15
	) -> Result<AssetsInHolding, XcmError> {
236
15
		Ok(AssetsInHolding::default())
237
15
	}
238
}
239

            
240
pub struct DummyWeightTrader;
241
impl WeightTrader for DummyWeightTrader {
242
13
	fn new() -> Self {
243
13
		DummyWeightTrader
244
13
	}
245

            
246
	fn buy_weight(
247
		&mut self,
248
		_weight: Weight,
249
		_payment: AssetsInHolding,
250
		_context: &XcmContext,
251
	) -> Result<AssetsInHolding, XcmError> {
252
		Ok(AssetsInHolding::default())
253
	}
254
}
255

            
256
parameter_types! {
257
	pub UniversalLocation: InteriorLocation = Here;
258
	pub MatcherLocation: Location = Location::here();
259
	pub const MaxAssetsIntoHolding: u32 = 64;
260
}
261

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

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

            
300
#[derive(Encode, Decode)]
301
pub enum UtilityCall {
302
	#[codec(index = 1u8)]
303
	AsDerivative(u16),
304
}
305

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

            
319
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
320
pub enum MockTransactors {
321
	Relay,
322
}
323

            
324
impl xcm_primitives::XcmTransact for MockTransactors {
325
	fn destination(self) -> Location {
326
		match self {
327
			MockTransactors::Relay => Location::parent(),
328
		}
329
	}
330
}
331

            
332
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
333
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
334
		match self {
335
			MockTransactors::Relay => match call {
336
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
337
					let mut call =
338
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
339
					call.append(&mut b.clone());
340
					call
341
				}
342
			},
343
		}
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 RuntimeEvent = RuntimeEvent;
356
	type Balance = Balance;
357
	type Transactor = MockTransactors;
358
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
359
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
360
	type CurrencyId = CurrencyId;
361
	type AccountIdToLocation = AccountIdToLocation;
362
	type CurrencyIdToLocation = CurrencyIdToMultiLocation;
363
	type SelfLocation = SelfLocation;
364
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
365
	type UniversalLocation = UniversalLocation;
366
	type BaseXcmWeight = BaseXcmWeight;
367
	type XcmSender = DoNothingRouter;
368
	type AssetTransactor = DummyAssetTransactor;
369
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
370
	type WeightInfo = ();
371
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
372
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
373
	type MaxHrmpFee = ();
374
}
375

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

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

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

            
428
pub struct CurrencyIdToMultiLocation;
429

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

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

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

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

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

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

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

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

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

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

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

            
517
14
pub(crate) fn events() -> Vec<RuntimeEvent> {
518
14
	System::events()
519
14
		.into_iter()
520
20
		.map(|r| r.event)
521
14
		.collect::<Vec<_>>()
522
14
}