1use frame_support::{defensive, ensure, traits::Defensive};
35use sp_runtime::DispatchResult;
36use sp_staking::{StakingAccount, StakingInterface};
37
38use crate::{
39 asset, BalanceOf, Bonded, Config, Error, Ledger, Pallet, Payee, RewardDestination,
40 StakingLedger, VirtualStakers,
41};
42
43#[cfg(any(feature = "runtime-benchmarks", test))]
44use sp_runtime::traits::Zero;
45
46impl<T: Config> StakingLedger<T> {
47 #[cfg(any(feature = "runtime-benchmarks", test))]
48 pub fn default_from(stash: T::AccountId) -> Self {
49 Self {
50 stash: stash.clone(),
51 total: Zero::zero(),
52 active: Zero::zero(),
53 unlocking: Default::default(),
54 legacy_claimed_rewards: Default::default(),
55 controller: Some(stash),
56 }
57 }
58
59 pub fn new(stash: T::AccountId, stake: BalanceOf<T>) -> Self {
67 Self {
68 stash: stash.clone(),
69 active: stake,
70 total: stake,
71 unlocking: Default::default(),
72 legacy_claimed_rewards: Default::default(),
73 controller: Some(stash),
75 }
76 }
77
78 pub(crate) fn paired_account(account: StakingAccount<T::AccountId>) -> Option<T::AccountId> {
87 match account {
88 StakingAccount::Stash(stash) => <Bonded<T>>::get(stash),
89 StakingAccount::Controller(controller) =>
90 <Ledger<T>>::get(&controller).map(|ledger| ledger.stash),
91 }
92 }
93
94 pub(crate) fn is_bonded(account: StakingAccount<T::AccountId>) -> bool {
96 match account {
97 StakingAccount::Stash(stash) => <Bonded<T>>::contains_key(stash),
98 StakingAccount::Controller(controller) => <Ledger<T>>::contains_key(controller),
99 }
100 }
101
102 pub(crate) fn get(account: StakingAccount<T::AccountId>) -> Result<StakingLedger<T>, Error<T>> {
111 let (stash, controller) = match account.clone() {
112 StakingAccount::Stash(stash) =>
113 (stash.clone(), <Bonded<T>>::get(&stash).ok_or(Error::<T>::NotStash)?),
114 StakingAccount::Controller(controller) => (
115 Ledger::<T>::get(&controller)
116 .map(|l| l.stash)
117 .ok_or(Error::<T>::NotController)?,
118 controller,
119 ),
120 };
121
122 let ledger = <Ledger<T>>::get(&controller)
123 .map(|mut ledger| {
124 ledger.controller = Some(controller.clone());
125 ledger
126 })
127 .ok_or(Error::<T>::NotController)?;
128
129 ensure!(
135 Bonded::<T>::get(&stash) == Some(controller) && ledger.stash == stash,
136 Error::<T>::BadState
137 );
138
139 Ok(ledger)
140 }
141
142 pub(crate) fn reward_destination(
147 account: StakingAccount<T::AccountId>,
148 ) -> Option<RewardDestination<T::AccountId>> {
149 let stash = match account {
150 StakingAccount::Stash(stash) => Some(stash),
151 StakingAccount::Controller(controller) =>
152 Self::paired_account(StakingAccount::Controller(controller)),
153 };
154
155 if let Some(stash) = stash {
156 <Payee<T>>::get(stash)
157 } else {
158 defensive!("fetched reward destination from unbonded stash {}", stash);
159 None
160 }
161 }
162
163 pub fn controller(&self) -> Option<T::AccountId> {
170 self.controller.clone().or_else(|| {
171 defensive!("fetched a controller on a ledger instance without it.");
172 Self::paired_account(StakingAccount::Stash(self.stash.clone()))
173 })
174 }
175
176 pub(crate) fn update(self) -> Result<(), Error<T>> {
184 if !<Bonded<T>>::contains_key(&self.stash) {
185 return Err(Error::<T>::NotStash)
186 }
187
188 if !Pallet::<T>::is_virtual_staker(&self.stash) {
190 asset::update_stake::<T>(&self.stash, self.total)
192 .map_err(|_| Error::<T>::NotEnoughFunds)?;
193 }
194
195 Ledger::<T>::insert(
196 &self.controller().ok_or_else(|| {
197 defensive!("update called on a ledger that is not bonded.");
198 Error::<T>::NotController
199 })?,
200 &self,
201 );
202
203 Ok(())
204 }
205
206 pub(crate) fn bond(self, payee: RewardDestination<T::AccountId>) -> Result<(), Error<T>> {
210 if <Bonded<T>>::contains_key(&self.stash) {
211 return Err(Error::<T>::AlreadyBonded)
212 }
213
214 <Payee<T>>::insert(&self.stash, payee);
215 <Bonded<T>>::insert(&self.stash, &self.stash);
216 self.update()
217 }
218
219 pub(crate) fn set_payee(self, payee: RewardDestination<T::AccountId>) -> Result<(), Error<T>> {
221 if !<Bonded<T>>::contains_key(&self.stash) {
222 return Err(Error::<T>::NotStash)
223 }
224
225 <Payee<T>>::insert(&self.stash, payee);
226 Ok(())
227 }
228
229 pub(crate) fn set_controller_to_stash(self) -> Result<(), Error<T>> {
231 let controller = self.controller.as_ref()
232 .defensive_proof("Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.")
233 .ok_or(Error::<T>::NotController)?;
234
235 ensure!(self.stash != *controller, Error::<T>::AlreadyPaired);
236
237 if let Some(bonded_ledger) = Ledger::<T>::get(&self.stash) {
239 ensure!(bonded_ledger.stash == self.stash, Error::<T>::BadState);
244 }
245
246 <Ledger<T>>::remove(&controller);
247 <Ledger<T>>::insert(&self.stash, &self);
248 <Bonded<T>>::insert(&self.stash, &self.stash);
249
250 Ok(())
251 }
252
253 pub(crate) fn kill(stash: &T::AccountId) -> DispatchResult {
256 let controller = <Bonded<T>>::get(stash).ok_or(Error::<T>::NotStash)?;
257
258 <Ledger<T>>::get(&controller).ok_or(Error::<T>::NotController).map(|ledger| {
259 Ledger::<T>::remove(controller);
260 <Bonded<T>>::remove(&stash);
261 <Payee<T>>::remove(&stash);
262
263 if <VirtualStakers<T>>::take(&ledger.stash).is_none() {
265 asset::kill_stake::<T>(&ledger.stash)?;
267 }
268
269 Ok(())
270 })?
271 }
272}
273
274#[cfg(test)]
275use {
276 crate::UnlockChunk,
277 codec::{Decode, Encode, MaxEncodedLen},
278 scale_info::TypeInfo,
279};
280
281#[cfg(test)]
284#[derive(frame_support::DebugNoBound, Clone, Encode, Decode, TypeInfo, MaxEncodedLen)]
285pub struct StakingLedgerInspect<T: Config> {
286 pub stash: T::AccountId,
287 #[codec(compact)]
288 pub total: BalanceOf<T>,
289 #[codec(compact)]
290 pub active: BalanceOf<T>,
291 pub unlocking: frame_support::BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
292 pub legacy_claimed_rewards: frame_support::BoundedVec<sp_staking::EraIndex, T::HistoryDepth>,
293}
294
295#[cfg(test)]
296impl<T: Config> PartialEq<StakingLedgerInspect<T>> for StakingLedger<T> {
297 fn eq(&self, other: &StakingLedgerInspect<T>) -> bool {
298 self.stash == other.stash &&
299 self.total == other.total &&
300 self.active == other.active &&
301 self.unlocking == other.unlocking &&
302 self.legacy_claimed_rewards == other.legacy_claimed_rewards
303 }
304}
305
306#[cfg(test)]
307impl<T: Config> codec::EncodeLike<StakingLedger<T>> for StakingLedgerInspect<T> {}