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

            
20
use cumulus_primitives_core::AggregateMessageOrigin;
21
use frame_support::{
22
	construct_runtime, parameter_types,
23
	traits::{Everything, PalletInfo as PalletInfoTrait},
24
	weights::Weight,
25
};
26
use pallet_evm::{
27
	EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider, SubstrateBlockHashMapping,
28
};
29
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
30
use precompile_utils::{precompile_set::*, testing::MockAccount};
31
use scale_info::TypeInfo;
32
use sp_core::{H160, H256};
33
use sp_runtime::{
34
	traits::{BlakeTwo256, IdentityLookup},
35
	BuildStorage, Perbill,
36
};
37
use xcm::latest::{prelude::*, Error as XcmError};
38
use xcm_builder::FixedWeightBounds;
39
use xcm_executor::{traits::TransactAsset, AssetsInHolding};
40

            
41
pub type AccountId = MockAccount;
42
pub type Balance = u128;
43

            
44
type Block = frame_system::mocking::MockBlockU32<Runtime>;
45

            
46
// Configure a mock runtime to test the pallet.
47
13
construct_runtime!(
48
13
	pub enum Runtime	{
49
13
		System: frame_system,
50
13
		Balances: pallet_balances,
51
13
		Evm: pallet_evm,
52
13
		ParachainSystem: cumulus_pallet_parachain_system,
53
13
		Timestamp: pallet_timestamp,
54
13
		XcmTransactor: pallet_xcm_transactor,
55
13
		MessageQueue: pallet_message_queue,
56
13
	}
57
13
);
58

            
59
parameter_types! {
60
	pub const BlockHashCount: u32 = 250;
61
	pub const SS58Prefix: u8 = 42;
62
}
63
impl frame_system::Config for Runtime {
64
	type BaseCallFilter = Everything;
65
	type DbWeight = ();
66
	type RuntimeOrigin = RuntimeOrigin;
67
	type RuntimeTask = RuntimeTask;
68
	type Nonce = u64;
69
	type Block = Block;
70
	type RuntimeCall = RuntimeCall;
71
	type Hash = H256;
72
	type Hashing = BlakeTwo256;
73
	type AccountId = AccountId;
74
	type Lookup = IdentityLookup<Self::AccountId>;
75
	type RuntimeEvent = RuntimeEvent;
76
	type BlockHashCount = BlockHashCount;
77
	type Version = ();
78
	type PalletInfo = PalletInfo;
79
	type AccountData = pallet_balances::AccountData<Balance>;
80
	type OnNewAccount = ();
81
	type OnKilledAccount = ();
82
	type SystemWeightInfo = ();
83
	type BlockWeights = ();
84
	type BlockLength = ();
85
	type SS58Prefix = SS58Prefix;
86
	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
87
	type MaxConsumers = frame_support::traits::ConstU32<16>;
88
	type SingleBlockMigrations = ();
89
	type MultiBlockMigrator = ();
90
	type PreInherents = ();
91
	type PostInherents = ();
92
	type PostTransactions = ();
93
	type ExtensionsWeightInfo = ();
94
}
95

            
96
parameter_types! {
97
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
98
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
99
}
100

            
101
impl cumulus_pallet_parachain_system::Config for Runtime {
102
	type SelfParaId = ParachainId;
103
	type RuntimeEvent = RuntimeEvent;
104
	type OnSystemEvent = ();
105
	type OutboundXcmpMessageSource = ();
106
	type XcmpMessageHandler = ();
107
	type ReservedXcmpWeight = ();
108
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
109
	type ReservedDmpWeight = ();
110
	type CheckAssociatedRelayNumber = cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
111
	type ConsensusHook = cumulus_pallet_parachain_system::ExpectParentIncluded;
112
	type WeightInfo = cumulus_pallet_parachain_system::weights::SubstrateWeight<Runtime>;
113
	type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
114
}
115

            
116
parameter_types! {
117
	pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000);
118
	pub const MessageQueueHeapSize: u32 = 65_536;
119
	pub const MessageQueueMaxStale: u32 = 16;
