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
//! Test utilities
18
use super::*;
19
use frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{Everything, PollStatus, Polling, TotalIssuanceOf},
22
	weights::Weight,
23
};
24
use pallet_conviction_voting::TallyOf;
25
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot};
26
use precompile_utils::{precompile_set::*, testing::MockAccount};
27
use sp_core::{H256, U256};
28
use sp_runtime::{
29
	traits::{BlakeTwo256, ConstU32, ConstU64, IdentityLookup},
30
	BuildStorage, DispatchError, Perbill,
31
};
32
use sp_std::collections::btree_map::BTreeMap;
33

            
34
#[cfg(feature = "runtime-benchmarks")]
35
use frame_support::traits::VoteTally;
36

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

            
40
type Block = frame_system::mocking::MockBlock<Runtime>;
41

            
42
912
construct_runtime!(
43
	pub enum Runtime	{
44
		System: frame_system,
45
		Balances: pallet_balances,
46
		Evm: pallet_evm,
47
		Timestamp: pallet_timestamp,
48
		ConvictionVoting: pallet_conviction_voting,
49
	}
50
1331
);
51

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

            
60
impl frame_system::Config for Runtime {
61
	type BaseCallFilter = Everything;
62
	type DbWeight = ();
63
	type RuntimeOrigin = RuntimeOrigin;
64
	type RuntimeTask = RuntimeTask;
65
	type Nonce = u64;
66
	type Block = Block;
67
	type RuntimeCall = RuntimeCall;
68
	type Hash = H256;
69
	type Hashing = BlakeTwo256;
70
	type AccountId = AccountId;
71
	type Lookup = IdentityLookup<AccountId>;
72
	type RuntimeEvent = RuntimeEvent;
73
	type BlockHashCount = BlockHashCount;
74
	type Version = ();
75
	type PalletInfo = PalletInfo;
76
	type AccountData = pallet_balances::AccountData<Balance>;
77
	type OnNewAccount = ();
78
	type OnKilledAccount = ();
79
	type SystemWeightInfo = ();
80
	type BlockWeights = ();
81
	type BlockLength = ();
82
	type SS58Prefix = SS58Prefix;
83
	type OnSetCode = ();
84
	type MaxConsumers = frame_support::traits::ConstU32<16>;
85
	type SingleBlockMigrations = ();
86
	type MultiBlockMigrator = ();
87
	type PreInherents = ();
88
	type PostInherents = ();
89
	type PostTransactions = ();
90
}
91
parameter_types! {
92
	pub const ExistentialDeposit: u128 = 0;
93
}
94
impl pallet_balances::Config for Runtime {
95
	type MaxReserves = ();
96
	type ReserveIdentifier = [u8; 4];
97
	type MaxLocks = ();
98
	type Balance = Balance;
99
	type RuntimeEvent = RuntimeEvent;
100
	type DustRemoval = ();
101
	type ExistentialDeposit = ExistentialDeposit;
102
	type AccountStore = System;
103
	type WeightInfo = ();
104
	type RuntimeHoldReason = ();
105
	type FreezeIdentifier = ();
106
	type MaxFreezes = ();
107
	type RuntimeFreezeReason = ();
108
}
109

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

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

            
128
pub type Precompiles<R> =
129
	PrecompileSetBuilder<R, (PrecompileAt<AddressU64<1>, ConvictionVotingPrecompile<R>>,)>;
