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
2783
construct_runtime!(
44
863
	pub enum Runtime	{
45
863
		System: frame_system,
46
863
		Balances: pallet_balances,
47
863
		Evm: pallet_evm,
48
863
		Timestamp: pallet_timestamp,
49
863
		Identity: pallet_identity,
50
863
	}
51
2911
);
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 RuntimeEvent = RuntimeEvent;
147
	type Runner = pallet_evm::runner::stack::Runner<Self>;
148
	type PrecompilesType = Precompiles<Runtime>;
149
	type PrecompilesValue = PrecompilesValue;
150
	type ChainId = ();
151
	type OnChargeTransaction = ();
152
	type BlockGasLimit = BlockGasLimit;
153
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
154
	type FindAuthor = ();
155
	type OnCreate = ();
156
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
157
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
158
	type Timestamp = Timestamp;
159
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
160
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
161
}
162

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

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

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

            
185
parameter_types! {
186
	pub const BasicDeposit: u64 = 10;
187
	pub const ByteDeposit: u64 = 10;
188
	pub const SubAccountDeposit: u64 = 10;
189
	pub const MaxSubAccounts: u32 = 2;
190
	pub const MaxAdditionalFields: u32 = 2;
191
	pub const MaxRegistrars: u32 = 20;
192
}
193
impl core::fmt::Debug for MaxAdditionalFields {
194
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
195
		write!(f, "<>")
196
	}
197
}
198
impl pallet_identity::Config for Runtime {
199
	type RuntimeEvent = RuntimeEvent;
200
	type Currency = Balances;
201
	type BasicDeposit = BasicDeposit;
202
	type ByteDeposit = ByteDeposit;
203
	type SubAccountDeposit = SubAccountDeposit;
204
	type MaxSubAccounts = MaxSubAccounts;
205
	type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
206
	type MaxRegistrars = MaxRegistrars;
207
	type Slashed = ();
208
	type RegistrarOrigin = EnsureRegistrarAndForceOriginOrRoot;
209
	type ForceOrigin = EnsureRegistrarAndForceOriginOrRoot;
210
	type OffchainSignature = MockSignature;
211
	type SigningPublicKey = <MockSignature as sp_runtime::traits::Verify>::Signer;
212
	type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
213
	type PendingUsernameExpiration = ConstU32<100>;
214
	type MaxSuffixLength = ConstU32<7>;
215
	type MaxUsernameLength = ConstU32<32>;
216
	type WeightInfo = ();
217
	type UsernameGracePeriod = ();
218
	type UsernameDeposit = ();
219
}
220

            
221
pub(crate) struct ExtBuilder {
222
	/// Endowed accounts with balances
223
	balances: Vec<(AccountId, Balance)>,
224
}
225

            
226
impl Default for ExtBuilder {
227
34
	fn default() -> ExtBuilder {
228
34
		ExtBuilder { balances: vec![] }
229
34
	}
230
}
231

            
232
impl ExtBuilder {
233
	/// Fund some accounts before starting the test
234
34
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
235
34
		self.balances = balances;
236
34
		self
237
34
	}
238

            
239
	/// Build the test externalities for use in tests
240
34
	pub(crate) fn build(self) -> sp_io::TestExternalities {
241
34
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
242
34
			.build_storage()
243
34
			.expect("Frame system builds valid default genesis config");
244
34

            
245
34
		pallet_balances::GenesisConfig::<Runtime> {
246
34
			balances: self.balances.clone(),
247
34
		}
248
34
		.assimilate_storage(&mut t)
249
34
		.expect("Pallet balances storage can be assimilated");
250
34

            
251
34
		let mut ext = sp_io::TestExternalities::new(t);
252
34
		ext.execute_with(|| {
253
34
			System::set_block_number(1);
254
34
		});
255
34
		ext
256
34
	}
257
}
258

            
259
20
pub(crate) fn events() -> Vec<RuntimeEvent> {
260
20
	System::events()
261
20
		.into_iter()
262
172
		.map(|r| r.event)
263
20
		.collect::<Vec<_>>()
264
20
}