120
}
121

            
122
impl pallet_message_queue::Config for Runtime {
123
	type RuntimeEvent = RuntimeEvent;
124
	type Size = u32;
125
	type HeapSize = MessageQueueHeapSize;
126
	type MaxStale = MessageQueueMaxStale;
127
	type ServiceWeight = MessageQueueServiceWeight;
128
	type MessageProcessor =
129
		pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
130
	type QueueChangeHandler = ();
131
	type WeightInfo = ();
132
	type QueuePausedQuery = ();
133
	type IdleMaxServiceWeight = MessageQueueServiceWeight;
134
}
135

            
136
parameter_types! {
137
	pub const ExistentialDeposit: u128 = 0;
138
}
139
impl pallet_balances::Config for Runtime {
140
	type MaxReserves = ();
141
	type ReserveIdentifier = ();
142
	type MaxLocks = ();
143
	type Balance = Balance;
144
	type RuntimeEvent = RuntimeEvent;
145
	type DustRemoval = ();
146
	type ExistentialDeposit = ExistentialDeposit;
147
	type AccountStore = System;
148
	type WeightInfo = ();
149
	type RuntimeHoldReason = ();
150
	type FreezeIdentifier = ();
151
	type MaxFreezes = ();
152
	type RuntimeFreezeReason = ();
153
	type DoneSlashHandler = ();
154
}
155

            
156
pub type AssetId = u128;
157

            
158
#[derive(
159
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
160
)]
161
pub enum CurrencyId {
162
	SelfReserve,
163
	OtherReserve(AssetId),
164
}
165

            
166
pub struct DoNothingRouter;
167
impl SendXcm for DoNothingRouter {
168
	type Ticket = ();
169

            
170
	fn validate(
171
		_destination: &mut Option<Location>,
172
		_message: &mut Option<Xcm<()>>,
173
	) -> SendResult<Self::Ticket> {
174
		Ok(((), Assets::new()))
175
	}
176

            
177
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
178
		Ok(XcmHash::default())
179
	}
180
}
181

            
182
parameter_types! {
183
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
184

            
185
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
186
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
187

            
188
	pub SelfLocation: Location =
189
		Location::new(1, [Parachain(ParachainId::get().into())]);
190

            
191
	pub SelfReserve: Location = Location::new(
192
		1,
193
		[
194
			Parachain(ParachainId::get().into()),
195
			PalletInstance(
196
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
197
			)
198
		]);
199
	pub MaxInstructions: u32 = 100;
200

            
201
	pub UniversalLocation: InteriorLocation = Here;
202
}
203

            
204
pub struct AccountIdToLocation;
205
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
206
	fn convert(account: AccountId) -> Location {
207
		let as_h160: H160 = account.into();
208
		Location::new(
209
			0,
210
			[AccountKey20 {
211
				network: None,
212
				key: as_h160.as_fixed_bytes().clone(),
213
			}],
214
		)
215
	}
216
}
217

            
218
pub struct CurrencyIdToLocation;
219

            
220
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToLocation {
221
	fn convert(currency: CurrencyId) -> Option<Location> {
222
		match currency {
223
			CurrencyId::SelfReserve => {
224
				let multi: Location = SelfReserve::get();
225
				Some(multi)
226
			}
227
			// To distinguish between relay and others, specially for reserve asset
228
			CurrencyId::OtherReserve(asset) => {
229
				if asset == 0 {
230
					Some(Location::parent())
231
				} else {
232
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
233
				}
234
			}
235
		}
236
	}
237
}
238

            
239
// We need to use the encoding from the relay mock runtime
240
#[derive(Encode, Decode)]
241
pub enum RelayCall {
242
	#[codec(index = 5u8)]
243
	// the index should match the position of the module in `construct_runtime!`
244
	Utility(UtilityCall),
245
}
246

            
247
#[derive(Encode, Decode)]
248
pub enum UtilityCall {
249
	#[codec(index = 1u8)]
250
	AsDerivative(u16),
251
}
252

            
253
#[derive(
254
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
255
)]
256
pub enum MockTransactors {
257
	Relay,
258
}
259

            
260
impl TryFrom<u8> for MockTransactors {
261
	type Error = ();
262

            
263
	fn try_from(value: u8) -> Result<Self, Self::Error> {
264
		match value {
265
			0x0 => Ok(MockTransactors::Relay),
266
			_ => Err(()),
267
		}
268
	}
269
}
270

            
271
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
272
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
273
		match self {
274
			MockTransactors::Relay => match call {
275
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
276
					let mut call =
277
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
278
					call.append(&mut b.clone());
279
					call
280
				}
281
			},
282
		}
283
	}
284
}
285

            
286
impl xcm_primitives::XcmTransact for MockTransactors {
287
	fn destination(self) -> Location {
288
		match self {
289
			MockTransactors::Relay => Location::parent(),
290
		}
291
	}
292
}
293

            
294
pub struct DummyAssetTransactor;
295
impl TransactAsset for DummyAssetTransactor {
296
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
297
		Ok(())
298
	}
299

            
300
	fn withdraw_asset(
301
		_what: &Asset,
302
		_who: &Location,
303
		_maybe_context: Option<&XcmContext>,
304
	) -> Result<AssetsInHolding, XcmError> {
305
		Ok(AssetsInHolding::default())
306
	}
