1use 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#[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
63pub struct EraRewardManager<T: Config>(core::marker::PhantomData<T>);
65
66impl<T: Config> EraRewardManager<T> {
67 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 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 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 pub(crate) fn drain(era: EraIndex, kind: RewardKind) {
162 let pot_account = T::RewardPots::pot_account(RewardPot::Era(era, kind));
163
164 if frame_system::Pallet::<T>::providers(&pot_account) == 0 {
166 return;
167 }
168
169 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 #[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 pub(crate) fn cleanup_era(era: EraIndex) {
226 Self::drain(era, RewardKind::StakerRewards);
227 Self::drain(era, RewardKind::ValidatorSelfStake);
228 }
229}
230
231pub 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 debug_assert_eq!(validator_payout + nominator_payout, validator_total_reward);
265
266 sp_staking::StakerRewardResult { validator_payout, nominator_payout }
267 }
268}
269
270fn 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 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 let slope = Perbill::from_rational(1u32, 2u32);
343 assert_eq!(incentive_weight::<Balance>(400_000, 0, 500_000, slope), 316);
346 assert_eq!(incentive_weight::<Balance>(400_000, 100_000, 500_000, slope), 418);
348 assert_eq!(incentive_weight::<Balance>(1_000_000, 0, 500_000, slope), 353);
350 }
351
352 #[test]
353 fn incentive_weight_below_optimum() {
354 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 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 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 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 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 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 assert_eq!(at_optimum, 316);
474 assert_eq!(at_cap, 707);
475 }
476
477 #[test]
478 fn incentive_weight_optimum_equals_cap() {
479 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); }
486}