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 precompile_utils::{
28
	precompile_set::{
29
		AddressU64, CallableByContract, CallableByPrecompile, OnlyFrom, PrecompileAt,
30
		PrecompileSetBuilder, RevertPrecompile, SubcallWithMaxNesting,
31
	},
32
	testing::MockAccount,
33
};
34
use scale_info::TypeInfo;
35
use sp_core::{H160, H256, U256};
36
use sp_io;
37
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
38
use sp_runtime::{
39
	codec::{Decode, Encode, MaxEncodedLen},
40
	BuildStorage,
41
};
42

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

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

            
48
995
construct_runtime!(
49
198
	pub enum Runtime	{
50
198
		System: frame_system,
51
198
		Balances: pallet_balances,
52
198
		Evm: pallet_evm,
53
198
		Timestamp: pallet_timestamp,
54
198
		Proxy: pallet_proxy,
55
198
	}
56
1019
);
57

            
58
parameter_types! {
59
	pub const BlockHashCount: u32 = 250;
60
	pub const SS58Prefix: u8 = 42;
61
}
62
impl frame_system::Config for Runtime {
63
	type BaseCallFilter = Everything;
64
	type DbWeight = ();
65
	type RuntimeOrigin = RuntimeOrigin;
66
	type RuntimeTask = RuntimeTask;
67
	type Nonce = u64;
68
	type Block = Block;
69
	type RuntimeCall = RuntimeCall;
70
	type Hash = H256;
71
	type Hashing = BlakeTwo256;
72
	type AccountId = AccountId;
73
	type Lookup = IdentityLookup<Self::AccountId>;
74
	type RuntimeEvent = RuntimeEvent;
75
	type BlockHashCount = BlockHashCount;
76
	type Version = ();
77
	type PalletInfo = PalletInfo;
78
	type AccountData = pallet_balances::AccountData<Balance>;
79
	type OnNewAccount = ();
80
	type OnKilledAccount = ();
81
	type SystemWeightInfo = ();
82
	type BlockWeights = ();
83
	type BlockLength = ();
84
	type SS58Prefix = SS58Prefix;
85
	type OnSetCode = ();
86
	type MaxConsumers = frame_support::traits::ConstU32<16>;
87
	type SingleBlockMigrations = ();
88
	type MultiBlockMigrator = ();
89
	type PreInherents = ();
90
	type PostInherents = ();
91
	type PostTransactions = ();
92
	type ExtensionsWeightInfo = ();
93
}
94
parameter_types! {
95
	pub const ExistentialDeposit: u128 = 0;
96
}
97
impl pallet_balances::Config for Runtime {
98
	type MaxReserves = ();
99
	type ReserveIdentifier = ();
100
	type MaxLocks = ();
101
	type Balance = Balance;
102
	type RuntimeEvent = RuntimeEvent;
103
	type DustRemoval = ();
104
	type ExistentialDeposit = ExistentialDeposit;
105
	type AccountStore = System;
106
	type WeightInfo = ();
107
	type RuntimeHoldReason = ();
108
	type FreezeIdentifier = ();
109
	type MaxFreezes = ();
110
	type RuntimeFreezeReason = ();
111
	type DoneSlashHandler = ();
112
}
113

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

            
131
pub type PCall = ProxyPrecompileCall<Runtime>;
132

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

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

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

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

            
156
parameter_types! {
157
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
158
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
159
	pub const 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
impl pallet_evm::Config for Runtime {
170
	type FeeCalculator = ();
171
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
172
	type WeightPerGas = WeightPerGas;
173
	type CallOrigin = EnsureAddressAlways;
174
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
175
	type AddressMapping = AccountId;
176
	type Currency = Balances;
177
	type RuntimeEvent = RuntimeEvent;
178
	type Runner = pallet_evm::runner::stack::Runner<Self>;
179
	type PrecompilesType = Precompiles<Self>;
180
	type PrecompilesValue = PrecompilesValue;
181
	type ChainId = ();
182
	type OnChargeTransaction = ();
183
	type BlockGasLimit = BlockGasLimit;
184
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
185
	type FindAuthor = ();
186
	type OnCreate = ();
187
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
188
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
189
	type Timestamp = Timestamp;
190
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
191
	type AccountProvider = FrameSystemAccountProvider<Self>;
192
}
193

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

            
204
#[repr(u8)]
205
#[derive(
206
	Debug, Eq, PartialEq, Ord, PartialOrd, Decode, MaxEncodedLen, Encode, Clone, Copy, TypeInfo,
207
)]
208
pub enum ProxyType {
209
6
	Any = 0,
210
24
	Something = 1,
211
3
	Nothing = 2,
212
}
213

            
214
impl std::default::Default for ProxyType {
215
	fn default() -> Self {
216
		ProxyType::Any
217
	}
218
}
219

            
220
impl crate::EvmProxyCallFilter for ProxyType {
221
2
	fn is_evm_proxy_call_allowed(
222
2
		&self,
223
2
		_call: &crate::EvmSubCall,
224
2
		_recipient_has_code: bool,
225
2
		_gas: u64,
226
2
	) -> precompile_utils::EvmResult<bool> {
227
2
		Ok(match self {
228
1
			Self::Any => true,
229
			Self::Something => true,
230
1
			Self::Nothing => false,
231
		})
232
2
	}
233
}
234

            
235
impl InstanceFilter<RuntimeCall> for ProxyType {
236
1
	fn filter(&self, _: &RuntimeCall) -> bool {
237
1
		true
238
1
	}
239

            
240
	fn is_superset(&self, o: &Self) -> bool {
241
		(*self as u8) > (*o as u8)
242
	}
243
}
244

            
245
parameter_types! {
246
	pub const ProxyDepositBase: u64 = 100;
247
	pub const ProxyDepositFactor: u64 = 1;
248
	pub const MaxProxies: u32 = 5;
249
	pub const MaxPending: u32 = 5;
250
}
251
impl pallet_proxy::Config for Runtime {
252
	type RuntimeEvent = RuntimeEvent;
253
	type RuntimeCall = RuntimeCall;
254
	type Currency = Balances;
255
	type ProxyType = ProxyType;
256
	type ProxyDepositBase = ProxyDepositBase;
257
	type ProxyDepositFactor = ProxyDepositFactor;
258
	type MaxProxies = MaxProxies;
259
	type WeightInfo = ();
260
	type MaxPending = MaxPending;
261
	type CallHasher = BlakeTwo256;
262
	type AnnouncementDepositBase = ();
263
	type AnnouncementDepositFactor = ();
264
}
265

            
266
/// Build test externalities, prepopulated with data for testing democracy precompiles
267
pub(crate) struct ExtBuilder {
268
	/// Endowed accounts with balances
269
	balances: Vec<(AccountId, Balance)>,
270
}
271

            
272
impl Default for ExtBuilder {
273
28
	fn default() -> ExtBuilder {
274
28
		ExtBuilder { balances: vec![] }
275
28
	}
276
}
277

            
278
impl ExtBuilder {
279
	/// Fund some accounts before starting the test
280
25
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
281
25
		self.balances = balances;
282
25
		self
283
25
	}
