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, Get, OnFinalize, OnInitialize},
22
	weights::Weight,
23
};
24
use frame_system::pallet_prelude::BlockNumberFor;
25
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot};
26
use pallet_parachain_staking::{AwardedPts, InflationInfo, Points, Range};
27
use precompile_utils::{
28
	precompile_set::*,
29
	testing::{Alice, MockAccount},
30
};
31
use sp_consensus_slots::Slot;
32
use sp_core::{H256, U256};
33
use sp_io;
34
use sp_runtime::{
35
	traits::{BlakeTwo256, IdentityLookup},
36
	BuildStorage, Perbill, Percent,
37
};
38

            
39
pub type AccountId = MockAccount;
40
pub type Balance = u128;
41
pub type BlockNumber = BlockNumberFor<Runtime>;
42

            
43
type Block = frame_system::mocking::MockBlockU32<Runtime>;
44

            
45
7534
construct_runtime!(
46
	pub enum Runtime {
47
		System: frame_system,
48
		Balances: pallet_balances,
49
		Evm: pallet_evm,
50
		Timestamp: pallet_timestamp,
51
		ParachainStaking: pallet_parachain_staking,
52
	}
53
20202
);
54

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

            
63
impl frame_system::Config for Runtime {
64
	type BaseCallFilter = Everything;
65
	type DbWeight = ();
66
	type RuntimeOrigin = RuntimeOrigin;
67
	type RuntimeTask = RuntimeTask;
68
	type Nonce = u64;
69
	type Block = Block;
70
	type RuntimeCall = RuntimeCall;
71
	type Hash = H256;
72
	type Hashing = BlakeTwo256;
73
	type AccountId = AccountId;
74
	type Lookup = IdentityLookup<AccountId>;
75
	type RuntimeEvent = RuntimeEvent;
76
	type BlockHashCount = BlockHashCount;
77
	type Version = ();
78
	type PalletInfo = PalletInfo;
79
	type AccountData = pallet_balances::AccountData<Balance>;
80
	type OnNewAccount = ();
81
	type OnKilledAccount = ();
82
	type SystemWeightInfo = ();
83
	type BlockWeights = ();
84
	type BlockLength = ();
85
	type SS58Prefix = SS58Prefix;
86
	type OnSetCode = ();
87
	type MaxConsumers = frame_support::traits::ConstU32<16>;
88
	type SingleBlockMigrations = ();
89
	type MultiBlockMigrator = ();
90
	type PreInherents = ();
91
	type PostInherents = ();
92
	type PostTransactions = ();
93
}
94

            
95
parameter_types! {
96
	pub const ExistentialDeposit: u128 = 0;
97
}
98
impl pallet_balances::Config for Runtime {
99
	type MaxReserves = ();
100
	type ReserveIdentifier = [u8; 4];
101
	type MaxLocks = ();
102
	type Balance = Balance;
103
	type RuntimeEvent = RuntimeEvent;
104
	type DustRemoval = ();
105
	type ExistentialDeposit = ExistentialDeposit;
106
	type AccountStore = System;
107
	type WeightInfo = ();
108
	type RuntimeHoldReason = ();
109
	type FreezeIdentifier = ();
110
	type MaxFreezes = ();
111
	type RuntimeFreezeReason = ();
112
}
113

            
114
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
115
/// Block storage limit in bytes. Set to 40 KB.
116
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
117

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

            
133
pub type Precompiles<R> =
134
	PrecompileSetBuilder<R, (PrecompileAt<AddressU64<1>, ParachainStakingPrecompile<R>>,)>;
135

            
136
pub type PCall = ParachainStakingPrecompileCall<Runtime>;
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 SuicideQuickClearLimit = SuicideQuickClearLimit;
158
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
159
	type Timestamp = Timestamp;
160
	type WeightInfo = pallet_evm::weights::SubstrateWeight<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
