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
260
construct_runtime!(
55
260
	pub enum Runtime	{
56
260
		System: frame_system,
57
260
		Balances: pallet_balances,
58
260
		Evm: pallet_evm,
59
260
		Timestamp: pallet_timestamp,
60
260
		XcmTransactor: pallet_xcm_transactor,
61
260
	}
62
260
);
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
12
			0,
70
12
			[AccountKey20 {
71
12
				network: None,
72
12
				key: as_h160.as_fixed_bytes().clone(),
73
12
			}],
74
12
		)
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 RuntimeEvent = RuntimeEvent;
215
	type Runner = pallet_evm::runner::stack::Runner<Self>;
216
	type PrecompilesValue = PrecompilesValue;
217
	type PrecompilesType = Precompiles<Self>;
218
	type ChainId = ();
219
	type OnChargeTransaction = ();
220
	type BlockGasLimit = BlockGasLimit;
221
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
222
	type FindAuthor = ();
223
	type OnCreate = ();
224
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
225
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
226
	type Timestamp = Timestamp;
227
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
228
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
229
	type CreateOriginFilter = ();
230
	type CreateInnerOriginFilter = ();
231
}
232

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
376
impl TryFrom<u8> for MockTransactors {
377
	type Error = ();
378

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

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

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

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

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

            
416
pub struct CurrencyIdToLocation;
417

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

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

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

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

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

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