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 frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{ConstU32, EnsureOrigin, Everything, Nothing, OriginTrait, PalletInfo as _},
22
	weights::{RuntimeDbWeight, Weight},
23
};
24
use pallet_evm::{
25
	EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider, GasWeightMapping,
26
};
27
use precompile_utils::{
28
	mock_account,
29
	precompile_set::*,
30
	testing::{AddressInPrefixedSet, MockAccount},
31
};
32
use sp_core::{H256, U256};
33
use sp_io;
34
use sp_runtime::traits::{BlakeTwo256, IdentityLookup, TryConvert};
35
use sp_runtime::BuildStorage;
36
use xcm::latest::Error as XcmError;
37
use xcm_builder::FixedWeightBounds;
38
use xcm_builder::IsConcrete;
39
use xcm_builder::SovereignSignedViaLocation;
40
use xcm_builder::{AllowUnpaidExecutionFrom, Case};
41
use xcm_executor::{
42
	traits::{ConvertLocation, TransactAsset, WeightTrader},
43
	AssetsInHolding,
44
};
45
use Junctions::Here;
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
210
construct_runtime!(
54
	pub enum Runtime	{
55
		System: frame_system,
56
		Balances: pallet_balances,
57
		Evm: pallet_evm,
58
		Timestamp: pallet_timestamp,
59
		PolkadotXcm: pallet_xcm,
60
	}
61
284
);
62

            
63
mock_account!(SelfReserveAccount, |_| MockAccount::from_u64(2));
64
2
mock_account!(ParentAccount, |_| MockAccount::from_u64(3));
65
// use simple encoding for parachain accounts.
66
mock_account!(
67
	SiblingParachainAccount(u32),
68
2
	|v: SiblingParachainAccount| { AddressInPrefixedSet(0xffffffff, v.0 as u128).into() }
69
);
70

            
71
use frame_system::RawOrigin as SystemRawOrigin;
72
use xcm::latest::Junction;
73
pub struct MockAccountToAccountKey20<Origin, AccountId>(PhantomData<(Origin, AccountId)>);
74

            
75
impl<Origin: OriginTrait + Clone, AccountId: Into<H160>> TryConvert<Origin, Location>
76
	for MockAccountToAccountKey20<Origin, AccountId>
77
where
78
	Origin::PalletsOrigin: From<SystemRawOrigin<AccountId>>
79
		+ TryInto<SystemRawOrigin<AccountId>, Error = Origin::PalletsOrigin>,
80
{
81
4
	fn try_convert(o: Origin) -> Result<Location, Origin> {
82
4
		o.try_with_caller(|caller| match caller.try_into() {
83
4
			Ok(SystemRawOrigin::Signed(who)) => {
84
4
				let account_h160: H160 = who.into();
85
4
				Ok(Junction::AccountKey20 {
86
4
					network: None,
87
4
					key: account_h160.into(),
88
4
				}
89
4
				.into())
90
			}
91
			Ok(other) => Err(other.into()),
92
			Err(other) => Err(other),
93
4
		})
94
4
	}
95
}
96

            
97
pub struct MockParentMultilocationToAccountConverter;
98
impl ConvertLocation<AccountId> for MockParentMultilocationToAccountConverter {
99
2
	fn convert_location(location: &Location) -> Option<AccountId> {
100
1
		match location {
101
			Location {
102
				parents: 1,
103
				interior: Here,
104
1
			} => Some(ParentAccount.into()),
105
1
			_ => None,
106
		}
107
2
	}
108
}
109

            
110
pub struct MockParachainMultilocationToAccountConverter;
111
impl ConvertLocation<AccountId> for MockParachainMultilocationToAccountConverter {
112
3
	fn convert_location(location: &Location) -> Option<AccountId> {
113
3
		match location.unpack() {
114
1
			(1, [Parachain(id)]) => Some(SiblingParachainAccount(*id).into()),
115
2
			_ => None,
116
		}
117
3
	}
118
}
119

            
120
pub type LocationToAccountId = (
121
	MockParachainMultilocationToAccountConverter,
122
	MockParentMultilocationToAccountConverter,
123
	xcm_builder::AccountKey20Aliases<LocalNetworkId, AccountId>,
124
);
125

            
126
pub struct AccountIdToLocation;
127
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
128
	fn convert(account: AccountId) -> Location {
129
		let as_h160: H160 = account.into();
130
		Location::new(
131
			0,
132
			[AccountKey20 {
133
				network: None,
134
				key: as_h160.as_fixed_bytes().clone(),
135
			}],
136
		)
137
	}
