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

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

            
129
pub type PCall = ProxyPrecompileCall<Runtime>;
130

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

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

            
142
1
	fn ensure_address_origin(
143
1
		_address: &H160,
144
1
		_origin: OuterOrigin,
145
1
	) -> Result<Self::Success, sp_runtime::traits::BadOrigin> {
146
1
		Ok(())
147
1
	}
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 BlockGasLimit: U256 = U256::from(u64::MAX);
156
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
157
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
158
	pub GasLimitPovSizeRatio: u64 = {
159
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
160
		block_gas_limit.saturating_div(MAX_POV_SIZE)
161
	};
162
	pub GasLimitStorageGrowthRatio: u64 = {
163
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
164
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
165
	};
166
}
167
impl pallet_evm::Config for Runtime {
168
	type FeeCalculator = ();
169
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
170
	type WeightPerGas = WeightPerGas;
171
	type CallOrigin = EnsureAddressAlways;
172
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
173
	type AddressMapping = AccountId;
174
	type Currency = Balances;
175
	type RuntimeEvent = RuntimeEvent;
176
	type Runner = pallet_evm::runner::stack::Runner<Self>;
177
	type PrecompilesType = Precompiles<Self>;
178
	type PrecompilesValue = PrecompilesValue;
179
	type ChainId = ();
180
	type OnChargeTransaction = ();
181
	type BlockGasLimit = BlockGasLimit;
182
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
183
	type FindAuthor = ();
184
	type OnCreate = ();
185
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
186
	type SuicideQuickClearLimit = ConstU32<0>;
187
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
188
	type Timestamp = Timestamp;
189
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
190
	type AccountProvider = FrameSystemAccountProvider<Self>;
191
}
192

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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