1
// Copyright 2019-2022 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};
23
use precompile_utils::{precompile_set::*, testing::MockAccount};
24
use sp_core::{ConstU32, 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
}
70

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

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

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

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

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

            
107
pub type PCall = Erc20BalancesPrecompileCall<Runtime, NativeErc20Metadata, ()>;
108

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

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

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

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

            
162
/// ERC20 metadata for the native token.
163
pub struct NativeErc20Metadata;
164

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

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

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

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

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

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

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

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

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

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

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