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::{ProxyPrecompile, ProxyPrecompileCall};
19
use frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{Everything, InstanceFilter},
22
	weights::Weight,
23
};
24
use pallet_evm::{
25
	EnsureAddressNever, EnsureAddressOrigin, FrameSystemAccountProvider, SubstrateBlockHashMapping,
26
};
27
use parity_scale_codec::DecodeWithMemTracking;
28
use precompile_utils::{
29
	precompile_set::{
30
		AddressU64, CallableByContract, CallableByPrecompile, OnlyFrom, PrecompileAt,
31
		PrecompileSetBuilder, RevertPrecompile, SubcallWithMaxNesting,
32
	},
33
	testing::MockAccount,
34
};
35
use scale_info::TypeInfo;
36
use sp_core::{H160, H256, U256};
37
use sp_io;
38
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
39
use sp_runtime::{
40
	codec::{Decode, Encode, MaxEncodedLen},
41
	BuildStorage,
42
};
43

            
44
pub type AccountId = MockAccount;
45
pub type Balance = u128;
46

            
47
type Block = frame_system::mocking::MockBlockU32<Runtime>;
48

            
49
construct_runtime!(
50
	pub enum Runtime	{
51
		System: frame_system,
52
		Balances: pallet_balances,
53
		Evm: pallet_evm,
54
		Timestamp: pallet_timestamp,
55
		Proxy: pallet_proxy,
56
	}
57
);
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 = ();
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
parameter_types! {
96
	pub const ExistentialDeposit: u128 = 0;
97
}
98
impl pallet_balances::Config for Runtime {
99
	type MaxReserves = ();
100
	type ReserveIdentifier = ();
101
	type MaxLocks = ();
102
	type Balance = Balance;
103
	type RuntimeEvent = RuntimeEvent;
104
	type DustRemoval = ();
105
	type ExistentialDeposit = ExistentialDeposit;
106
	type AccountStore = System;
107
	type WeightInfo = ();
108
	type RuntimeHoldReason = ();
109
	type FreezeIdentifier = ();
110
	type MaxFreezes = ();
111
	type RuntimeFreezeReason = ();
112
	type DoneSlashHandler = ();
113
}
114

            
115
pub type Precompiles<R> = PrecompileSetBuilder<
116
	R,
117
	(
118
		PrecompileAt<
119
			AddressU64<1>,
120
			ProxyPrecompile<R>,
121
			(
122
				SubcallWithMaxNesting<1>,
123
				CallableByContract<crate::OnlyIsProxyAndProxy<R>>,
124
				// Batch is the only precompile allowed to call Proxy.
125
				CallableByPrecompile<OnlyFrom<AddressU64<2>>>,
126
			),
127
		>,
128
		RevertPrecompile<AddressU64<2>>,
129
	),
130
>;
131

            
132
pub type PCall = ProxyPrecompileCall<Runtime>;
133

            
134
pub struct EnsureAddressAlways;
135
impl<OuterOrigin> EnsureAddressOrigin<OuterOrigin> for EnsureAddressAlways {
136
	type Success = ();
137

            
138
	fn try_address_origin(
139
		_address: &H160,
140
		_origin: OuterOrigin,
141
	) -> Result<Self::Success, OuterOrigin> {
142
		Ok(())
143
	}
144

            
145
1
	fn ensure_address_origin(
146
1
		_address: &H160,
147
1
		_origin: OuterOrigin,
148
1
	) -> Result<Self::Success, sp_runtime::traits::BadOrigin> {
149
1
		Ok(())
150
1
	}
151
}
152

            
153
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
154
/// Block storage limit in bytes. Set to 40 KB.
155
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
156

            
157
parameter_types! {
158
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
159
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
160
	pub const WeightPerGas: Weight = Weight::from_parts(25_000, 0);
161
	pub GasLimitPovSizeRatio: u64 = {
162
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
163
		block_gas_limit.saturating_div(MAX_POV_SIZE)
164
	};
165
	pub GasLimitStorageGrowthRatio: u64 = {
166
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
167
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
168
	};
169
	pub SuicideQuickClearLimit: u32 = 0;
170
}
171

            
172
impl pallet_evm::Config for Runtime {
173
	type FeeCalculator = ();
174
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
175
	type WeightPerGas = WeightPerGas;
176
	type CallOrigin = EnsureAddressAlways;
177
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
178
	type AddressMapping = AccountId;
179
	type Currency = Balances;
180
	type Runner = pallet_evm::runner::stack::Runner<Self>;
181
	type PrecompilesType = Precompiles<Self>;
182
	type PrecompilesValue = PrecompilesValue;
183
	type ChainId = ();
184
	type OnChargeTransaction = ();
185
	type BlockGasLimit = BlockGasLimit;
186
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
187
	type FindAuthor = ();
188
	type OnCreate = ();
189
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
190
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
191
	type Timestamp = Timestamp;
192
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
193
	type AccountProvider = FrameSystemAccountProvider<Self>;
194
	type CreateOriginFilter = ();
195
	type CreateInnerOriginFilter = ();
196
}
197

            
198
parameter_types! {
199
	pub const MinimumPeriod: u64 = 5;
200
}
201
impl pallet_timestamp::Config for Runtime {
202
	type Moment = u64;
203
	type OnTimestampSet = ();
204
	type MinimumPeriod = MinimumPeriod;
205
	type WeightInfo = ();
206
}
207

            
208
#[repr(u8)]
209
#[derive(
210
	Debug,
