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

            
19
use frame_support::{
20
	parameter_types,
21
	traits::{ConstU32, FindAuthor, InstanceFilter},
22
	weights::Weight,
23
	ConsensusEngineId, PalletId,
24
};
25
use frame_system::{pallet_prelude::BlockNumberFor, EnsureRoot};
26
use pallet_evm::{
27
	AddressMapping, EnsureAddressTruncated, FeeCalculator, FrameSystemAccountProvider,
28
};
29
use sp_core::{hashing::keccak_256, H160, H256, U256};
30
use sp_runtime::{
31
	traits::{BlakeTwo256, IdentityLookup},
32
	AccountId32, BuildStorage,
33
};
34

            
35
use super::*;
36
use pallet_ethereum::{IntermediateStateRoot, PostLogContent};
37
use sp_runtime::{
38
	traits::DispatchInfoOf,
39
	transaction_validity::{TransactionValidity, TransactionValidityError},
40
};
41

            
42
pub type BlockNumber = BlockNumberFor<Test>;
43

            
44
type Block = frame_system::mocking::MockBlock<Test>;
45

            
46
frame_support::construct_runtime! {
47
	pub enum Test
48
	{
49
		System: frame_system,
50
		Balances: pallet_balances,
51
		Timestamp: pallet_timestamp,
52
		EVM: pallet_evm,
53
		Ethereum: pallet_ethereum,
54
		EthereumXcm: crate,
55
		Proxy: pallet_proxy,
56
	}
57
3735
}
58

            
59
parameter_types! {
60
	pub const BlockHashCount: u32 = 250;
61
	pub BlockWeights: frame_system::limits::BlockWeights =
62
		frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, 1));
63
}
64

            
65
impl frame_system::Config for Test {
66
	type BaseCallFilter = frame_support::traits::Everything;
67
	type BlockWeights = ();
68
	type BlockLength = ();
69
	type DbWeight = ();
70
	type RuntimeOrigin = RuntimeOrigin;
71
	type RuntimeTask = RuntimeTask;
72
	type Nonce = u64;
73
	type Block = Block;
74
	type Hash = H256;
75
	type RuntimeCall = RuntimeCall;
76
	type Hashing = BlakeTwo256;
77
	type AccountId = AccountId32;
78
	type Lookup = IdentityLookup<Self::AccountId>;
79
	type RuntimeEvent = RuntimeEvent;
80
	type BlockHashCount = BlockHashCount;
81
	type Version = ();
82
	type PalletInfo = PalletInfo;
83
	type AccountData = pallet_balances::AccountData<u64>;
84
	type OnNewAccount = ();
85
	type OnKilledAccount = ();
86
	type SystemWeightInfo = ();
87
	type SS58Prefix = ();
88
	type OnSetCode = ();
89
	type MaxConsumers = ConstU32<16>;
90
	type SingleBlockMigrations = ();
91
	type MultiBlockMigrator = ();
92
	type PreInherents = ();
93
	type PostInherents = ();
94
	type PostTransactions = ();
95
	type ExtensionsWeightInfo = ();
96
}
97

            
98
parameter_types! {
99
	// For weight estimation, we assume that the most locks on an individual account will be 50.
100
	// This number may need to be adjusted in the future if this assumption no longer holds true.
101
	pub const MaxLocks: u32 = 50;
102
	pub const ExistentialDeposit: u64 = 500;
103
}
104

            
105
impl pallet_balances::Config for Test {
106
	type MaxLocks = MaxLocks;
107
	type Balance = u64;
108
	type RuntimeEvent = RuntimeEvent;
109
	type DustRemoval = ();
110
	type ExistentialDeposit = ExistentialDeposit;
111
	type AccountStore = System;
112
	type WeightInfo = ();
113
	type MaxReserves = ();
114
	type ReserveIdentifier = ();
115
	type RuntimeHoldReason = ();
116
	type FreezeIdentifier = ();
117
	type MaxFreezes = ();
118
	type RuntimeFreezeReason = ();
119
	type DoneSlashHandler = ();
120
}
121

            
122
parameter_types! {
123
	pub const MinimumPeriod: u64 = 6000 / 2;
124
}
125

            
126
impl pallet_timestamp::Config for Test {
127
	type Moment = u64;
128
	type OnTimestampSet = ();
129
	type MinimumPeriod = MinimumPeriod;
130
	type WeightInfo = ();
131
}
132

            
133
pub struct FixedGasPrice;
134
impl FeeCalculator for FixedGasPrice {
135
54
	fn min_gas_price() -> (U256, Weight) {
136
54
		(1.into(), Weight::zero())
137
54
	}
138
}
139

            
140
pub struct FindAuthorTruncated;
141
impl FindAuthor<H160> for FindAuthorTruncated {
142
51
	fn find_author<'a, I>(_digests: I) -> Option<H160>
143
51
	where
144
51
		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
145
	{
146
51
		Some(address_build(0).address)
147
51
	}
148
}
149

            
150
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
151
/// Block storage limit in bytes. Set to 40 KB.
152
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
153

            
154
parameter_types! {
155
	pub const TransactionByteFee: u64 = 1;
156
	pub const ChainId: u64 = 42;
157
	pub const EVMModuleId: PalletId = PalletId(*b"py/evmpa");
158
	pub const BlockGasLimit: U256 = U256::MAX;
159
	pub WeightPerGas: Weight = Weight::from_parts(1, 0);
160
	pub GasLimitPovSizeRatio: u64 = {
161
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
162
		block_gas_limit.saturating_div(MAX_POV_SIZE)
163
	};
164
	pub GasLimitStorageGrowthRatio: u64 = {
165
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
166
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
167
	};
168
}
169

            
170
pub struct HashedAddressMapping;
171

            
172
impl AddressMapping<AccountId32> for HashedAddressMapping {
173
229
	fn into_account_id(address: H160) -> AccountId32 {
174
229
		let mut data = [0u8; 32];
175
229
		data[0..20].copy_from_slice(&address[..]);
176
229
		AccountId32::from(Into::<[u8; 32]>::into(data))
177
229
	}
178
}
179

            
180
impl pallet_evm::Config for Test {
181
	type FeeCalculator = FixedGasPrice;
182
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
183
	type WeightPerGas = WeightPerGas;
184
	type CallOrigin = EnsureAddressTruncated;
185
	type WithdrawOrigin = EnsureAddressTruncated;
186
	type AddressMapping = HashedAddressMapping;
187
	type Currency = Balances;
188
	type PrecompilesType = ();
189
	type PrecompilesValue = ();
190
	type Runner = pallet_evm::runner::stack::Runner<Self>;
191
	type ChainId = ChainId;
192
	type BlockGasLimit = BlockGasLimit;
193
	type OnChargeTransaction = ();
194
	type FindAuthor = FindAuthorTruncated;
195
	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
196
	type OnCreate = ();
197
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
198
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
199
	type Timestamp = Timestamp;
200
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Test>;
201
	type AccountProvider = FrameSystemAccountProvider<Test>;
202
	type CreateOriginFilter = ();
203
	type CreateInnerOriginFilter = ();
204
}
205

            
206
parameter_types! {
207
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
208
}
209

            
210
impl pallet_ethereum::Config for Test {
211
	type StateRoot = IntermediateStateRoot<<Test as frame_system::Config>::Version>;
212
	type PostLogContent = PostBlockAndTxnHashes;
213
	type ExtraDataLength = ConstU32<30>;
214
}
215

            
216
parameter_types! {
217
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 1);
218
}
219

            
220
#[derive(
221
	Copy,
