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
1105
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
1105
);
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
	type CreateOriginFilter = ();
164
	type CreateInnerOriginFilter = ();
165
}
166

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

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

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

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

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

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

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

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

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

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

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

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

            
340
65
		let mut ext = sp_io::TestExternalities::new(t);
341
65
		ext.execute_with(|| System::set_block_number(1));
342
65
		ext
343
65
	}
344
}
345

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

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

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

            
371
25
pub(crate) fn events() -> Vec<RuntimeEvent> {
372
25
	System::events()
373
25
		.into_iter()
374
89
		.map(|r| r.event)
375
25
		.collect::<Vec<_>>()
376
25
}