const GENESIS_BLOCKS_PER_ROUND: u32 = 5;
173
const GENESIS_COLLATOR_COMMISSION: Perbill = Perbill::from_percent(20);
174
const GENESIS_PARACHAIN_BOND_RESERVE_PERCENT: Percent = Percent::from_percent(30);
175
const GENESIS_NUM_SELECTED_CANDIDATES: u32 = 5;
176
parameter_types! {
177
	pub const MinBlocksPerRound: u32 = 3;
178
	pub const MaxOfflineRounds: u32 = 2;
179
	pub const LeaveCandidatesDelay: u32 = 2;
180
	pub const CandidateBondLessDelay: u32 = 2;
181
	pub const LeaveDelegatorsDelay: u32 = 2;
182
	pub const RevokeDelegationDelay: u32 = 2;
183
	pub const DelegationBondLessDelay: u32 = 2;
184
	pub const RewardPaymentDelay: u32 = 2;
185
	pub const MinSelectedCandidates: u32 = GENESIS_NUM_SELECTED_CANDIDATES;
186
	pub const MaxTopDelegationsPerCandidate: u32 = 2;
187
	pub const MaxBottomDelegationsPerCandidate: u32 = 4;
188
	pub const MaxDelegationsPerDelegator: u32 = 4;
189
	pub const MinCandidateStk: u128 = 10;
190
	pub const MinDelegation: u128 = 3;
191
	pub const MaxCandidates: u32 = 10;
192
	pub BlockAuthor: AccountId = Alice.into();
193
}
194

            
195
pub struct StakingRoundSlotProvider;
196
impl Get<Slot> for StakingRoundSlotProvider {
197
17
	fn get() -> Slot {
198
17
		let block_number: u64 = System::block_number().into();
199
17
		Slot::from(block_number)
200
17
	}
201
}
202

            
203
impl pallet_parachain_staking::Config for Runtime {
204
	type RuntimeEvent = RuntimeEvent;
205
	type Currency = Balances;
206
	type MonetaryGovernanceOrigin = frame_system::EnsureRoot<AccountId>;
207
	type MinBlocksPerRound = MinBlocksPerRound;
208
	type MaxOfflineRounds = MaxOfflineRounds;
209
	type LeaveCandidatesDelay = LeaveCandidatesDelay;
210
	type CandidateBondLessDelay = CandidateBondLessDelay;
211
	type LeaveDelegatorsDelay = LeaveDelegatorsDelay;
212
	type RevokeDelegationDelay = RevokeDelegationDelay;
213
	type DelegationBondLessDelay = DelegationBondLessDelay;
214
	type RewardPaymentDelay = RewardPaymentDelay;
215
	type MinSelectedCandidates = MinSelectedCandidates;
216
	type MaxTopDelegationsPerCandidate = MaxTopDelegationsPerCandidate;
217
	type MaxBottomDelegationsPerCandidate = MaxBottomDelegationsPerCandidate;
218
	type MaxDelegationsPerDelegator = MaxDelegationsPerDelegator;
219
	type MinCandidateStk = MinCandidateStk;
220
	type MinDelegation = MinDelegation;
221
	type BlockAuthor = BlockAuthor;
222
	type PayoutCollatorReward = ();
223
	type OnCollatorPayout = ();
224
	type OnInactiveCollator = ();
225
	type OnNewRound = ();
226
	type SlotProvider = StakingRoundSlotProvider;
227
	type WeightInfo = ();
228
	type MaxCandidates = MaxCandidates;
229
	type SlotDuration = frame_support::traits::ConstU64<6_000>;
230
	type BlockTime = frame_support::traits::ConstU64<6_000>;
231
}
232

            
233
pub(crate) struct ExtBuilder {
234
	// endowed accounts with balances
235
	balances: Vec<(AccountId, Balance)>,
236
	// [collator, amount]
237
	collators: Vec<(AccountId, Balance)>,
238
	// [delegator, collator, delegation_amount]
239
	delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
240
	// inflation config
241
	inflation: InflationInfo<Balance>,
242
}
243

            
244
impl Default for ExtBuilder {
245
65
	fn default() -> ExtBuilder {
246
65
		ExtBuilder {
247
65
			balances: vec![],
248
65
			delegations: vec![],
249
65
			collators: vec![],
250
65
			inflation: InflationInfo {
251
65
				expect: Range {
252
65
					min: 700,
253
65
					ideal: 700,
254
65
					max: 700,
255
65
				},
256
65
				// not used
257
65
				annual: Range {
258
65
					min: Perbill::from_percent(50),
259
65
					ideal: Perbill::from_percent(50),
260
65
					max: Perbill::from_percent(50),
261
65
				},
262
65
				// unrealistically high parameterization, only for testing
263
65
				round: Range {
264
65
					min: Perbill::from_percent(5),
265
65
					ideal: Perbill::from_percent(5),
266
65
					max: Perbill::from_percent(5),
267
65
				},
268
65
			},
269
65
		}
270
65
	}
271
}
272

            
273
impl ExtBuilder {
274
54
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
275
54
		self.balances = balances;
276
54
		self
277
54
	}