130

            
131
pub type PCall = ConvictionVotingPrecompileCall<Runtime>;
132

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

            
158
parameter_types! {
159
	pub const MinimumPeriod: u64 = 5;
160
}
161
impl pallet_timestamp::Config for Runtime {
162
	type Moment = u64;
163
	type OnTimestampSet = ();
164
	type MinimumPeriod = MinimumPeriod;
165
	type WeightInfo = ();
166
}
167

            
168
#[derive(Clone, PartialEq, Eq, Debug)]
169
pub enum TestPollState {
170
	Ongoing(TallyOf<Runtime>, u8),
171
	Completed(u64, bool),
172
}
173
use TestPollState::*;
174

            
175
44
parameter_types! {
176
44
	pub static Polls: BTreeMap<u8, TestPollState> = vec![
177
44
		(1, Completed(1, true)),
178
44
		(2, Completed(2, false)),
179
44
		(3, Ongoing(Tally::from_parts(0, 0, 0), 0)),
180
44
	].into_iter().collect();
181
44
}
182

            
183
pub struct TestPolls;
184
impl Polling<TallyOf<Runtime>> for TestPolls {
185
	type Index = u8;
186
	type Votes = u128;
187
	type Moment = u64;
188
	type Class = u8;
189
17
	fn classes() -> Vec<u8> {
190
17
		vec![0, 1, 2]
191
17
	}
192
2
	fn as_ongoing(index: u8) -> Option<(TallyOf<Runtime>, Self::Class)> {
193
2
		Polls::get().remove(&index).and_then(|x| {
194
2
			if let TestPollState::Ongoing(t, c) = x {
195
2
				Some((t, c))
196
			} else {
197
				None
198
			}
199
2
		})
200
2
	}
201
	fn access_poll<R>(
202
		index: Self::Index,
203
		f: impl FnOnce(PollStatus<&mut TallyOf<Runtime>, u64, u8>) -> R,
204
	) -> R {
205
		let mut polls = Polls::get();
206
		let entry = polls.get_mut(&index);
207
		let r = match entry {
208
			Some(Ongoing(ref mut tally_mut_ref, class)) => {
209
				f(PollStatus::Ongoing(tally_mut_ref, *class))
210
			}
211
			Some(Completed(when, succeeded)) => f(PollStatus::Completed(
212
				(*when).try_into().unwrap(),
213
				*succeeded,
214
			)),
215
			None => f(PollStatus::None),
216
		};
217
		Polls::set(polls);
218
		r
219
	}
220
16
	fn try_access_poll<R>(
221
16
		index: Self::Index,
222
16
		f: impl FnOnce(PollStatus<&mut TallyOf<Runtime>, u64, u8>) -> Result<R, DispatchError>,
223
16
	) -> Result<R, DispatchError> {
224
16
		let mut polls = Polls::get();
225
16
		let entry = polls.get_mut(&index);
226
16
		let r = match entry {
227
16
			Some(Ongoing(ref mut tally_mut_ref, class)) => {
228
16
				f(PollStatus::Ongoing(tally_mut_ref, *class))
229
			}
230
			Some(Completed(when, succeeded)) => f(PollStatus::Completed(
231
				(*when).try_into().unwrap(),
232
				*succeeded,
233
			)),
234
			None => f(PollStatus::None),
235
		}?;
236
16
		Polls::set(polls);
237
16
		Ok(r)
238
16
	}
239

            
240
	#[cfg(feature = "runtime-benchmarks")]
241
	fn create_ongoing(class: Self::Class) -> Result<Self::Index, ()> {
242
		let mut polls = Polls::get();
243
		let i = polls.keys().rev().next().map_or(0, |x| x + 1);
244
		polls.insert(i, Ongoing(Tally::new(0), class));
245
		Polls::set(polls);
246
		Ok(i)
247
	}
248

            
249
	#[cfg(feature = "runtime-benchmarks")]
250
	fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()> {
251
		let mut polls = Polls::get();
252
		match polls.get(&index) {
253
			Some(Ongoing(..)) => {}
254
			_ => return Err(()),
255
		}
256
		let now = frame_system::Pallet::<Runtime>::block_number();
257
		polls.insert(index, Completed(now, approved));
258
		Polls::set(polls);
259
		Ok(())
260
	}
261
}
262

            
263
impl pallet_conviction_voting::Config for Runtime {
264
	type RuntimeEvent = RuntimeEvent;
265
	type Currency = pallet_balances::Pallet<Self>;
266
	type VoteLockingPeriod = ConstU64<3>;
267
	type MaxVotes = ConstU32<3>;
268
	type WeightInfo = ();
269
	type MaxTurnout = TotalIssuanceOf<Balances, Self::AccountId>;
270
	type Polls = TestPolls;
271
}
272

            
273
pub(crate) struct ExtBuilder {
274
	/// Endowed accounts with balances
275
	balances: Vec<(AccountId, Balance)>,
276
}
277

            
278
impl Default for ExtBuilder {
279
11
	fn default() -> ExtBuilder {
280
11
		ExtBuilder { balances: vec![] }
281
11
	}
282
}
283

            
284
impl ExtBuilder {
285
	/// Fund some accounts before starting the test
286
11
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
287
11
		self.balances = balances;
288
11
		self
289
11
	}
290

            
291
	/// Build the test externalities for use in tests
292
11
	pub(crate) fn build(self) -> sp_io::TestExternalities {
293
11
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
294
11
			.build_storage()
295
11
			.expect("Frame system builds valid default genesis config");
296
11

            
297
11
		pallet_balances::GenesisConfig::<Runtime> {
298
11
			balances: self.balances.clone(),
299
11
		}
300
11
		.assimilate_storage(&mut t)
301
11
		.expect("Pallet balances storage can be assimilated");
302
11

            
303
11
		let mut ext = sp_io::TestExternalities::new(t);
304
11
		ext.execute_with(|| {
305
11
			System::set_block_number(1);
306
11
		});
307
11
		ext
308
11
	}
309
}
310

            
311
10
pub(crate) fn events() -> Vec<RuntimeEvent> {
312
10
	System::events()
313
10
		.into_iter()
314
54
		.map(|r| r.event)
315
10
		.collect::<Vec<_>>()
316
10
}