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 super::*;
19
use frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{EitherOfDiverse, Everything, SortedMembers},
22
	weights::Weight,
23
};
24
use frame_system::{EnsureRoot, EnsureSignedBy};
25
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
26
use pallet_identity::legacy::IdentityInfo;
27
use precompile_utils::mock_account;
28
use precompile_utils::{
29
	precompile_set::*,
30
	testing::{MockAccount, MockSignature},
31
};
32
use sp_core::{H256, U256};
33
use sp_runtime::{
34
	traits::{BlakeTwo256, IdentityLookup},
35
	BuildStorage, Perbill,
36
};
37

            
38
pub type AccountId = MockAccount;
39
pub type Balance = u128;
40

            
41
type Block = frame_system::mocking::MockBlockU32<Runtime>;
42

            
43
construct_runtime!(
44
	pub enum Runtime	{
45
		System: frame_system,
46
		Balances: pallet_balances,
47
		Evm: pallet_evm,
48
		Timestamp: pallet_timestamp,
49
		Identity: pallet_identity,
50
	}
51
);
52

            
53
parameter_types! {
54
	pub const BlockHashCount: u32 = 250;
55
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
56
	pub const MaximumBlockLength: u32 = 2 * 1024;
57
	pub const AvailableBlockRatio: Perbill = Perbill::one();
58
	pub const SS58Prefix: u8 = 42;
59
}
60

            
61
impl frame_system::Config for Runtime {
62
	type BaseCallFilter = Everything;
63
	type DbWeight = ();
64
	type RuntimeOrigin = RuntimeOrigin;
65
	type RuntimeTask = RuntimeTask;
66
	type Nonce = u64;
67
	type Block = Block;
68
	type RuntimeCall = RuntimeCall;
69
	type Hash = H256;
70
	type Hashing = BlakeTwo256;
71
	type AccountId = AccountId;
72
	type Lookup = IdentityLookup<AccountId>;
73
	type RuntimeEvent = RuntimeEvent;
74
	type BlockHashCount = BlockHashCount;
75
	type Version = ();
76
	type PalletInfo = PalletInfo;
77
	type AccountData = pallet_balances::AccountData<Balance>;
78
	type OnNewAccount = ();
79
	type OnKilledAccount = ();
80
	type SystemWeightInfo = ();
81
	type BlockWeights = ();
82
	type BlockLength = ();
83
	type SS58Prefix = SS58Prefix;
84
	type OnSetCode = ();
85
	type MaxConsumers = frame_support::traits::ConstU32<16>;
86
	type SingleBlockMigrations = ();
87
	type MultiBlockMigrator = ();
88
	type PreInherents = ();
89
	type PostInherents = ();
90
	type PostTransactions = ();
91
	type ExtensionsWeightInfo = ();
92
}
93
parameter_types! {
94
	pub const ExistentialDeposit: u128 = 1;
95
}
96
impl pallet_balances::Config for Runtime {
97
	type MaxReserves = ();
98
	type ReserveIdentifier = [u8; 4];
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
	type DoneSlashHandler = ();
111
}
112

            
113
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
114
/// Block storage limit in bytes. Set to 40 KB.
115
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
116

            
117
parameter_types! {
118
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
119
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
120
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
121
	pub GasLimitPovSizeRatio: u64 = {
122
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
123
		block_gas_limit.saturating_div(MAX_POV_SIZE)
124
	};
125
	pub GasLimitStorageGrowthRatio: u64 = {
126
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
127
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
128
	};
129
}
130

            
131
pub type Precompiles<R> = PrecompileSetBuilder<
132
	R,
133
	(PrecompileAt<AddressU64<1>, IdentityPrecompile<R, MaxAdditionalFields>>,),
134
>;
135

            
136
pub type PCall = IdentityPrecompileCall<Runtime, MaxAdditionalFields>;
137

            
138
impl pallet_evm::Config for Runtime {
139
	type FeeCalculator = ();
140
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
141
	type WeightPerGas = WeightPerGas;
142
	type CallOrigin = EnsureAddressRoot<AccountId>;
143
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
144
	type AddressMapping = AccountId;
145
	type Currency = Balances;
146
	type Runner = pallet_evm::runner::stack::Runner<Self>;
147
	type PrecompilesType = Precompiles<Runtime>;
148
	type PrecompilesValue = PrecompilesValue;
149
	type ChainId = ();
150
	type OnChargeTransaction = ();
151
	type BlockGasLimit = BlockGasLimit;
152
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
153
	type FindAuthor = ();
154
	type OnCreate = ();
155
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
156
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
157
	type Timestamp = Timestamp;
158
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
159
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
160
	type CreateOriginFilter = ();
161
	type CreateInnerOriginFilter = ();
162
}
163

            
164
parameter_types! {
165
	pub const MinimumPeriod: u64 = 5;
166
}
167
impl pallet_timestamp::Config for Runtime {
168
	type Moment = u64;
169
	type OnTimestampSet = ();
170
	type MinimumPeriod = MinimumPeriod;
171
	type WeightInfo = ();
172
}
173

            
174
22
mock_account!(RegistrarAndForceOrigin, |_| H160::repeat_byte(0x1C).into());
175
impl SortedMembers<MockAccount> for RegistrarAndForceOrigin {
176
11
	fn sorted_members() -> Vec<MockAccount> {
177
11
		vec![RegistrarAndForceOrigin.into()]
178
11
	}
179
	#[cfg(feature = "runtime-benchmarks")]
180
	fn add(_m: &MockAccount) {}
181
}
182

            
183
type EnsureRegistrarAndForceOriginOrRoot =
184
	EitherOfDiverse<EnsureRoot<AccountId>, EnsureSignedBy<RegistrarAndForceOrigin, AccountId>>;
