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, 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
212
construct_runtime!(
54
48
	pub enum Runtime	{
55
48
		System: frame_system,
56
48
		Balances: pallet_balances,
57
48
		Evm: pallet_evm,
58
48
		Timestamp: pallet_timestamp,
59
48
		PolkadotXcm: pallet_xcm,
60
48
	}
61
220
);
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
parameter_types! {
127
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
128
	pub LocalNetworkId: Option<NetworkId> = None;
129
}
130

            
131
parameter_types! {
132
	pub const BlockHashCount: u32 = 250;
133
	pub const SS58Prefix: u8 = 42;
134
	pub const MockDbWeight: RuntimeDbWeight = RuntimeDbWeight {
135
		read: 1,
136
		write: 5,
137
	};
138
}
139

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

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

            
234
pub type PCall = XcmUtilsPrecompileCall<Runtime, XcmConfig>;
235

            
236
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
237
/// Block storage limit in bytes. Set to 40 KB.
238
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
239

            
240
parameter_types! {
241
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
242
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
243
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
244
	pub GasLimitPovSizeRatio: u64 = {
245
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
246
		block_gas_limit.saturating_div(MAX_POV_SIZE)
247
	};
248
	pub GasLimitStorageGrowthRatio: u64 = {
249
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
250
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
251
	};
252
}
253

            
254
/// A mapping function that converts Ethereum gas to Substrate weight
255
/// We are mocking this 1-1 to test db read charges too
256
pub struct MockGasWeightMapping;
257
impl GasWeightMapping for MockGasWeightMapping {
258
	fn gas_to_weight(gas: u64, _without_base_weight: bool) -> Weight {
259
		Weight::from_parts(gas, 1)
260
	}
261
26
	fn weight_to_gas(weight: Weight) -> u64 {
262
26
		weight.ref_time().into()
263
26
	}
264
}
265

            
266
impl pallet_evm::Config for Runtime {
267
	type FeeCalculator = ();
268
	type GasWeightMapping = MockGasWeightMapping;
269
	type WeightPerGas = WeightPerGas;
270
	type CallOrigin = EnsureAddressRoot<AccountId>;
271
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
272
	type AddressMapping = AccountId;
273
	type Currency = Balances;
274
	type RuntimeEvent = RuntimeEvent;
275
	type Runner = pallet_evm::runner::stack::Runner<Self>;
276
	type PrecompilesValue = PrecompilesValue;
277
	type PrecompilesType = Precompiles<Self>;
278
	type ChainId = ();
279
	type OnChargeTransaction = ();
280
	type BlockGasLimit = BlockGasLimit;
281
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
282
	type FindAuthor = ();
283
	type OnCreate = ();
284
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
285
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
286
	type Timestamp = Timestamp;
287
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
288
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
289
}
290

            
291
parameter_types! {
292
	pub const MinimumPeriod: u64 = 5;
293
}
294
impl pallet_timestamp::Config for Runtime {
295
	type Moment = u64;
296
	type OnTimestampSet = ();
297
	type MinimumPeriod = MinimumPeriod;
298
	type WeightInfo = ();
299
}
300
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
301

            
302
use sp_std::cell::RefCell;
303
use xcm::latest::opaque;
304
// Simulates sending a XCM message
305
thread_local! {
306
	pub static SENT_XCM: RefCell<Vec<(Location, opaque::Xcm)>> = RefCell::new(Vec::new());
307
}
308
2
pub fn sent_xcm() -> Vec<(Location, opaque::Xcm)> {
309
2
	SENT_XCM.with(|q| (*q.borrow()).clone())
310
2
}
311
pub struct TestSendXcm;
312
impl SendXcm for TestSendXcm {
313
	type Ticket = ();
314

            
315
3
	fn validate(
316
3
		destination: &mut Option<Location>,
317
3
		message: &mut Option<opaque::Xcm>,
318
3
	) -> SendResult<Self::Ticket> {
319
3
		SENT_XCM.with(|q| {
320
3
			q.borrow_mut()
321
3
				.push((destination.clone().unwrap(), message.clone().unwrap()))
322
3
		});
323
3
		Ok(((), Assets::new()))
324
3
	}
325

            
326
2
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
327
2
		Ok(XcmHash::default())
328
2
	}
329
}
330

            
331
pub struct DummyAssetTransactor;
332
impl TransactAsset for DummyAssetTransactor {
333
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
334
		Ok(())
335
	}
