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
7656
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
20866
);
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
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
162
}
163

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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