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
//! Testing utilities.
18

            
19
use super::*;
20

            
21
use frame_support::{construct_runtime, parameter_types, traits::Everything, weights::Weight};
22
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
23
use precompile_utils::{precompile_set::*, testing::MockAccount};
24
use sp_core::{H256, U256};
25
use sp_runtime::{
26
	traits::{BlakeTwo256, IdentityLookup},
27
	BuildStorage,
28
};
29

            
30
pub type AccountId = MockAccount;
31
pub type Balance = u128;
32
pub type Block = frame_system::mocking::MockBlockU32<Runtime>;
33

            
34
parameter_types! {
35
	pub const BlockHashCount: u32 = 250;
36
	pub const SS58Prefix: u8 = 42;
37
}
38

            
39
impl frame_system::Config for Runtime {
40
	type BaseCallFilter = Everything;
41
	type DbWeight = ();
42
	type RuntimeOrigin = RuntimeOrigin;
43
	type RuntimeTask = RuntimeTask;
44
	type Nonce = u64;
45
	type Block = Block;
46
	type RuntimeCall = RuntimeCall;
47
	type Hash = H256;
48
	type Hashing = BlakeTwo256;
49
	type AccountId = AccountId;
50
	type Lookup = IdentityLookup<Self::AccountId>;
51
	type RuntimeEvent = RuntimeEvent;
52
	type BlockHashCount = BlockHashCount;
53
	type Version = ();
54
	type PalletInfo = PalletInfo;
55
	type AccountData = pallet_balances::AccountData<Balance>;
56
	type OnNewAccount = ();
57
	type OnKilledAccount = ();
58
	type SystemWeightInfo = ();
59
	type BlockWeights = ();
60
	type BlockLength = ();
61
	type SS58Prefix = SS58Prefix;
62
	type OnSetCode = ();
63
	type MaxConsumers = frame_support::traits::ConstU32<16>;
64
	type SingleBlockMigrations = ();
65
	type MultiBlockMigrator = ();
66
	type PreInherents = ();
67
	type PostInherents = ();
68
	type PostTransactions = ();
69
	type ExtensionsWeightInfo = ();
70
}
71

            
72
parameter_types! {
73
	pub const MinimumPeriod: u64 = 5;
74
}
75

            
76
impl pallet_timestamp::Config for Runtime {
77
	type Moment = u64;
78
	type OnTimestampSet = ();
79
	type MinimumPeriod = MinimumPeriod;
80
	type WeightInfo = ();
81
}
82

            
83
parameter_types! {
84
	pub const ExistentialDeposit: u128 = 0;
85
}
86

            
87
impl pallet_balances::Config for Runtime {
88
	type MaxReserves = ();
89
	type ReserveIdentifier = ();
90
	type MaxLocks = ();
91
	type Balance = Balance;
92
	type RuntimeEvent = RuntimeEvent;
93
	type DustRemoval = ();
94
	type ExistentialDeposit = ExistentialDeposit;
95
	type AccountStore = System;
96
	type WeightInfo = ();
97
	type RuntimeHoldReason = ();
98
	type FreezeIdentifier = ();
99
	type MaxFreezes = ();
100
	type RuntimeFreezeReason = ();
101
	type DoneSlashHandler = ();
102
}
103

            
104
pub type Precompiles<R> = PrecompileSetBuilder<
105
	R,
106
	(PrecompileAt<AddressU64<1>, Erc20BalancesPrecompile<R, NativeErc20Metadata>>,),
107
>;
108

            
109
pub type PCall = Erc20BalancesPrecompileCall<Runtime, NativeErc20Metadata, ()>;
110

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

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

            
129
impl pallet_evm::Config for Runtime {
130
	type FeeCalculator = ();
131
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
132
	type WeightPerGas = WeightPerGas;
133
	type CallOrigin = EnsureAddressRoot<AccountId>;
134
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
135
	type AddressMapping = AccountId;
136
	type Currency = Balances;
137
	type RuntimeEvent = RuntimeEvent;
138
	type Runner = pallet_evm::runner::stack::Runner<Self>;
139
	type PrecompilesType = Precompiles<Self>;
140
	type PrecompilesValue = PrecompilesValue;
141
	type ChainId = ();
142
	type OnChargeTransaction = ();
143
	type BlockGasLimit = BlockGasLimit;
144
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
145
	type FindAuthor = ();
146
	type OnCreate = ();
147
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
148
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
149
	type Timestamp = Timestamp;
150
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
151
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
152
}
153

            
154
// Configure a mock runtime to test the pallet.
155
944
construct_runtime!(
156
123
	pub enum Runtime	{
157
123
		System: frame_system,
158
123
		Balances: pallet_balances,
159
123
		Evm: pallet_evm,
160
123
		Timestamp: pallet_timestamp,
161
123
	}
162
957
);
163

            
164
/// ERC20 metadata for the native token.
165
pub struct NativeErc20Metadata;
166

            
167
impl Erc20Metadata for NativeErc20Metadata {
168
	/// Returns the name of the token.
169
10
	fn name() -> &'static str {
170
10
		"Mock token"
171
10
	}
172

            
173
	/// Returns the symbol of the token.
174
2
	fn symbol() -> &'static str {
175
2
		"MOCK"
176
2
	}
177

            
178
	/// Returns the decimals places of the token.
179
2
	fn decimals() -> u8 {
180
2
		18
181
2
	}
182

            
183
	/// Must return `true` only if it represents the main native currency of
184
	/// the network. It must be the currency used in `pallet_evm`.
185
7
	fn is_native_currency() -> bool {
186
7
		true
187
7
	}
188
}
189

            
190
pub(crate) struct ExtBuilder {
191
	// endowed accounts with balances
192
	balances: Vec<(AccountId, Balance)>,
193
}
194

            
195
impl Default for ExtBuilder {
196
27
	fn default() -> ExtBuilder {
197
27
		ExtBuilder { balances: vec![] }
198
27
	}
199
}
200

            
201
impl ExtBuilder {
202
27
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
203
27
		self.balances = balances;
204
27
		self
205
27
	}
206

            
207
27
	pub(crate) fn build(self) -> sp_io::TestExternalities {
208
27
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
209
27
			.build_storage()
210
27
			.expect("Frame system builds valid default genesis config");
211
27

            
212
27
		pallet_balances::GenesisConfig::<Runtime> {
213
27
			balances: self.balances,
214
27
		}
215
27
		.assimilate_storage(&mut t)
216
27
		.expect("Pallet balances storage can be assimilated");
217
27

            
218
27
		let mut ext = sp_io::TestExternalities::new(t);
219
27
		ext.execute_with(|| System::set_block_number(1));
220
27
		ext
221
27
	}
222
}
223

            
224
4
pub(crate) fn events() -> Vec<RuntimeEvent> {
225
4
	System::events()
226
4
		.into_iter()
227
19
		.map(|r| r.event)
228
4
		.collect::<Vec<_>>()
229
4
}