138
}
139

            
140
parameter_types! {
141
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
142
	pub LocalNetworkId: Option<NetworkId> = None;
143
}
144

            
145
parameter_types! {
146
	pub const BlockHashCount: u32 = 250;
147
	pub const SS58Prefix: u8 = 42;
148
	pub const MockDbWeight: RuntimeDbWeight = RuntimeDbWeight {
149
		read: 1,
150
		write: 5,
151
	};
152
}
153

            
154
impl frame_system::Config for Runtime {
155
	type BaseCallFilter = Everything;
156
	type DbWeight = MockDbWeight;
157
	type RuntimeOrigin = RuntimeOrigin;
158
	type RuntimeTask = RuntimeTask;
159
	type Nonce = u64;
160
	type Block = Block;
161
	type RuntimeCall = RuntimeCall;
162
	type Hash = H256;
163
	type Hashing = BlakeTwo256;
164
	type AccountId = AccountId;
165
	type Lookup = IdentityLookup<Self::AccountId>;
166
	type RuntimeEvent = RuntimeEvent;
167
	type BlockHashCount = BlockHashCount;
168
	type Version = ();
169
	type PalletInfo = PalletInfo;
170
	type AccountData = pallet_balances::AccountData<Balance>;
171
	type OnNewAccount = ();
172
	type OnKilledAccount = ();
173
	type SystemWeightInfo = ();
174
	type BlockWeights = ();
175
	type BlockLength = ();
176
	type SS58Prefix = SS58Prefix;
177
	type OnSetCode = ();
178
	type MaxConsumers = frame_support::traits::ConstU32<16>;
179
	type SingleBlockMigrations = ();
180
	type MultiBlockMigrator = ();
181
	type PreInherents = ();
182
	type PostInherents = ();
183
	type PostTransactions = ();
184
}
185
parameter_types! {
186
	pub const ExistentialDeposit: u128 = 0;
187
}
188
impl pallet_balances::Config for Runtime {
189
	type MaxReserves = ();
190
	type ReserveIdentifier = ();
191
	type MaxLocks = ();
192
	type Balance = Balance;
193
	type RuntimeEvent = RuntimeEvent;
194
	type DustRemoval = ();
195
	type ExistentialDeposit = ExistentialDeposit;
196
	type AccountStore = System;
197
	type WeightInfo = ();
198
	type RuntimeHoldReason = ();
199
	type FreezeIdentifier = ();
200
	type MaxFreezes = ();
201
	type RuntimeFreezeReason = ();
202
}
203

            
204
parameter_types! {
205
	pub MatcherLocation: Location = Location::here();
206
}
207
pub type LocalOriginToLocation = MockAccountToAccountKey20<RuntimeOrigin, AccountId>;
208
impl pallet_xcm::Config for Runtime {
209
	type RuntimeEvent = RuntimeEvent;
210
	type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
211
	type XcmRouter = TestSendXcm;
212
	type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
213
	type XcmExecuteFilter = frame_support::traits::Everything;
214
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
215
	// Do not allow teleports
216
	type XcmTeleportFilter = Everything;
217
	type XcmReserveTransferFilter = Everything;
218
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
219
	type UniversalLocation = Ancestry;
220
	type RuntimeOrigin = RuntimeOrigin;
221
	type RuntimeCall = RuntimeCall;
222
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
223
	// We use a custom one to test runtime ugprades
224
	type AdvertisedXcmVersion = ();
225
	type Currency = Balances;
226
	type CurrencyMatcher = IsConcrete<MatcherLocation>;
227
	type TrustedLockers = ();
228
	type SovereignAccountOf = ();
229
	type MaxLockers = ConstU32<8>;
230
	type WeightInfo = pallet_xcm::TestWeightInfo;
231
	type MaxRemoteLockConsumers = ConstU32<0>;
232
	type RemoteLockConsumerIdentifier = ();
233
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
234
}
235
pub type Precompiles<R> = PrecompileSetBuilder<
236
	R,
237
	(
238
		PrecompileAt<
239
			AddressU64<1>,
240
			XcmUtilsPrecompile<R, XcmConfig>,
241
			CallableByContract<AllExceptXcmExecute<R, XcmConfig>>,
242
		>,
243
	),
