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 crate::v1::{XcmTransactorPrecompileV1, XcmTransactorPrecompileV1Call};
19
use crate::v2::{XcmTransactorPrecompileV2, XcmTransactorPrecompileV2Call};
20
use crate::v3::{XcmTransactorPrecompileV3, XcmTransactorPrecompileV3Call};
21
use frame_support::{
22
	construct_runtime, parameter_types,
23
	traits::{Everything, PalletInfo as PalletInfoTrait},
24
	weights::{RuntimeDbWeight, Weight},
25
};
26
use pallet_evm::{
27
	EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider, GasWeightMapping,
28
};
29
use pallet_xcm_transactor::RelayIndices;
30
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
31
use precompile_utils::{
32
	mock_account,
33
	precompile_set::*,
34
	testing::{AddressInPrefixedSet, MockAccount},
35
};
36
use scale_info::TypeInfo;
37
use sp_core::{H160, H256, U256};
38
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
39
use sp_runtime::BuildStorage;
40
use xcm::latest::{prelude::*, Error as XcmError};
41
use xcm_builder::FixedWeightBounds;
42
use xcm_executor::{
43
	traits::{TransactAsset, WeightTrader},
44
	AssetsInHolding,
45
};
46
use xcm_primitives::AccountIdToCurrencyId;
47

            
48
pub type AccountId = MockAccount;
49
pub type Balance = u128;
50

            
51
type Block = frame_system::mocking::MockBlockU32<Runtime>;
52

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

            
64
pub struct AccountIdToLocation;
65
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
66
12
	fn convert(account: AccountId) -> Location {
67
12
		let as_h160: H160 = account.into();
68
12
		Location::new(
69
			0,
70
12
			[AccountKey20 {
71
12
				network: None,
72
12
				key: as_h160.as_fixed_bytes().clone(),
73
12
			}],
74
		)
75
12
	}
76
}
77

            
78
pub type AssetId = u128;
79

            
80
parameter_types! {
81
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
82
}
83

            
84
parameter_types! {
85
	pub const BlockHashCount: u32 = 250;
86
	pub const SS58Prefix: u8 = 42;
87
	pub const MockDbWeight: RuntimeDbWeight = RuntimeDbWeight {
88
		read: 1,
89
		write: 5,
90
	};
91
}
92

            
93
impl frame_system::Config for Runtime {
94
	type BaseCallFilter = Everything;
95
	type DbWeight = MockDbWeight;
96
	type RuntimeOrigin = RuntimeOrigin;
97
	type RuntimeTask = RuntimeTask;
98
	type Nonce = u64;
99
	type Block = Block;
100
	type RuntimeCall = RuntimeCall;
101
	type Hash = H256;
102
	type Hashing = BlakeTwo256;
103
	type AccountId = AccountId;
104
	type Lookup = IdentityLookup<Self::AccountId>;
105
	type RuntimeEvent = RuntimeEvent;
106
	type BlockHashCount = BlockHashCount;
107
	type Version = ();
108
	type PalletInfo = PalletInfo;
109
	type AccountData = pallet_balances::AccountData<Balance>;
110
	type OnNewAccount = ();
111
	type OnKilledAccount = ();
112
	type SystemWeightInfo = ();
113
	type BlockWeights = ();
114
	type BlockLength = ();
115
	type SS58Prefix = SS58Prefix;
116
	type OnSetCode = ();
117
	type MaxConsumers = frame_support::traits::ConstU32<16>;
118
	type SingleBlockMigrations = ();
119
	type MultiBlockMigrator = ();
120
	type PreInherents = ();
121
	type PostInherents = ();
122
	type PostTransactions = ();
123
	type ExtensionsWeightInfo = ();
124
}
125
parameter_types! {
126
	pub const ExistentialDeposit: u128 = 0;
127
}
128
impl pallet_balances::Config for Runtime {
129
	type MaxReserves = ();
130
	type ReserveIdentifier = ();
131
	type MaxLocks = ();
132
	type Balance = Balance;
133
	type RuntimeEvent = RuntimeEvent;
134
	type DustRemoval = ();
135
	type ExistentialDeposit = ExistentialDeposit;
136
	type AccountStore = System;
137
	type WeightInfo = ();
138
	type RuntimeHoldReason = ();
139
	type FreezeIdentifier = ();
140
	type MaxFreezes = ();
141
	type RuntimeFreezeReason = ();
142
	type DoneSlashHandler = ();
143
}
144

            
145
// These parameters dont matter much as this will only be called by root with the forced arguments
146
// No deposit is substracted with those methods
147
parameter_types! {
148
	pub const AssetDeposit: Balance = 0;
149
	pub const ApprovalDeposit: Balance = 0;
150
	pub const AssetsStringLimit: u32 = 50;
151
	pub const MetadataDepositBase: Balance = 0;
152
	pub const MetadataDepositPerByte: Balance = 0;
153
}
154

            
155
pub type Precompiles<R> = PrecompileSetBuilder<
156
	R,
