use frame_support::{defensive, ensure, traits::Defensive};
use sp_runtime::DispatchResult;
use sp_staking::{StakingAccount, StakingInterface};
use crate::{
asset, BalanceOf, Bonded, Config, Error, Ledger, Pallet, Payee, RewardDestination,
StakingLedger, VirtualStakers,
};
#[cfg(any(feature = "runtime-benchmarks", test))]
use sp_runtime::traits::Zero;
impl<T: Config> StakingLedger<T> {
#[cfg(any(feature = "runtime-benchmarks", test))]
pub fn default_from(stash: T::AccountId) -> Self {
Self {
stash: stash.clone(),
total: Zero::zero(),
active: Zero::zero(),
unlocking: Default::default(),
legacy_claimed_rewards: Default::default(),
controller: Some(stash),
}
}
pub fn new(stash: T::AccountId, stake: BalanceOf<T>) -> Self {
Self {
stash: stash.clone(),
active: stake,
total: stake,
unlocking: Default::default(),
legacy_claimed_rewards: Default::default(),
controller: Some(stash),
}
}
pub(crate) fn paired_account(account: StakingAccount<T::AccountId>) -> Option<T::AccountId> {
match account {
StakingAccount::Stash(stash) => <Bonded<T>>::get(stash),
StakingAccount::Controller(controller) => {
<Ledger<T>>::get(&controller).map(|ledger| ledger.stash)
},
}
}
pub(crate) fn is_bonded(account: StakingAccount<T::AccountId>) -> bool {
match account {
StakingAccount::Stash(stash) => <Bonded<T>>::contains_key(stash),
StakingAccount::Controller(controller) => <Ledger<T>>::contains_key(controller),
}
}
pub(crate) fn get(account: StakingAccount<T::AccountId>) -> Result<StakingLedger<T>, Error<T>> {
let (stash, controller) = match account.clone() {
StakingAccount::Stash(stash) => {
(stash.clone(), <Bonded<T>>::get(&stash).ok_or(Error::<T>::NotStash)?)
},
StakingAccount::Controller(controller) => (
Ledger::<T>::get(&controller)
.map(|l| l.stash)
.ok_or(Error::<T>::NotController)?,
controller,
),
};
let ledger = <Ledger<T>>::get(&controller)
.map(|mut ledger| {
ledger.controller = Some(controller.clone());
ledger
})
.ok_or(Error::<T>::NotController)?;
ensure!(
Bonded::<T>::get(&stash) == Some(controller) && ledger.stash == stash,
Error::<T>::BadState
);
Ok(ledger)
}
pub(crate) fn reward_destination(
account: StakingAccount<T::AccountId>,
) -> Option<RewardDestination<T::AccountId>> {
let stash = match account {
StakingAccount::Stash(stash) => Some(stash),
StakingAccount::Controller(controller) => {
Self::paired_account(StakingAccount::Controller(controller))
},
};
if let Some(stash) = stash {
<Payee<T>>::get(stash)
} else {
defensive!("fetched reward destination from unbonded stash {}", stash);
None
}
}
pub fn controller(&self) -> Option<T::AccountId> {
self.controller.clone().or_else(|| {
defensive!("fetched a controller on a ledger instance without it.");
Self::paired_account(StakingAccount::Stash(self.stash.clone()))
})
}
pub(crate) fn update(self) -> Result<(), Error<T>> {
if !<Bonded<T>>::contains_key(&self.stash) {
return Err(Error::<T>::NotStash);
}
if !Pallet::<T>::is_virtual_staker(&self.stash) {
asset::update_stake::<T>(&self.stash, self.total)
.map_err(|_| Error::<T>::NotEnoughFunds)?;
}
Ledger::<T>::insert(
&self.controller().ok_or_else(|| {
defensive!("update called on a ledger that is not bonded.");
Error::<T>::NotController
})?,
&self,
);
Ok(())
}
pub(crate) fn bond(self, payee: RewardDestination<T::AccountId>) -> Result<(), Error<T>> {
if <Bonded<T>>::contains_key(&self.stash) {
return Err(Error::<T>::AlreadyBonded);
}
<Payee<T>>::insert(&self.stash, payee);
<Bonded<T>>::insert(&self.stash, &self.stash);
self.update()
}
pub(crate) fn set_payee(self, payee: RewardDestination<T::AccountId>) -> Result<(), Error<T>> {
if !<Bonded<T>>::contains_key(&self.stash) {
return Err(Error::<T>::NotStash);
}
<Payee<T>>::insert(&self.stash, payee);
Ok(())
}
pub(crate) fn set_controller_to_stash(self) -> Result<(), Error<T>> {
let controller = self.controller.as_ref()
.defensive_proof("Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.")
.ok_or(Error::<T>::NotController)?;
ensure!(self.stash != *controller, Error::<T>::AlreadyPaired);
if let Some(bonded_ledger) = Ledger::<T>::get(&self.stash) {
ensure!(bonded_ledger.stash == self.stash, Error::<T>::BadState);
}
<Ledger<T>>::remove(&controller);
<Ledger<T>>::insert(&self.stash, &self);
<Bonded<T>>::insert(&self.stash, &self.stash);
Ok(())
}
pub(crate) fn kill(stash: &T::AccountId) -> DispatchResult {
let controller = <Bonded<T>>::get(stash).ok_or(Error::<T>::NotStash)?;
<Ledger<T>>::get(&controller).ok_or(Error::<T>::NotController).map(|ledger| {
Ledger::<T>::remove(controller);
<Bonded<T>>::remove(&stash);
<Payee<T>>::remove(&stash);
if <VirtualStakers<T>>::take(&ledger.stash).is_none() {
asset::kill_stake::<T>(&ledger.stash)?;
}
Ok(())
})?
}
}
#[cfg(test)]
use {
crate::UnlockChunk,
codec::{Decode, Encode, MaxEncodedLen},
scale_info::TypeInfo,
};
#[cfg(test)]
#[derive(frame_support::DebugNoBound, Clone, Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct StakingLedgerInspect<T: Config> {
pub stash: T::AccountId,
#[codec(compact)]
pub total: BalanceOf<T>,
#[codec(compact)]
pub active: BalanceOf<T>,
pub unlocking: frame_support::BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
pub legacy_claimed_rewards: frame_support::BoundedVec<sp_staking::EraIndex, T::HistoryDepth>,
}
#[cfg(test)]
impl<T: Config> PartialEq<StakingLedgerInspect<T>> for StakingLedger<T> {
fn eq(&self, other: &StakingLedgerInspect<T>) -> bool {
self.stash == other.stash &&
self.total == other.total &&
self.active == other.active &&
self.unlocking == other.unlocking &&
self.legacy_claimed_rewards == other.legacy_claimed_rewards
}
}
#[cfg(test)]
impl<T: Config> codec::EncodeLike<StakingLedger<T>> for StakingLedgerInspect<T> {}