336

            
337
1
	fn withdraw_asset(
338
1
		_what: &Asset,
339
1
		_who: &Location,
340
1
		_maybe_context: Option<&XcmContext>,
341
1
	) -> Result<AssetsInHolding, XcmError> {
342
1
		Ok(AssetsInHolding::default())
343
1
	}
344
}
345

            
346
pub struct DummyWeightTrader;
347
impl WeightTrader for DummyWeightTrader {
348
4
	fn new() -> Self {
349
4
		DummyWeightTrader
350
4
	}
351

            
352
1
	fn buy_weight(
353
1
		&mut self,
354
1
		weight: Weight,
355
1
		payment: AssetsInHolding,
356
1
		_context: &XcmContext,
357
1
	) -> Result<AssetsInHolding, XcmError> {
358
1
		let asset_to_charge: Asset = (Location::parent(), weight.ref_time() as u128).into();
359
1
		let unused = payment
360
1
			.checked_sub(asset_to_charge)
361
1
			.map_err(|_| XcmError::TooExpensive)?;
362

            
363
1
		Ok(unused)
364
1
	}
365
}
366

            
367
parameter_types! {
368
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 0u64);
369
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
370

            
371
	pub SelfLocation: Location =
372
		Location::new(1, [Parachain(ParachainId::get().into())]);
373

            
374
	pub SelfReserve: Location = Location::new(
375
		1,
376
		[
377
			Parachain(ParachainId::get().into()),
378
			PalletInstance(<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8)
379
		]);
380
	pub MaxInstructions: u32 = 100;
381

            
382
	pub UniversalLocation: InteriorLocation = Here;
383
	pub Ancestry: InteriorLocation =
384
		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainId::get().into())].into();
385

            
386
	pub const MaxAssetsIntoHolding: u32 = 64;
387

            
388
	pub RelayLocation: Location = Location::parent();
389
	pub RelayForeignAsset: (AssetFilter, Location) = (All.into(), RelayLocation::get());
390
}
391

            
392
pub type XcmOriginToTransactDispatchOrigin = (
393
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
394
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
395
	// foreign chains who want to have a local sovereign account on this chain which they control.
396
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
397
);
398
pub struct XcmConfig;
399
impl xcm_executor::Config for XcmConfig {
400
	type RuntimeCall = RuntimeCall;
401
	type XcmSender = TestSendXcm;
402
	type AssetTransactor = DummyAssetTransactor;
403
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
404
	type IsReserve = Case<RelayForeignAsset>;
405
	type IsTeleporter = ();
406
	type UniversalLocation = UniversalLocation;
407
	type Barrier = Barrier;
408
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
409
	type Trader = DummyWeightTrader;
410
	type ResponseHandler = ();
411
	type SubscriptionService = ();
412
	type AssetTrap = ();
413
	type AssetClaims = ();
414
	type CallDispatcher = RuntimeCall;
415
	type AssetLocker = ();
416
	type AssetExchanger = ();
417
	type PalletInstancesInfo = ();
418
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
419
	type FeeManager = ();
420
	type MessageExporter = ();
421
	type UniversalAliases = Nothing;
422
	type SafeCallFilter = Everything;
423
	type Aliasers = Nothing;
424
	type TransactionalProcessor = ();
425
	type HrmpNewChannelOpenRequestHandler = ();
426
	type HrmpChannelAcceptedHandler = ();
427
	type HrmpChannelClosingHandler = ();
428
	type XcmRecorder = ();
429
}
430

            
431
pub(crate) struct ExtBuilder {
432
	// endowed accounts with balances
433
	balances: Vec<(AccountId, Balance)>,
434
}
435

            
436
impl Default for ExtBuilder {
437
10
	fn default() -> ExtBuilder {
438
10
		ExtBuilder { balances: vec![] }
439
10
	}
440
}
441

            
442
impl ExtBuilder {
443
2
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
444
2
		self.balances = balances;
445
2
		self
446
2
	}
447

            
448
10
	pub(crate) fn build(self) -> sp_io::TestExternalities {
449
10
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
450
10
			.build_storage()
451
10
			.expect("Frame system builds valid default genesis config");
452
10

            
453
10
		pallet_balances::GenesisConfig::<Runtime> {
454
10
			balances: self.balances,
455
10
		}
456
10
		.assimilate_storage(&mut t)
457
10
		.expect("Pallet balances storage can be assimilated");
458
10

            
459
10
		let mut ext = sp_io::TestExternalities::new(t);
460
10
		ext.execute_with(|| System::set_block_number(1));
461
10
		ext
462
10
	}
463
}