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
198
construct_runtime!(
50
198
	pub enum Runtime	{
51
198
		System: frame_system,
52
198
		Balances: pallet_balances,
53
198
		Evm: pallet_evm,
54
198
		Timestamp: pallet_timestamp,
55
198
		Proxy: pallet_proxy,
56
198
	}
57
198
);
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(1, 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
}
170
impl pallet_evm::Config for Runtime {
171
	type FeeCalculator = ();
172
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
173
	type WeightPerGas = WeightPerGas;
174
	type CallOrigin = EnsureAddressAlways;
175
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
176
	type AddressMapping = AccountId;
177
	type Currency = Balances;
178
	type RuntimeEvent = RuntimeEvent;
179
	type Runner = pallet_evm::runner::stack::Runner<Self>;
180
	type PrecompilesType = Precompiles<Self>;
181
	type PrecompilesValue = PrecompilesValue;
182
	type ChainId = ();
183
	type OnChargeTransaction = ();
184
	type BlockGasLimit = BlockGasLimit;
185
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
186
	type FindAuthor = ();
187
	type OnCreate = ();
188
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
189
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
190
	type Timestamp = Timestamp;
191
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
192
	type AccountProvider = FrameSystemAccountProvider<Self>;
193
	type CreateOriginFilter = ();
194
	type CreateInnerOriginFilter = ();
195
}
196

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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