157
	(
158
		PrecompileAt<AddressU64<1>, XcmTransactorPrecompileV1<R>, CallableByContract>,
159
		PrecompileAt<AddressU64<2>, XcmTransactorPrecompileV2<R>, CallableByContract>,
160
		PrecompileAt<AddressU64<4>, XcmTransactorPrecompileV3<R>, CallableByContract>,
161
	),
162
>;
163

            
164
15
mock_account!(TransactorV1, |_| MockAccount::from_u64(1));
165
5
mock_account!(TransactorV2, |_| MockAccount::from_u64(2));
166
6
mock_account!(TransactorV3, |_| MockAccount::from_u64(4));
167
mock_account!(SelfReserveAddress, |_| MockAccount::from_u64(3));
168
6
mock_account!(AssetAddress(u128), |value: AssetAddress| {
169
6
	AddressInPrefixedSet(0xffffffff, value.0).into()
170
6
});
171

            
172
pub type PCallV1 = XcmTransactorPrecompileV1Call<Runtime>;
173
pub type PCallV2 = XcmTransactorPrecompileV2Call<Runtime>;
174
pub type PCallV3 = XcmTransactorPrecompileV3Call<Runtime>;
175

            
176
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
177
/// Block storage limit in bytes. Set to 40 KB.
178
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
179

            
180
parameter_types! {
181
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
182
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
183
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
184
	pub GasLimitPovSizeRatio: u64 = {
185
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
186
		block_gas_limit.saturating_div(MAX_POV_SIZE)
187
	};
188
	pub GasLimitStorageGrowthRatio: u64 = {
189
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
190
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
191
	};
192
}
193

            
194
/// A mapping function that converts Ethereum gas to Substrate weight
195
/// We are mocking this 1-1 to test db read charges too
196
pub struct MockGasWeightMapping;
197
impl GasWeightMapping for MockGasWeightMapping {
198
	fn gas_to_weight(gas: u64, _without_base_weight: bool) -> Weight {
199
		Weight::from_parts(gas, 1)
200
	}
201
105
	fn weight_to_gas(weight: Weight) -> u64 {
202
105
		weight.ref_time().into()
203
105
	}
204
}
205

            
206
impl pallet_evm::Config for Runtime {
207
	type FeeCalculator = ();
208
	type GasWeightMapping = MockGasWeightMapping;
209
	type WeightPerGas = WeightPerGas;
210
	type CallOrigin = EnsureAddressRoot<AccountId>;
211
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
212
	type AddressMapping = AccountId;
213
	type Currency = Balances;
214
	type Runner = pallet_evm::runner::stack::Runner<Self>;
215
	type PrecompilesValue = PrecompilesValue;
216
	type PrecompilesType = Precompiles<Self>;
217
	type ChainId = ();
218
	type OnChargeTransaction = ();
219
	type BlockGasLimit = BlockGasLimit;
220
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
221
	type FindAuthor = ();
222
	type OnCreate = ();
223
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
224
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
225
	type Timestamp = Timestamp;
226
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
227
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
228
	type CreateOriginFilter = ();
229
	type CreateInnerOriginFilter = ();
230
}
231

            
232
parameter_types! {
233
	pub const MinimumPeriod: u64 = 5;
234
}
235
impl pallet_timestamp::Config for Runtime {
236
	type Moment = u64;
237
	type OnTimestampSet = ();
238
	type MinimumPeriod = MinimumPeriod;
239
	type WeightInfo = ();
240
}
241

            
242
pub struct DoNothingRouter;
243
impl SendXcm for DoNothingRouter {
244
	type Ticket = ();
245

            
246
12
	fn validate(
247
12
		_destination: &mut Option<Location>,
248
12
		_message: &mut Option<Xcm<()>>,
249
12
	) -> SendResult<Self::Ticket> {
250
12
		Ok(((), Assets::new()))
251
12
	}
252

            
253
12
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
254
12
		Ok(XcmHash::default())
255
12
	}