307
}
308

            
309
parameter_types! {
310
	pub SelfLocationAbsolute: Location = Location {
311
		parents: 1,
312
		interior: [Parachain(ParachainId::get().into())].into(),
313
	};
314
}
315

            
316
impl pallet_xcm_transactor::Config for Runtime {
317
	type RuntimeEvent = RuntimeEvent;
318
	type Balance = Balance;
319
	type Transactor = MockTransactors;
320
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
321
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
322
	type CurrencyId = CurrencyId;
323
	type AccountIdToLocation = AccountIdToLocation;
324
	type CurrencyIdToLocation = CurrencyIdToLocation;
325
	type SelfLocation = SelfLocation;
326
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
327
	type UniversalLocation = UniversalLocation;
328
	type BaseXcmWeight = BaseXcmWeight;
329
	type XcmSender = DoNothingRouter;
330
	type AssetTransactor = DummyAssetTransactor;
331
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
332
	type WeightInfo = ();
333
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
334
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
335
	type MaxHrmpFee = ();
336
}
337

            
338
pub type Precompiles<R> =
339
	PrecompileSetBuilder<R, PrecompileAt<AddressU64<1>, RelayEncoderPrecompile<R>>>;
340

            
341
pub type PCall = RelayEncoderPrecompileCall<Runtime>;
342

            
343
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
344
/// Block storage limit in bytes. Set to 40 KB.
345
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
346

            
347
parameter_types! {
348
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
349
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
350
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
351
	pub GasLimitPovSizeRatio: u64 = {
352
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
353
		block_gas_limit.saturating_div(MAX_POV_SIZE)
354
	};
355
	pub GasLimitStorageGrowthRatio: u64 = {
356
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
357
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
358
	};
359
}
360

            
361
impl pallet_evm::Config for Runtime {
362
	type FeeCalculator = ();
363
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
364
	type WeightPerGas = WeightPerGas;
365
	type CallOrigin = EnsureAddressRoot<AccountId>;
366
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
367
	type AddressMapping = AccountId;
368
	type Currency = Balances;
369
	type RuntimeEvent = RuntimeEvent;
370
	type Runner = pallet_evm::runner::stack::Runner<Self>;
371
	type PrecompilesValue = PrecompilesValue;
372
	type PrecompilesType = Precompiles<Self>;
373
	type ChainId = ();
374
	type OnChargeTransaction = ();
375
	type BlockGasLimit = BlockGasLimit;
376
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
377
	type FindAuthor = ();
378
	type OnCreate = ();
379
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
380
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
381
	type Timestamp = Timestamp;
382
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
383
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
384
	type CreateOriginFilter = ();
385
	type CreateInnerOriginFilter = ();
386
}
387

            
388
parameter_types! {
389
	pub const MinimumPeriod: u64 = 5;
390
}
391
impl pallet_timestamp::Config for Runtime {
392
	type Moment = u64;
393
	type OnTimestampSet = ();
394
	type MinimumPeriod = MinimumPeriod;
395
	type WeightInfo = ();
396
}
397

            
398
parameter_types! {
399
	pub const TestMaxInitContributors: u32 = 8;
400
	pub const TestMinimumReward: u128 = 0;
401
	pub const TestInitialized: bool = false;
402
	pub const TestInitializationPayment: Perbill = Perbill::from_percent(20);
403
}
404

            
405
pub(crate) struct ExtBuilder {
406
	// endowed accounts with balances
407
	balances: Vec<(AccountId, Balance)>,
408
}
409

            
410
impl Default for ExtBuilder {
411
13
	fn default() -> ExtBuilder {
412
13
		ExtBuilder { balances: vec![] }
413
13
	}
414
}
415

            
416
impl ExtBuilder {
417
10
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
418
10
		self.balances = balances;
419
10
		self
420
10
	}
421

            
422
13
	pub(crate) fn build(self) -> sp_io::TestExternalities {
423
13
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
424
13
			.build_storage()
425
13
			.expect("Frame system builds valid default genesis config");
426
13

            
427
13
		pallet_balances::GenesisConfig::<Runtime> {
428
13
			balances: self.balances,
429
13
			dev_accounts: Default::default(),
430
13
		}
431
13
		.assimilate_storage(&mut t)
432
13
		.expect("Pallet balances storage can be assimilated");
433
13

            
434
13
		let mut ext = sp_io::TestExternalities::new(t);
435
13
		ext.execute_with(|| System::set_block_number(1));
436
13
		ext.execute_with(|| {
437
13
			pallet_xcm_transactor::RelayIndices::<Runtime>::put(
438
13
				crate::test_relay_runtime::TEST_RELAY_INDICES,
439
13
			);
440
13
		});
441
13
		ext
442
13
	}
443
}