1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use frame_support::{traits::ConstU32, WeakBoundedVec};
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Zero},
RuntimeDebug,
};
use sp_std::prelude::*;
#[derive(Clone, Default, PartialEq, Eq, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct StakingLock<Balance, Moment> {
pub staking_amount: Balance,
pub unbondings: WeakBoundedVec<Unbonding<Balance, Moment>, ConstU32<32>>,
}
impl<Balance, Moment> StakingLock<Balance, Moment>
where
Balance: Copy + PartialOrd + AtLeast32BitUnsigned + Zero,
Moment: Copy + PartialOrd,
{
#[inline]
pub fn total_unbond_at(&self, at: Moment) -> Balance {
self.unbondings
.iter()
.fold(Zero::zero(), |acc, unbonding| acc.saturating_add(unbonding.locked_amount(at)))
}
#[inline]
#[deprecated = "If you know what you are doing now."]
pub fn total_unbond(&self) -> Balance {
self.unbondings
.iter()
.fold(Zero::zero(), |acc, unbonding| acc.saturating_add(unbonding.amount))
}
#[inline]
pub fn refresh(&mut self, at: Moment) {
self.unbondings.retain(|unbonding| unbonding.valid_at(at));
}
}
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct Unbonding<Balance, Moment> {
pub amount: Balance,
pub until: Moment,
}
impl<Balance, Moment> Unbonding<Balance, Moment>
where
Balance: Copy + PartialOrd + Zero,
Moment: PartialOrd,
{
#[inline]
fn valid_at(&self, at: Moment) -> bool {
self.until > at
}
#[inline]
pub fn locked_amount(&self, at: Moment) -> Balance {
if self.valid_at(at) {
self.amount
} else {
Zero::zero()
}
}
}