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
//! 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, FrameSystemAccountProvider};
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
7745
construct_runtime!(
46
1105
	pub enum Runtime {
47
1105
		System: frame_system,
48
1105
		Balances: pallet_balances,
49
1105
		Evm: pallet_evm,
50
1105
		Timestamp: pallet_timestamp,
51
1105
		ParachainStaking: pallet_parachain_staking,
52
1105
	}
53
7896
);
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
	type ExtensionsWeightInfo = ();
94
}
95

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

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

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

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

            
138
pub type PCall = ParachainStakingPrecompileCall<Runtime>;
139

            
140
impl pallet_evm::Config for Runtime {
141
	type FeeCalculator = ();
142
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
143
	type WeightPerGas = WeightPerGas;
144
	type CallOrigin = EnsureAddressRoot<AccountId>;
145
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
146
	type AddressMapping = AccountId;
147
	type Currency = Balances;
148
	type RuntimeEvent = RuntimeEvent;
149
	type Runner = pallet_evm::runner::stack::Runner<Self>;
150
	type PrecompilesType = Precompiles<Runtime>;
151
	type PrecompilesValue = PrecompilesValue;
152
	type ChainId = ();
153
	type OnChargeTransaction = ();
154
	type BlockGasLimit = BlockGasLimit;
155
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
156
	type FindAuthor = ();
157
	type OnCreate = ();
158
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
159
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
160
	type Timestamp = Timestamp;
161
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
162
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
163
}
164

            
165
parameter_types! {
166
	pub const MinimumPeriod: u64 = 5;
167
}
168
impl pallet_timestamp::Config for Runtime {
169
	type Moment = u64;
170
	type OnTimestampSet = ();
171
	type MinimumPeriod = MinimumPeriod;
172
	type WeightInfo = ();
173
}
174
const GENESIS_BLOCKS_PER_ROUND: u32 = 5;
175
const GENESIS_COLLATOR_COMMISSION: Perbill = Perbill::from_percent(20);
176
const GENESIS_PARACHAIN_BOND_RESERVE_PERCENT: Percent = Percent::from_percent(30);
177
const GENESIS_NUM_SELECTED_CANDIDATES: u32 = 5;
178
parameter_types! {
179
	pub const MinBlocksPerRound: u32 = 3;
180
	pub const MaxOfflineRounds: u32 = 2;
181
	pub const LeaveCandidatesDelay: u32 = 2;
182
	pub const CandidateBondLessDelay: u32 = 2;
183
	pub const LeaveDelegatorsDelay: u32 = 2;
184
	pub const RevokeDelegationDelay: u32 = 2;
185
	pub const DelegationBondLessDelay: u32 = 2;
186
	pub const RewardPaymentDelay: u32 = 2;
187
	pub const MinSelectedCandidates: u32 = GENESIS_NUM_SELECTED_CANDIDATES;
188
	pub const MaxTopDelegationsPerCandidate: u32 = 2;
189
	pub const MaxBottomDelegationsPerCandidate: u32 = 4;
190
	pub const MaxDelegationsPerDelegator: u32 = 4;
191
	pub const MinCandidateStk: u128 = 10;
192
	pub const MinDelegation: u128 = 3;
193
	pub const MaxCandidates: u32 = 10;
194
	pub BlockAuthor: AccountId = Alice.into();
195
}
196

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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