222
	Clone,
223
	Eq,
224
	PartialEq,
225
	Ord,
226
	PartialOrd,
227
	Encode,
228
	Decode,
229
	Debug,
230
	MaxEncodedLen,
231
	TypeInfo,
232
	DecodeWithMemTracking,
233
)]
234
pub enum ProxyType {
235
	NotAllowed = 0,
236
	Any = 1,
237
}
238

            
239
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
240

            
241
impl InstanceFilter<RuntimeCall> for ProxyType {
242
	fn filter(&self, _c: &RuntimeCall) -> bool {
243
		match self {
244
			ProxyType::NotAllowed => false,
245
			ProxyType::Any => true,
246
		}
247
	}
248
	fn is_superset(&self, _o: &Self) -> bool {
249
		false
250
	}
251
}
252

            
253
impl Default for ProxyType {
254
	fn default() -> Self {
255
		Self::NotAllowed
256
	}
257
}
258

            
259
parameter_types! {
260
	pub const ProxyCost: u64 = 1;
261
}
262

            
263
impl pallet_proxy::Config for Test {
264
	type RuntimeEvent = RuntimeEvent;
265
	type RuntimeCall = RuntimeCall;
266
	type Currency = Balances;
267
	type ProxyType = ProxyType;
268
	type ProxyDepositBase = ProxyCost;
269
	type ProxyDepositFactor = ProxyCost;
270
	type MaxProxies = ConstU32<32>;
271
	type WeightInfo = pallet_proxy::weights::SubstrateWeight<Test>;
272
	type MaxPending = ConstU32<32>;
273
	type CallHasher = BlakeTwo256;
274
	type AnnouncementDepositBase = ProxyCost;
275
	type AnnouncementDepositFactor = ProxyCost;
276
	type BlockNumberProvider = System;
277
}
278

            
279
pub struct EthereumXcmEnsureProxy;
280
impl xcm_primitives::EnsureProxy<AccountId32> for EthereumXcmEnsureProxy {
281
17
	fn ensure_ok(delegator: AccountId32, delegatee: AccountId32) -> Result<(), &'static str> {
282
17
		let f = |x: &pallet_proxy::ProxyDefinition<AccountId32, ProxyType, BlockNumber>| -> bool {
283
12
			x.delegate == delegatee && (x.proxy_type == ProxyType::Any)
284
12
		};
285
17
		Proxy::proxies(delegator)
286
17
			.0
287
17
			.into_iter()
288
17
			.find(f)
289
17
			.map(|_| ())
290
17
			.ok_or("proxy error: expected `ProxyType::Any`")
291
17
	}