244
>;
245

            
246
pub type PCall = XcmUtilsPrecompileCall<Runtime, XcmConfig>;
247

            
248
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
249
/// Block storage limit in bytes. Set to 40 KB.
250
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
251

            
252
parameter_types! {
253
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
254
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
255
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
256
	pub GasLimitPovSizeRatio: u64 = {
257
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
258
		block_gas_limit.saturating_div(MAX_POV_SIZE)
259
	};
260
	pub GasLimitStorageGrowthRatio: u64 = {
261
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
262
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
263
	};
264
}
265

            
266
/// A mapping function that converts Ethereum gas to Substrate weight
267
/// We are mocking this 1-1 to test db read charges too
268
pub struct MockGasWeightMapping;
269
impl GasWeightMapping for MockGasWeightMapping {
270
	fn gas_to_weight(gas: u64, _without_base_weight: bool) -> Weight {
271
		Weight::from_parts(gas, 1)
272
	}
273
26
	fn weight_to_gas(weight: Weight) -> u64 {
274
26
		weight.ref_time().into()
275
26
	}
276
}
277

            
278
impl pallet_evm::Config for Runtime {
279
	type FeeCalculator = ();
280
	type GasWeightMapping = MockGasWeightMapping;
281
	type WeightPerGas = WeightPerGas;
282
	type CallOrigin = EnsureAddressRoot<AccountId>;
283
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
284
	type AddressMapping = AccountId;
285
	type Currency = Balances;
286
	type RuntimeEvent = RuntimeEvent;
287
	type Runner = pallet_evm::runner::stack::Runner<Self>;
288
	type PrecompilesValue = PrecompilesValue;
289
	type PrecompilesType = Precompiles<Self>;
290
	type ChainId = ();
291
	type OnChargeTransaction = ();
292
	type BlockGasLimit = BlockGasLimit;
293
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
294
	type FindAuthor = ();
295
	type OnCreate = ();
296
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
297
	type SuicideQuickClearLimit = ConstU32<0>;
298
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
299
	type Timestamp = Timestamp;
300
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
301
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
302
}
303

            
304
parameter_types! {
305
	pub const MinimumPeriod: u64 = 5;
306
}
307
impl pallet_timestamp::Config for Runtime {
308
	type Moment = u64;
309
	type OnTimestampSet = ();
310
	type MinimumPeriod = MinimumPeriod;
311
	type WeightInfo = ();
312
}
313
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
314

            
315
pub struct ConvertOriginToLocal;
316
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
317
	type Success = Location;
318

            
319
	fn try_origin(_: Origin) -> Result<Location, Origin> {
320
		Ok(Location::here())
321
	}
322

            
323
	#[cfg(feature = "runtime-benchmarks")]
324
	fn try_successful_origin() -> Result<Origin, ()> {
325
		Ok(Origin::root())
326
	}
327
}
328

            
329
use sp_std::cell::RefCell;
330
use xcm::latest::opaque;
331
// Simulates sending a XCM message
332
2
thread_local! {
333
2
	pub static SENT_XCM: RefCell<Vec<(Location, opaque::Xcm)>> = RefCell::new(Vec::new());
334
2
}
335
2
pub fn sent_xcm() -> Vec<(Location, opaque::Xcm)> {
336
2
	SENT_XCM.with(|q| (*q.borrow()).clone())
337
2
}
338
pub struct TestSendXcm;
339
impl SendXcm for TestSendXcm {
340
	type Ticket = ();
341

            
342
2
	fn validate(
343
2
		destination: &mut Option<Location>,
344
2
		message: &mut Option<opaque::Xcm>,
345
2
	) -> SendResult<Self::Ticket> {
346
2
		SENT_XCM.with(|q| {
347
2
			q.borrow_mut()
348
2
				.push((destination.clone().unwrap(), message.clone().unwrap()))
349
2
		});
350
2
		Ok(((), Assets::new()))
351
2
	}
352

            
353
2
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
354
2
		Ok(XcmHash::default())
355
2
	}
356
}
357

            
358
pub struct DummyAssetTransactor;
359
impl TransactAsset for DummyAssetTransactor {
360
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
361
		Ok(())
362
	}
363

            
364
1
	fn withdraw_asset(
365
1
		_what: &Asset,
366
1
		_who: &Location,
367
1
		_maybe_context: Option<&XcmContext>,
368
1
	) -> Result<AssetsInHolding, XcmError> {
369
1
		Ok(AssetsInHolding::default())
370
1
	}
