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

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

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

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

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

            
77
pub type AssetId = u128;
78

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

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

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

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

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

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

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

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

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

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

            
205
impl pallet_evm::Config for Runtime {
206
	type FeeCalculator = ();
207
	type GasWeightMapping = MockGasWeightMapping;
208
	type WeightPerGas = WeightPerGas;
209
	type CallOrigin = EnsureAddressRoot<AccountId>;
210
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
211
	type AddressMapping = AccountId;
212
	type Currency = Balances;
213
	type RuntimeEvent = RuntimeEvent;
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 RuntimeEvent = RuntimeEvent;
334
	type Balance = Balance;
335
	type Transactor = MockTransactors;
336
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
337
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
338
	type CurrencyId = CurrencyId;
339
	type AccountIdToLocation = AccountIdToLocation;
340
	type CurrencyIdToLocation = CurrencyIdToLocation;
341
	type SelfLocation = SelfLocation;
342
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
343
	type UniversalLocation = UniversalLocation;
344
	type BaseXcmWeight = BaseXcmWeight;
345
	type XcmSender = DoNothingRouter;
346
	type AssetTransactor = DummyAssetTransactor;
347
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
348
	type WeightInfo = ();
349
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
350
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
351
	type MaxHrmpFee = ();
352
}
353

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

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

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

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

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

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

            
394
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
395
6
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
396
6
		match self {
397
6
			MockTransactors::Relay => match call {
398
6
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
399
6
					let mut call =
400
6
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
401
6
					call.append(&mut b.clone());
402
6
					call
403
6
				}
404
6
			},
405
6
		}
406
6
	}
407
}
408

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

            
422
pub struct CurrencyIdToLocation;
423

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

            
443
pub(crate) struct ExtBuilder {
444
	// endowed accounts with balances
445
	balances: Vec<(AccountId, Balance)>,
446
}
447

            
448
impl Default for ExtBuilder {
449
20
	fn default() -> ExtBuilder {
450
20
		ExtBuilder { balances: vec![] }
451
20
	}
452
}
453

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

            
464
20
		pallet_balances::GenesisConfig::<Runtime> {
465
20
			balances: self.balances,
466
20
			dev_accounts: None,
467
20
		}
468
20
		.assimilate_storage(&mut t)
469
20
		.expect("Pallet balances storage can be assimilated");
470
20

            
471
20
		let mut ext = sp_io::TestExternalities::new(t);
472
20
		ext.execute_with(|| System::set_block_number(1));
473
20
		ext
474
20
	}
475
}