292
}
293

            
294
impl crate::Config for Test {
295
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
296
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
297
	type XcmEthereumOrigin = crate::EnsureXcmEthereumTransaction;
298
	type ReservedXcmpWeight = ReservedXcmpWeight;
299
	type EnsureProxy = EthereumXcmEnsureProxy;
300
	type ControllerOrigin = EnsureRoot<AccountId32>;
301
	type ForceOrigin = EnsureRoot<AccountId32>;
302
}
303

            
304
impl fp_self_contained::SelfContainedCall for RuntimeCall {
305
	type SignedInfo = H160;
306

            
307
	fn is_self_contained(&self) -> bool {
308
		match self {
309
			RuntimeCall::Ethereum(call) => call.is_self_contained(),
310
			_ => false,
311
		}
312
	}
313

            
314
	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
315
		match self {
316
			RuntimeCall::Ethereum(call) => call.check_self_contained(),
317
			_ => None,
318
		}
319
	}
320

            
321
	fn validate_self_contained(
322
		&self,
323
		info: &Self::SignedInfo,
324
		dispatch_info: &DispatchInfoOf<RuntimeCall>,
325
		len: usize,
326
	) -> Option<TransactionValidity> {
327
		match self {
328
			RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
329
			_ => None,
330
		}
331
	}
332

            
333
	fn pre_dispatch_self_contained(
334
		&self,
335
		info: &Self::SignedInfo,
336
		dispatch_info: &DispatchInfoOf<RuntimeCall>,
337
		len: usize,
338
	) -> Option<Result<(), TransactionValidityError>> {
339
		match self {
340
			RuntimeCall::Ethereum(call) => {
341
				call.pre_dispatch_self_contained(info, dispatch_info, len)
342
			}
343
			_ => None,
344
		}
345
	}
346

            
347
	fn apply_self_contained(
348
		self,
349
		info: Self::SignedInfo,
350
	) -> Option<sp_runtime::DispatchResultWithInfo<sp_runtime::traits::PostDispatchInfoOf<Self>>> {
351
		use sp_runtime::traits::Dispatchable as _;
352
		match self {
353
			call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
354
				Some(call.dispatch(RuntimeOrigin::from(
355
					pallet_ethereum::RawOrigin::EthereumTransaction(info),
356
				)))
357
			}
358
			_ => None,
359
		}
360
	}
361
}
362

            
363
pub struct AccountInfo {
364
	pub address: H160,
365
	pub account_id: AccountId32,
366
}
367

            
368
175
fn address_build(seed: u8) -> AccountInfo {
369
175
	let private_key = H256::from_slice(&[(seed + 1) as u8; 32]);
370
175
	let secret_key = libsecp256k1::SecretKey::parse_slice(&private_key[..]).unwrap();
371
175
	let public_key = &libsecp256k1::PublicKey::from_secret_key(&secret_key).serialize()[1..65];
372
175
	let address = H160::from(H256::from(keccak_256(public_key)));
373

            
374
175
	let mut data = [0u8; 32];
375
175
	data[0..20].copy_from_slice(&address[..]);
376

            
377
175
	AccountInfo {
378
175
		account_id: AccountId32::from(Into::<[u8; 32]>::into(data)),
379
175
		address,
380
175
	}
381
175
}
382

            
383
// This function basically just builds a genesis storage key/value store according to
384
// our desired mockup.
385
56
pub fn new_test_ext(accounts_len: usize) -> (Vec<AccountInfo>, sp_io::TestExternalities) {
386
	// sc_cli::init_logger("");
387
56
	let mut ext = frame_system::GenesisConfig::<Test>::default()
388
56
		.build_storage()
389
56
		.unwrap();
390

            
391
56
	let pairs = (0..accounts_len)
392
124
		.map(|i| address_build(i as u8))
393
56
		.collect::<Vec<_>>();
394

            
395
56
	let balances: Vec<_> = (0..accounts_len)
396
124
		.map(|i| (pairs[i].account_id.clone(), 10_000_000))
397
56
		.collect();
398

            
399
56
	pallet_balances::GenesisConfig::<Test> {
400
56
		balances,
401
56
		dev_accounts: Default::default(),
402
56
	}
403
56
	.assimilate_storage(&mut ext)
404
56
	.unwrap();
405

            
406
56
	(pairs, ext.into())
407
56
}