185

            
186
parameter_types! {
187
	pub const BasicDeposit: u64 = 10;
188
	pub const ByteDeposit: u64 = 10;
189
	pub const SubAccountDeposit: u64 = 10;
190
	pub const MaxSubAccounts: u32 = 2;
191
	pub const MaxAdditionalFields: u32 = 2;
192
	pub const MaxRegistrars: u32 = 20;
193
}
194
impl core::fmt::Debug for MaxAdditionalFields {
195
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
196
		write!(f, "<>")
197
	}
198
}
199

            
200
#[cfg(feature = "runtime-benchmarks")]
201
pub struct IdentityBenchmarkHelper;
202
#[cfg(feature = "runtime-benchmarks")]
203
impl
204
	pallet_identity::BenchmarkHelper<
205
		<MockSignature as sp_runtime::traits::Verify>::Signer,
206
		MockSignature,
207
	> for IdentityBenchmarkHelper
208
{
209
	fn sign_message(
210
		_message: &[u8],
211
	) -> (
212
		<MockSignature as sp_runtime::traits::Verify>::Signer,
213
		MockSignature,
214
	) {
215
		// This is only used in runtime benchmarks, not in precompile tests
216
		// So we panic here since this should never be called in tests
217
		panic!("BenchmarkHelper::sign_message should not be called in precompile tests")
218
	}
219
}
220

            
221
impl pallet_identity::Config for Runtime {
222
	type RuntimeEvent = RuntimeEvent;
223
	type Currency = Balances;
224
	type BasicDeposit = BasicDeposit;
225
	type ByteDeposit = ByteDeposit;
226
	type SubAccountDeposit = SubAccountDeposit;
227
	type MaxSubAccounts = MaxSubAccounts;
228
	type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
229
	type MaxRegistrars = MaxRegistrars;
230
	type Slashed = ();
231
	type RegistrarOrigin = EnsureRegistrarAndForceOriginOrRoot;
232
	type ForceOrigin = EnsureRegistrarAndForceOriginOrRoot;
233
	type OffchainSignature = MockSignature;
234
	type SigningPublicKey = <MockSignature as sp_runtime::traits::Verify>::Signer;
235
	type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
236
	type PendingUsernameExpiration = ConstU32<100>;
237
	type MaxSuffixLength = ConstU32<7>;
238
	type MaxUsernameLength = ConstU32<32>;
239
	type WeightInfo = ();
240
	type UsernameGracePeriod = ();
241
	type UsernameDeposit = ();
242
	#[cfg(feature = "runtime-benchmarks")]
243
	type BenchmarkHelper = IdentityBenchmarkHelper;
244
}
245

            
246
pub(crate) struct ExtBuilder {
247
	/// Endowed accounts with balances
248
	balances: Vec<(AccountId, Balance)>,
249
}
250

            
251
impl Default for ExtBuilder {
252
34
	fn default() -> ExtBuilder {
253
34
		ExtBuilder { balances: vec![] }
254
34
	}
255
}
256

            
257
impl ExtBuilder {
258
	/// Fund some accounts before starting the test
259
34
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
260
34
		self.balances = balances;
261
34
		self
262
34
	}
263

            
264
	/// Build the test externalities for use in tests
265
34
	pub(crate) fn build(self) -> sp_io::TestExternalities {
266
34
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
267
34
			.build_storage()
268
34
			.expect("Frame system builds valid default genesis config");
269

            
270
34
		pallet_balances::GenesisConfig::<Runtime> {
271
34
			balances: self.balances.clone(),
272
34
			dev_accounts: Default::default(),
273
34
		}
274
34
		.assimilate_storage(&mut t)
275
34
		.expect("Pallet balances storage can be assimilated");
276

            
277
34
		let mut ext = sp_io::TestExternalities::new(t);
278
34
		ext.execute_with(|| {
279
34
			System::set_block_number(1);
280
34
		});
281
34
		ext
282
34
	}
283
}
284

            
285
20
pub(crate) fn events() -> Vec<RuntimeEvent> {
286
20
	System::events()
287
20
		.into_iter()
288
20
		.map(|r| r.event)
289
20
		.collect::<Vec<_>>()
290
20
}