371
}
372

            
373
pub struct DummyWeightTrader;
374
impl WeightTrader for DummyWeightTrader {
375
4
	fn new() -> Self {
376
4
		DummyWeightTrader
377
4
	}
378

            
379
1
	fn buy_weight(
380
1
		&mut self,
381
1
		weight: Weight,
382
1
		payment: AssetsInHolding,
383
1
		_context: &XcmContext,
384
1
	) -> Result<AssetsInHolding, XcmError> {
385
1
		let asset_to_charge: Asset = (Location::parent(), weight.ref_time() as u128).into();
386
1
		let unused = payment
387
1
			.checked_sub(asset_to_charge)
388
1
			.map_err(|_| XcmError::TooExpensive)?;
389

            
390
1
		Ok(unused)
391
1
	}
392
}
393

            
394
parameter_types! {
395
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 0u64);
396
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
397

            
398
	pub SelfLocation: Location =
399
		Location::new(1, [Parachain(ParachainId::get().into())]);
400

            
401
	pub SelfReserve: Location = Location::new(
402
		1,
403
		[
404
			Parachain(ParachainId::get().into()),
405
			PalletInstance(<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8)
406
		]);
407
	pub MaxInstructions: u32 = 100;
408

            
409
	pub UniversalLocation: InteriorLocation = Here;
410
	pub Ancestry: InteriorLocation =
411
		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainId::get().into())].into();
412

            
413
	pub const MaxAssetsIntoHolding: u32 = 64;
414

            
415
	pub RelayLocation: Location = Location::parent();
416
	pub RelayForeignAsset: (AssetFilter, Location) = (All.into(), RelayLocation::get());
417
}
418

            
419
pub type XcmOriginToTransactDispatchOrigin = (
420
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
421
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
422
	// foreign chains who want to have a local sovereign account on this chain which they control.
423
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
424
);
425
pub struct XcmConfig;
426
impl xcm_executor::Config for XcmConfig {
427
	type RuntimeCall = RuntimeCall;
428
	type XcmSender = TestSendXcm;
429
	type AssetTransactor = DummyAssetTransactor;
430
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
431
	type IsReserve = Case<RelayForeignAsset>;
432
	type IsTeleporter = ();
433
	type UniversalLocation = UniversalLocation;
434
	type Barrier = Barrier;
435
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
436
	type Trader = DummyWeightTrader;
437
	type ResponseHandler = ();
438
	type SubscriptionService = ();
439
	type AssetTrap = ();
440
	type AssetClaims = ();
441
	type CallDispatcher = RuntimeCall;
442
	type AssetLocker = ();
443
	type AssetExchanger = ();
444
	type PalletInstancesInfo = ();
445
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
446
	type FeeManager = ();
447
	type MessageExporter = ();
448
	type UniversalAliases = Nothing;
449
	type SafeCallFilter = Everything;
450
	type Aliasers = Nothing;
451
	type TransactionalProcessor = ();
452
	type HrmpNewChannelOpenRequestHandler = ();
453
	type HrmpChannelAcceptedHandler = ();
454
	type HrmpChannelClosingHandler = ();
455
	type XcmRecorder = ();
456
}
457

            
458
pub(crate) struct ExtBuilder {
459
	// endowed accounts with balances
460
	balances: Vec<(AccountId, Balance)>,
461
}
462

            
463
impl Default for ExtBuilder {
464
10
	fn default() -> ExtBuilder {
465
10
		ExtBuilder { balances: vec![] }
466
10
	}
467
}
468

            
469
impl ExtBuilder {
470
2
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
471
2
		self.balances = balances;
472
2
		self
473
2
	}
474

            
475
10
	pub(crate) fn build(self) -> sp_io::TestExternalities {
476
10
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
477
10
			.build_storage()
478
10
			.expect("Frame system builds valid default genesis config");
479
10

            
480
10
		pallet_balances::GenesisConfig::<Runtime> {
481
10
			balances: self.balances,
482
10
		}
483
10
		.assimilate_storage(&mut t)
484
10
		.expect("Pallet balances storage can be assimilated");
485
10

            
486
10
		let mut ext = sp_io::TestExternalities::new(t);
487
10
		ext.execute_with(|| System::set_block_number(1));
488
10
		ext
489
10
	}
490
}