256
}
257

            
258
pub struct DummyAssetTransactor;
259
impl TransactAsset for DummyAssetTransactor {
260
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
261
		Ok(())
262
	}
263

            
264
6
	fn withdraw_asset(
265
6
		_what: &Asset,
266
6
		_who: &Location,
267
6
		_maybe_context: Option<&XcmContext>,
268
6
	) -> Result<AssetsInHolding, XcmError> {
269
6
		Ok(AssetsInHolding::default())
270
6
	}
271
}
272

            
273
pub struct DummyWeightTrader;
274
impl WeightTrader for DummyWeightTrader {
275
	fn new() -> Self {
276
		DummyWeightTrader
277
	}
278

            
279
	fn buy_weight(
280
		&mut self,
281
		_weight: Weight,
282
		_payment: AssetsInHolding,
283
		_context: &XcmContext,
284
	) -> Result<AssetsInHolding, XcmError> {
285
		Ok(AssetsInHolding::default())
286
	}
287
}
288

            
289
#[derive(
290
	Clone,
291
	Eq,
292
	Debug,
293
	PartialEq,
294
	Ord,
295
	PartialOrd,
296
	Encode,
297
	Decode,
298
	scale_info::TypeInfo,
299
	DecodeWithMemTracking,
300
)]
301
pub enum CurrencyId {
302
	SelfReserve,
303
	OtherReserve(AssetId),
304
}
305

            
306
parameter_types! {
307
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
308

            
309
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
310
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
311

            
312
	pub SelfLocation: Location =
313
		Location::new(1, [Parachain(ParachainId::get().into())]);
314

            
315
	pub SelfReserve: Location = Location::new(
316
		1,
317
		[
318
			Parachain(ParachainId::get().into()),
319
			PalletInstance(
320
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
321
			)
322
		]);
323
	pub MaxInstructions: u32 = 100;
324

            
325
	pub UniversalLocation: InteriorLocation = Here;
326
	pub SelfLocationAbsolute: Location = Location {
327
		parents: 1,
328
		interior: [Parachain(ParachainId::get().into())].into(),
329
	};
330
}
331

            
332
impl pallet_xcm_transactor::Config for Runtime {
333
	type Balance = Balance;
334
	type Transactor = MockTransactors;
335
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
336
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
337
	type CurrencyId = CurrencyId;
338
	type AccountIdToLocation = AccountIdToLocation;
339
	type CurrencyIdToLocation = CurrencyIdToLocation;
340
	type SelfLocation = SelfLocation;
341
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
342
	type UniversalLocation = UniversalLocation;
343
	type BaseXcmWeight = BaseXcmWeight;
344
	type XcmSender = DoNothingRouter;
345
	type AssetTransactor = DummyAssetTransactor;
346
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
347
	type WeightInfo = ();
348
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
349
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
350
	type MaxHrmpFee = ();
351
}
352

            
353
// We need to use the encoding from the relay mock runtime
354
#[derive(Encode, Decode)]
355
pub enum RelayCall {
356
	#[codec(index = 5u8)]
357
	// the index should match the position of the module in `construct_runtime!`
358
	Utility(UtilityCall),
359
}
360

            
361
#[derive(Encode, Decode)]
362
pub enum UtilityCall {
363
	#[codec(index = 1u8)]
364
	AsDerivative(u16),
365
}
366

            
367
#[derive(
368
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
369
)]
370
pub enum MockTransactors {
371
	Relay,
372
}
373

            
374
impl TryFrom<u8> for MockTransactors {
375
	type Error = ();
376

            
377
6
	fn try_from(value: u8) -> Result<Self, Self::Error> {
378
6
		match value {
379
6
			0x0 => Ok(MockTransactors::Relay),
380
			_ => Err(()),
381
		}
382
6
	}
383
}
384

            
385
impl xcm_primitives::XcmTransact for MockTransactors {
386
6
	fn destination(self) -> Location {
387
6
		match self {
388
6
			MockTransactors::Relay => Location::parent(),
389
		}
390
6
	}
391

            
392
6
	fn utility_pallet_index(&self) -> u8 {
393
6
		RelayIndices::<Runtime>::get().utility
394
6
	}
395

            
396
	fn staking_pallet_index(&self) -> u8 {
397
		RelayIndices::<Runtime>::get().staking
398
	}
399
}
400

            
401
// Implement the trait, where we convert AccountId to AssetID
402
impl AccountIdToCurrencyId<AccountId, CurrencyId> for Runtime {
403
	/// The way to convert an account to assetId is by ensuring that the prefix is 0XFFFFFFFF
404
	/// and by taking the lowest 128 bits as the assetId
405
6
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
406
6
		match account {
407
6
			a if a.has_prefix_u32(0xffffffff) => Some(CurrencyId::OtherReserve(a.without_prefix())),
408
			a if a == SelfReserveAddress.into() => Some(CurrencyId::SelfReserve),
409
			_ => None,
410
		}
411
6
	}
