referrerpolicy=no-referrer-when-downgrade

pallet_staking_async/
reward.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Era reward management.
19//!
20//! Manages the lifecycle of era reward pot accounts: creation, funding
21//! via snapshot from the general DAP pot, and draining of expired eras.
22//!
23//! Era pots are backed by a rotating pool of `POT_POOL_SIZE` accounts
24//! addressed by `era % POT_POOL_SIZE`. Once created, a slot's account is kept
25//! alive forever — at the end of each era's history window, its remaining
26//! balance is drained to [`crate::Config::UnclaimedRewardHandler`] but the
27//! provider reference is retained. A future era that reuses the same slot
28//! finds an existing zero-balance account and snapshots into it. This bounds
29//! the storage footprint contributed by era pots to a constant.
30
31use crate::*;
32use frame_support::{
33	defensive,
34	traits::{
35		fungible::{Balanced, Inspect, Mutate},
36		tokens::{Fortitude, Precision, Preservation},
37		OnUnbalanced,
38	},
39};
40use sp_runtime::{
41	traits::{AtLeast32BitUnsigned, Zero},
42	Perbill,
43};
44use sp_staking::EraIndex;
45
46/// Allocation breakdown of era-end rewards.
47#[derive(
48	Debug,
49	Clone,
50	Copy,
51	PartialEq,
52	Eq,
53	codec::Encode,
54	codec::Decode,
55	codec::DecodeWithMemTracking,
56	scale_info::TypeInfo,
57)]
58pub struct EraRewardAllocation<Balance> {
59	pub staker_rewards: Balance,
60	pub validator_incentive: Balance,
61}
62
63/// Manager for era reward pot lifecycle.
64pub struct EraRewardManager<T: Config>(core::marker::PhantomData<T>);
65
66impl<T: Config> EraRewardManager<T> {
67	/// Ensures the era pot account for `(era, kind)` exists by holding a provider
68	/// reference. Idempotent: if the slot's account is already provided (because a
69	/// previous era reused it), this is a no-op.
70	///
71	/// Should only be called in non-minting mode (`DisableMinting = true`).
72	pub(crate) fn create(era: EraIndex, kind: RewardKind) -> T::AccountId {
73		debug_assert!(
74			T::DisableMinting::get(),
75			"Era pots should only be created when DisableMinting is true"
76		);
77		let pot_account = T::RewardPots::pot_account(RewardPot::Era(era, kind));
78		if frame_system::Pallet::<T>::providers(&pot_account) == 0 {
79			frame_system::Pallet::<T>::inc_providers(&pot_account);
80		}
81		pot_account
82	}
83
84	/// Snapshots the general reward pots into era-specific pots.
85	///
86	/// DAP drips inflation continuously into the general pots. At era boundary,
87	/// this transfers the accumulated balances (minus ED) into era pots.
88	pub(crate) fn snapshot_era_rewards(era: EraIndex) -> EraRewardAllocation<BalanceOf<T>> {
89		let staker_era_pot = Self::create(era, RewardKind::StakerRewards);
90		let incentive_era_pot = Self::create(era, RewardKind::ValidatorSelfStake);
91
92		let general_staker_pot =
93			T::RewardPots::pot_account(RewardPot::General(RewardKind::StakerRewards));
94		let general_incentive_pot =
95			T::RewardPots::pot_account(RewardPot::General(RewardKind::ValidatorSelfStake));
96
97		// Leave ED in the general pots to keep them alive.
98		let staker_balance = T::Currency::reducible_balance(
99			&general_staker_pot,
100			Preservation::Preserve,
101			Fortitude::Polite,
102		);
103		let incentive_balance = T::Currency::reducible_balance(
104			&general_incentive_pot,
105			Preservation::Preserve,
106			Fortitude::Polite,
107		);
108
109		let actual_staker = if !staker_balance.is_zero() {
110			match T::Currency::transfer(
111				&general_staker_pot,
112				&staker_era_pot,
113				staker_balance,
114				Preservation::Preserve,
115			) {
116				Ok(_) => staker_balance,
117				Err(e) => {
118					log!(error, "Era {:?}: staker reward transfer failed: {:?}", era, e);
119					defensive!("Failed to transfer staker rewards to era pot");
120					Zero::zero()
121				},
122			}
123		} else {
124			Zero::zero()
125		};
126
127		let actual_incentive = if !incentive_balance.is_zero() {
128			match T::Currency::transfer(
129				&general_incentive_pot,
130				&incentive_era_pot,
131				incentive_balance,
132				Preservation::Preserve,
133			) {
134				Ok(_) => incentive_balance,
135				Err(e) => {
136					log!(error, "Era {:?}: validator incentive transfer failed: {:?}", era, e);
137					defensive!("Failed to transfer validator incentive to era pot");
138					Zero::zero()
139				},
140			}
141		} else {
142			Zero::zero()
143		};
144
145		log!(
146			info,
147			"Era {:?}: snapshotted staker_rewards={:?}, validator_incentive={:?}",
148			era,
149			actual_staker,
150			actual_incentive
151		);
152
153		EraRewardAllocation { staker_rewards: actual_staker, validator_incentive: actual_incentive }
154	}
155
156	/// Drains an era pot's remaining balance to the unclaimed reward handler.
157	///
158	/// The pot account itself is kept alive (provider retained) so the same slot
159	/// can be reused by a future era. No-op if the pot was never created (e.g.
160	/// the era ran in legacy minting mode).
161	pub(crate) fn drain(era: EraIndex, kind: RewardKind) {
162		let pot_account = T::RewardPots::pot_account(RewardPot::Era(era, kind));
163
164		// Skip if pot was never created (legacy mode doesn't create pots).
165		if frame_system::Pallet::<T>::providers(&pot_account) == 0 {
166			return;
167		}
168
169		// Anyone can lock funds in a pot with a vested transfer. Leave them in place, otherwise the
170		// lock would short the payouts of the next era reusing this slot.
171		let remaining = T::Currency::reducible_balance(
172			&pot_account,
173			Preservation::Expendable,
174			Fortitude::Polite,
175		);
176
177		if remaining.is_zero() {
178			return;
179		}
180
181		match T::Currency::withdraw(
182			&pot_account,
183			remaining,
184			Precision::BestEffort,
185			Preservation::Expendable,
186			Fortitude::Polite,
187		) {
188			Ok(credit) => {
189				T::UnclaimedRewardHandler::on_unbalanced(credit);
190				log!(
191					debug,
192					"Drained {:?} unclaimed rewards from era {:?} {:?} pot",
193					remaining,
194					era,
195					kind
196				);
197			},
198			Err(e) => {
199				defensive!("Failed to withdraw unclaimed rewards from era pot");
200				log!(
201					error,
202					"Era {:?} {:?}: unclaimed reward withdrawal failed: {:?}",
203					era,
204					kind,
205					e
206				);
207			},
208		}
209	}
210
211	/// Whether the slot backing this era's staker reward pot exists.
212	///
213	/// Because slots are reused across eras (rotating pool), this returns
214	/// `true` for an era as long as *some* era mapping to the same slot
215	/// has created the account.
216	#[cfg(any(test, feature = "try-runtime"))]
217	pub(crate) fn has_staker_rewards_pot(era: EraIndex) -> bool {
218		let pot = T::RewardPots::pot_account(RewardPot::Era(era, RewardKind::StakerRewards));
219		frame_system::Pallet::<T>::providers(&pot) > 0
220	}
221
222	/// Cleans up all pot accounts for a given era by draining their balances.
223	///
224	/// Pot accounts are kept alive for reuse by a future era at the same slot.
225	pub(crate) fn cleanup_era(era: EraIndex) {
226		Self::drain(era, RewardKind::StakerRewards);
227		Self::drain(era, RewardKind::ValidatorSelfStake);
228	}
229}
230
231/// Default implementation of the staker reward calculator.
232///
233/// Commission-based split: validator gets commission + proportional stake share,
234/// nominators get the rest. Incentive weight returns zero (no incentive curve).
235pub struct DefaultStakerRewardCalculator<T>(core::marker::PhantomData<T>);
236
237impl<T: Config> sp_staking::StakerRewardCalculator<BalanceOf<T>>
238	for DefaultStakerRewardCalculator<T>
239where
240	BalanceOf<T>: Into<u128> + From<u128>,
241{
242	fn calculate_validator_incentive_weight(self_stake: BalanceOf<T>) -> BalanceOf<T> {
243		let optimum = OptimumSelfStake::<T>::get();
244		let cap = HardCapSelfStake::<T>::get();
245		let slope_factor = SelfStakeSlopeFactor::<T>::get();
246
247		incentive_weight::<BalanceOf<T>>(self_stake, optimum, cap, slope_factor)
248	}
249
250	fn calculate_staker_reward(
251		validator_total_reward: BalanceOf<T>,
252		validator_commission: Perbill,
253		validator_own_stake: BalanceOf<T>,
254		total_exposure: BalanceOf<T>,
255	) -> sp_staking::StakerRewardResult<BalanceOf<T>> {
256		let validator_commission_payout = validator_commission.mul_floor(validator_total_reward);
257		let leftover = validator_total_reward.saturating_sub(validator_commission_payout);
258		let validator_exposure_part = Perbill::from_rational(validator_own_stake, total_exposure);
259		let validator_staking_payout = validator_exposure_part.mul_floor(leftover);
260		let validator_payout = validator_staking_payout.saturating_add(validator_commission_payout);
261		let nominator_payout = leftover.saturating_sub(validator_staking_payout);
262
263		// Validator and nominator payout is exactly same as total reward.
264		debug_assert_eq!(validator_payout + nominator_payout, validator_total_reward);
265
266		sp_staking::StakerRewardResult { validator_payout, nominator_payout }
267	}
268}
269
270/// Piecewise sqrt-based incentive weight function.
271///
272/// - Below optimum: `w(s) = √s`
273/// - Between optimum and cap: `w(s) = √(T + k² × (s - T))`
274/// - Above cap: plateau at `w(cap)`
275fn incentive_weight<Balance>(
276	self_stake: Balance,
277	optimum: Balance,
278	cap: Balance,
279	slope_factor: Perbill,
280) -> Balance
281where
282	Balance: AtLeast32BitUnsigned + Copy + Into<u128> + From<u128>,
283{
284	debug_assert!(optimum <= cap, "config invariant: optimum must be <= cap");
285
286	if self_stake.is_zero() {
287		return Balance::zero();
288	}
289
290	if optimum.is_zero() && cap.is_zero() {
291		return Balance::zero();
292	}
293
294	let self_stake_u128: u128 = self_stake.into();
295	let optimum_u128: u128 = optimum.into();
296	let cap_u128: u128 = cap.into();
297
298	let weight_u128 = if self_stake <= optimum {
299		sp_arithmetic::helpers_128bit::sqrt(self_stake_u128)
300	} else if self_stake <= cap {
301		let k_squared = slope_factor.square();
302		let excess = self_stake_u128.saturating_sub(optimum_u128);
303		let arg = optimum_u128.saturating_add(k_squared.mul_floor(excess));
304		sp_arithmetic::helpers_128bit::sqrt(arg)
305	} else {
306		let k_squared = slope_factor.square();
307		let excess = cap_u128.saturating_sub(optimum_u128);
308		let arg = optimum_u128.saturating_add(k_squared.mul_floor(excess));
309		sp_arithmetic::helpers_128bit::sqrt(arg)
310	};
311
312	Balance::from(weight_u128)
313}
314
315#[cfg(test)]
316mod tests {
317	use super::*;
318	use sp_runtime::Perbill;
319
320	type Balance = u128;
321
322	#[test]
323	fn incentive_weight_zero_self_stake() {
324		assert_eq!(
325			incentive_weight::<Balance>(0, 100_000, 500_000, Perbill::from_rational(1u32, 2u32)),
326			0
327		);
328	}
329
330	#[test]
331	fn incentive_weight_config_not_set() {
332		// Both optimum and cap are zero (config never set) -> disabled.
333		assert_eq!(
334			incentive_weight::<Balance>(100_000, 0, 0, Perbill::from_rational(1u32, 2u32)),
335			0
336		);
337	}
338
339	#[test]
340	fn incentive_weight_optimum_zero_cap_set() {
341		// optimum = 0, cap > 0: dampened-growth zone from 0 up to cap.
342		let slope = Perbill::from_rational(1u32, 2u32);
343		// self_stake below cap: w(s) = √(0 + 0.25·s) = √(s/4).
344		// s = 400_000 -> √100_000 ≈ 316.
345		assert_eq!(incentive_weight::<Balance>(400_000, 0, 500_000, slope), 316);
346		// Same self-stake with a positive optimum yields higher weight
347		assert_eq!(incentive_weight::<Balance>(400_000, 100_000, 500_000, slope), 418);
348		// Above cap plateaus at √(0.25·cap) = √125_000 ≈ 353.
349		assert_eq!(incentive_weight::<Balance>(1_000_000, 0, 500_000, slope), 353);
350	}
351
352	#[test]
353	fn incentive_weight_below_optimum() {
354		// √10_000 = 100
355		assert_eq!(
356			incentive_weight::<Balance>(
357				10_000,
358				100_000,
359				500_000,
360				Perbill::from_rational(1u32, 2u32)
361			),
362			100
363		);
364	}
365
366	#[test]
367	fn incentive_weight_at_optimum() {
368		// √100_000 ≈ 316
369		assert_eq!(
370			incentive_weight::<Balance>(
371				100_000,
372				100_000,
373				500_000,
374				Perbill::from_rational(1u32, 2u32)
375			),
376			316
377		);
378	}
379
380	#[test]
381	fn incentive_weight_between_optimum_and_cap() {
382		// √(100k + 0.25 × 200k) = √150k ≈ 387
383		assert_eq!(
384			incentive_weight::<Balance>(
385				300_000,
386				100_000,
387				500_000,
388				Perbill::from_rational(1u32, 2u32)
389			),
390			387
391		);
392	}
393
394	#[test]
395	fn incentive_weight_at_cap() {
396		// √(100k + 0.25 × 400k) = √200k ≈ 447
397		assert_eq!(
398			incentive_weight::<Balance>(
399				500_000,
400				100_000,
401				500_000,
402				Perbill::from_rational(1u32, 2u32)
403			),
404			447
405		);
406	}
407
408	#[test]
409	fn incentive_weight_plateau_above_cap() {
410		let at_cap = incentive_weight::<Balance>(
411			500_000,
412			100_000,
413			500_000,
414			Perbill::from_rational(1u32, 2u32),
415		);
416		let above = incentive_weight::<Balance>(
417			1_000_000,
418			100_000,
419			500_000,
420			Perbill::from_rational(1u32, 2u32),
421		);
422		assert_eq!(at_cap, above);
423	}
424
425	#[test]
426	fn incentive_weight_monotonically_increasing_below_cap() {
427		let slope = Perbill::from_rational(1u32, 2u32);
428		let w1 = incentive_weight::<Balance>(50_000, 100_000, 500_000, slope);
429		let w2 = incentive_weight::<Balance>(100_000, 100_000, 500_000, slope);
430		let w3 = incentive_weight::<Balance>(200_000, 100_000, 500_000, slope);
431		let w4 = incentive_weight::<Balance>(400_000, 100_000, 500_000, slope);
432		assert!(w1 < w2 && w2 < w3 && w3 < w4);
433	}
434
435	#[test]
436	fn incentive_weight_different_slope_factors() {
437		let self_stake = 300_000;
438		let w_025 = incentive_weight::<Balance>(
439			self_stake,
440			100_000,
441			500_000,
442			Perbill::from_rational(1u32, 4u32),
443		);
444		let w_050 = incentive_weight::<Balance>(
445			self_stake,
446			100_000,
447			500_000,
448			Perbill::from_rational(1u32, 2u32),
449		);
450		let w_075 = incentive_weight::<Balance>(
451			self_stake,
452			100_000,
453			500_000,
454			Perbill::from_rational(3u32, 4u32),
455		);
456		assert!(w_025 < w_050 && w_050 < w_075);
457	}
458
459	#[test]
460	fn incentive_weight_slope_factor_zero_plateaus_at_optimum() {
461		// k=0 -> immediate plateau at optimum (no growth beyond T).
462		let at_optimum = incentive_weight::<Balance>(100_000, 100_000, 500_000, Perbill::zero());
463		let above_optimum = incentive_weight::<Balance>(300_000, 100_000, 500_000, Perbill::zero());
464		assert_eq!(at_optimum, above_optimum);
465	}
466
467	#[test]
468	fn incentive_weight_slope_factor_one_no_discouragement() {
469		// k=1 -> no discouragement above T (same curve as below T).
470		let at_optimum = incentive_weight::<Balance>(100_000, 100_000, 500_000, Perbill::one());
471		let at_cap = incentive_weight::<Balance>(500_000, 100_000, 500_000, Perbill::one());
472		// sqrt(100_000) = 316, sqrt(500_000) = 707
473		assert_eq!(at_optimum, 316);
474		assert_eq!(at_cap, 707);
475	}
476
477	#[test]
478	fn incentive_weight_optimum_equals_cap() {
479		// When T == C, the middle segment vanishes -- plateau immediately at T.
480		let slope = Perbill::from_rational(1u32, 2u32);
481		let at_boundary = incentive_weight::<Balance>(100_000, 100_000, 100_000, slope);
482		let above = incentive_weight::<Balance>(200_000, 100_000, 100_000, slope);
483		assert_eq!(at_boundary, above);
484		assert_eq!(at_boundary, 316); // sqrt(100_000)
485	}
486}