278

            
279
51
	pub(crate) fn with_candidates(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
280
51
		self.collators = collators;
281
51
		self
282
51
	}
283

            
284
24
	pub(crate) fn with_delegations(
285
24
		mut self,
286
24
		delegations: Vec<(AccountId, AccountId, Balance)>,
287
24
	) -> Self {
288
24
		self.delegations = delegations
289
24
			.into_iter()
290
35
			.map(|d| (d.0, d.1, d.2, Percent::zero()))
291
24
			.collect();
292
24
		self
293
24
	}
294

            
295
2
	pub(crate) fn with_auto_compounding_delegations(
296
2
		mut self,
297
2
		delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
298
2
	) -> Self {
299
2
		self.delegations = delegations
300
2
			.into_iter()
301
2
			.map(|d| (d.0, d.1, d.2, d.3))
302
2
			.collect();
303
2
		self
304
2
	}
305

            
306
	#[allow(dead_code)]
307
	pub(crate) fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self {
308
		self.inflation = inflation;
309
		self
310
	}
311

            
312
65
	pub(crate) fn build(self) -> sp_io::TestExternalities {
313
65
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
314
65
			.build_storage()
315
65
			.expect("Frame system builds valid default genesis config");
316
65

            
317
65
		pallet_balances::GenesisConfig::<Runtime> {
318
65
			balances: self.balances,
319
65
		}
320
65
		.assimilate_storage(&mut t)
321
65
		.expect("Pallet balances storage can be assimilated");
322
65
		pallet_parachain_staking::GenesisConfig::<Runtime> {
323
65
			candidates: self.collators,
324
65
			delegations: self.delegations,
325
65
			inflation_config: self.inflation,
326
65
			collator_commission: GENESIS_COLLATOR_COMMISSION,
327
65
			parachain_bond_reserve_percent: GENESIS_PARACHAIN_BOND_RESERVE_PERCENT,
328
65
			blocks_per_round: GENESIS_BLOCKS_PER_ROUND,
329
65
			num_selected_candidates: GENESIS_NUM_SELECTED_CANDIDATES,
330
65
		}
331
65
		.assimilate_storage(&mut t)
332
65
		.expect("Parachain Staking's storage can be assimilated");
333
65

            
334
65
		let mut ext = sp_io::TestExternalities::new(t);
335
65
		ext.execute_with(|| System::set_block_number(1));
336
65
		ext
337
65
	}
338
}
339

            
340
// Sets the same storage changes as EventHandler::note_author impl
341
4
pub(crate) fn set_points(round: BlockNumber, acc: impl Into<AccountId>, pts: u32) {
342
4
	<Points<Runtime>>::mutate(round, |p| *p += pts);
343
4
	<AwardedPts<Runtime>>::mutate(round, acc.into(), |p| *p += pts);
344
4
}
345

            
346
13
pub(crate) fn roll_to(n: BlockNumber) {
347
93
	while System::block_number() < n {
348
80
		ParachainStaking::on_finalize(System::block_number());
349
80
		Balances::on_finalize(System::block_number());
350
80
		System::on_finalize(System::block_number());
351
80
		System::set_block_number(System::block_number() + 1);
352
80
		System::on_initialize(System::block_number());
353
80
		Balances::on_initialize(System::block_number());
354
80
		ParachainStaking::on_initialize(System::block_number());
355
80
	}
356
13
}
357

            
358
/// Rolls block-by-block to the beginning of the specified round.
359
/// This will complete the block in which the round change occurs.
360
9
pub(crate) fn roll_to_round_begin(round: BlockNumber) {
361
9
	let block = (round - 1) * GENESIS_BLOCKS_PER_ROUND;
362
9
	roll_to(block)
363
9
}
364

            
365
25
pub(crate) fn events() -> Vec<RuntimeEvent> {
366
25
	System::events()
367
25
		.into_iter()
368
89
		.map(|r| r.event)
369
25
		.collect::<Vec<_>>()
370
25
}