412
}
413

            
414
pub struct CurrencyIdToLocation;
415

            
416
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToLocation {
417
6
	fn convert(currency: CurrencyId) -> Option<Location> {
418
6
		match currency {
419
			CurrencyId::SelfReserve => {
420
				let multi: Location = SelfReserve::get();
421
				Some(multi)
422
			}
423
			// To distinguish between relay and others, specially for reserve asset
424
6
			CurrencyId::OtherReserve(asset) => {
425
6
				if asset == 0 {
426
6
					Some(Location::parent())
427
				} else {
428
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
429
				}
430
			}
431
		}
432
6
	}
433
}
434

            
435
pub(crate) struct ExtBuilder {
436
	// endowed accounts with balances
437
	balances: Vec<(AccountId, Balance)>,
438
}
439

            
440
impl Default for ExtBuilder {
441
20
	fn default() -> ExtBuilder {
442
20
		ExtBuilder { balances: vec![] }
443
20
	}
444
}
445

            
446
impl ExtBuilder {
447
17
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
448
17
		self.balances = balances;
449
17
		self
450
17
	}
451
20
	pub(crate) fn build(self) -> sp_io::TestExternalities {
452
20
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
453
20
			.build_storage()
454
20
			.expect("Frame system builds valid default genesis config");
455

            
456
20
		pallet_balances::GenesisConfig::<Runtime> {
457
20
			balances: self.balances,
458
20
			dev_accounts: None,
459
20
		}
460
20
		.assimilate_storage(&mut t)
461
20
		.expect("Pallet balances storage can be assimilated");
462

            
463
20
		let mut ext = sp_io::TestExternalities::new(t);
464
20
		ext.execute_with(|| System::set_block_number(1));
465
20
		ext
466
20
	}
467
}