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
	type CreateOriginFilter = ();
153
	type CreateInnerOriginFilter = ();
154
}
155

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

            
166
/// ERC20 metadata for the native token.
167
pub struct NativeErc20Metadata;
168

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

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

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

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

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

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

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

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

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

            
221
27
		let mut ext = sp_io::TestExternalities::new(t);
222
27
		ext.execute_with(|| System::set_block_number(1));
223
27
		ext
224
27
	}
225
}
226

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