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(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 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
	type CreateOriginFilter = ();
193
	type CreateInnerOriginFilter = ();
194
}
195

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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