211
	Eq,
212
	PartialEq,
213
	Ord,
214
	PartialOrd,
215
	Decode,
216
	MaxEncodedLen,
217
	Encode,
218
	Clone,
219
	Copy,
220
	TypeInfo,
221
	DecodeWithMemTracking,
222
)]
223
pub enum ProxyType {
224
	Any = 0,
225
	Something = 1,
226
	Nothing = 2,
227
}
228

            
229
impl std::default::Default for ProxyType {
230
	fn default() -> Self {
231
		ProxyType::Any
232
	}
233
}
234

            
235
impl crate::EvmProxyCallFilter for ProxyType {
236
2
	fn is_evm_proxy_call_allowed(
237
2
		&self,
238
2
		_call: &crate::EvmSubCall,
239
2
		_recipient_has_code: bool,
240
2
		_gas: u64,
241
2
	) -> precompile_utils::EvmResult<bool> {
242
2
		Ok(match self {
243
1
			Self::Any => true,
244
			Self::Something => true,
245
1
			Self::Nothing => false,
246
		})
247
2
	}
248
}
249

            
250
impl InstanceFilter<RuntimeCall> for ProxyType {
251
1
	fn filter(&self, _: &RuntimeCall) -> bool {
252
1
		true
253
1
	}
254

            
255
	fn is_superset(&self, o: &Self) -> bool {
256
		(*self as u8) > (*o as u8)
257
	}
258
}
259

            
260
parameter_types! {
261
	pub const ProxyDepositBase: u64 = 100;
262
	pub const ProxyDepositFactor: u64 = 1;
263
	pub const MaxProxies: u32 = 5;
264
	pub const MaxPending: u32 = 5;
265
}
266
impl pallet_proxy::Config for Runtime {
267
	type RuntimeEvent = RuntimeEvent;
268
	type RuntimeCall = RuntimeCall;
269
	type Currency = Balances;
270
	type ProxyType = ProxyType;
271
	type ProxyDepositBase = ProxyDepositBase;
272
	type ProxyDepositFactor = ProxyDepositFactor;
273
	type MaxProxies = MaxProxies;
274
	type WeightInfo = ();
275
	type MaxPending = MaxPending;
276
	type CallHasher = BlakeTwo256;
277
	type AnnouncementDepositBase = ();
278
	type AnnouncementDepositFactor = ();
279
	type BlockNumberProvider = System;
280
}
281

            
282
/// Build test externalities, prepopulated with data for testing democracy precompiles
283
pub(crate) struct ExtBuilder {
284
	/// Endowed accounts with balances
285
	balances: Vec<(AccountId, Balance)>,
286
}
287

            
288
impl Default for ExtBuilder {
289
28
	fn default() -> ExtBuilder {
290
28
		ExtBuilder { balances: vec![] }
291
28
	}
292
}
293

            
294
impl ExtBuilder {
295
	/// Fund some accounts before starting the test
296
25
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
297
25
		self.balances = balances;
298
25
		self
299
25
	}
300

            
301
	/// Build the test externalities for use in tests
302
28
	pub(crate) fn build(self) -> sp_io::TestExternalities {
303
28
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
304
28
			.build_storage()
305
28
			.expect("Frame system builds valid default genesis config");
306

            
307
28
		pallet_balances::GenesisConfig::<Runtime> {
308
28
			balances: self.balances.clone(),
309
28
			dev_accounts: Default::default(),
310
28
		}
311
28
		.assimilate_storage(&mut t)
312
28
		.expect("Pallet balances storage can be assimilated");
313

            
314
28
		let mut ext = sp_io::TestExternalities::new(t);
315
28
		ext.execute_with(|| {
316
28
			System::set_block_number(1);
317
28
		});
318
28
		ext
319
28
	}
320
}
321

            
322
3
pub(crate) fn events() -> Vec<RuntimeEvent> {
323
3
	System::events()
324
3
		.into_iter()
325
3
		.map(|r| r.event)
326
3
		.collect::<Vec<_>>()
327
3
}
328

            
329
/// Panics if an event is not found in the system log of events
330
#[macro_export]
331
macro_rules! assert_event_emitted {
332
	($event:expr) => {
333
		match &$event {
334
			e => {
335
				assert!(
336
6
					crate::mock::events().iter().find(|x| *x == e).is_some(),
337
					"Event {:?} was not found in events: \n {:#?}",
338
					e,
339
					crate::mock::events()
340
				);
341
			}
342
		}
343
	};
344
}
345

            
346
// Panics if an event is found in the system log of events
347
#[macro_export]
348
macro_rules! assert_event_not_emitted {
349
	($event:expr) => {
350
		match &$event {
351
			e => {
352
				assert!(
353
4
					crate::mock::events().iter().find(|x| *x == e).is_none(),
354
					"Event {:?} was found in events: \n {:?}",
355
					e,
356
					crate::mock::events()
357
				);
358
			}
359
		}
360
	};
361
}