284

            
285
	/// Build the test externalities for use in tests
286
28
	pub(crate) fn build(self) -> sp_io::TestExternalities {
287
28
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
288
28
			.build_storage()
289
28
			.expect("Frame system builds valid default genesis config");
290
28

            
291
28
		pallet_balances::GenesisConfig::<Runtime> {
292
28
			balances: self.balances.clone(),
293
28
		}
294
28
		.assimilate_storage(&mut t)
295
28
		.expect("Pallet balances storage can be assimilated");
296
28

            
297
28
		let mut ext = sp_io::TestExternalities::new(t);
298
28
		ext.execute_with(|| {
299
28
			System::set_block_number(1);
300
28
		});
301
28
		ext
302
28
	}
303
}
304

            
305
3
pub(crate) fn events() -> Vec<RuntimeEvent> {
306
3
	System::events()
307
3
		.into_iter()
308
10
		.map(|r| r.event)
309
3
		.collect::<Vec<_>>()
310
3
}
311

            
312
/// Panics if an event is not found in the system log of events
313
#[macro_export]
314
macro_rules! assert_event_emitted {
315
	($event:expr) => {
316
		match &$event {
317
			e => {
318
				assert!(
319
6
					crate::mock::events().iter().find(|x| *x == e).is_some(),
320
					"Event {:?} was not found in events: \n {:#?}",
321
					e,
322
					crate::mock::events()
323
				);
324
			}
325
		}
326
	};
327
}
328

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