Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initialize TotalValueUnbonding #2514

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 57 additions & 16 deletions substrate/frame/nomination-pools/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,23 +544,26 @@ impl<T: Config> PoolMember<T> {
fn total_balance(&self) -> BalanceOf<T> {
let pool = BondedPool::<T>::get(self.pool_id).unwrap();
let active_balance = pool.points_to_balance(self.active_points());
let unbonding_balance = self.unbonding_balance();
active_balance + unbonding_balance
}

/// Unbonding balance of the member. Doesn't mutate state.
#[cfg(any(feature = "try-runtime", feature = "fuzzing", test, debug_assertions))]
fn unbonding_balance(&self) -> BalanceOf<T> {
let sub_pools = match SubPoolsStorage::<T>::get(self.pool_id) {
Some(sub_pools) => sub_pools,
None => return active_balance,
None => return BalanceOf::<T>::zero(),
};

let unbonding_balance = self.unbonding_eras.iter().fold(
BalanceOf::<T>::zero(),
|accumulator, (era, unlocked_points)| {
self.unbonding_eras
.iter()
.fold(BalanceOf::<T>::zero(), |acc, (era, unlocking_points)| {
// if the `SubPools::with_era` has already been merged into the
// `SubPools::no_era` use this pool instead.
let era_pool = sub_pools.with_era.get(era).unwrap_or(&sub_pools.no_era);
accumulator + (era_pool.point_to_balance(*unlocked_points))
},
);

active_balance + unbonding_balance
acc + (era_pool.point_to_balance(*unlocking_points))
})
}

/// Total points of this member, both active and unbonding.
Expand Down Expand Up @@ -1256,6 +1259,16 @@ impl<T: Config> BondedPool<T> {
Ok(points_issued)
}

fn try_unbond_funds(&self, amount: BalanceOf<T>) -> Result<(), DispatchError> {
let bonded_account = self.bonded_account();
T::Staking::unbond(&bonded_account, amount)?;
// unbonding `amount` successes
TotalValueUnbonding::<T>::mutate(|tvu| {
tvu.saturating_accrue(amount);
});
Ok(())
}

// Set the state of `self`, and deposit an event if the state changed. State should never be set
// directly in in order to ensure a state change event is always correctly deposited.
fn set_state(&mut self, state: PoolState) {
Expand Down Expand Up @@ -1286,6 +1299,9 @@ impl<T: Config> BondedPool<T> {
TotalValueLocked::<T>::mutate(|tvl| {
tvl.saturating_reduce(diff);
});
TotalValueUnbonding::<T>::mutate(|tvu| {
tvu.saturating_reduce(diff);
});
outcome
}
}
Expand Down Expand Up @@ -1572,7 +1588,7 @@ pub mod pallet {
use sp_runtime::Perbill;

/// The current storage version.
const STORAGE_VERSION: StorageVersion = StorageVersion::new(7);
const STORAGE_VERSION: StorageVersion = StorageVersion::new(8);

#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
Expand Down Expand Up @@ -1658,6 +1674,10 @@ pub mod pallet {
#[pallet::storage]
pub type TotalValueLocked<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;

/// The sum of funds in the process of unbonding across all pools.
#[pallet::storage]
pub type TotalValueUnbonding<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;

/// Minimum amount to bond to join a pool.
#[pallet::storage]
pub type MinJoinBond<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
Expand Down Expand Up @@ -2124,7 +2144,7 @@ pub mod pallet {

// Unbond in the actual underlying nominator.
let unbonding_balance = bonded_pool.dissolve(unbonding_points);
T::Staking::unbond(&bonded_pool.bonded_account(), unbonding_balance)?;
bonded_pool.try_unbond_funds(unbonding_balance)?;

// Note that we lazily create the unbonding pools here if they don't already exist
let mut sub_pools = SubPoolsStorage::<T>::get(member.pool_id)
Expand Down Expand Up @@ -3299,7 +3319,8 @@ impl<T: Config> Pallet<T> {
let mut pools_members = BTreeMap::<PoolId, u32>::new();
let mut pools_members_pending_rewards = BTreeMap::<PoolId, BalanceOf<T>>::new();
let mut all_members = 0u32;
let mut total_balance_members = Default::default();
let mut members_balance_total = Default::default();
let mut members_balance_unbonding = Default::default();
PoolMembers::<T>::iter().try_for_each(|(_, d)| -> Result<(), TryRuntimeError> {
let bonded_pool = BondedPools::<T>::get(d.pool_id).unwrap();
ensure!(!d.total_points().is_zero(), "No member should have zero points");
Expand All @@ -3315,7 +3336,8 @@ impl<T: Config> Pallet<T> {
let pending_rewards = d.pending_rewards(current_rc).unwrap();
*pools_members_pending_rewards.entry(d.pool_id).or_default() += pending_rewards;
} // else this pool has been heavily slashed and cannot have any rewards anymore.
total_balance_members += d.total_balance();
members_balance_total += d.total_balance();
members_balance_unbonding += d.unbonding_balance();

Ok(())
})?;
Expand All @@ -3340,6 +3362,8 @@ impl<T: Config> Pallet<T> {
})?;

let mut expected_tvl: BalanceOf<T> = Default::default();
let mut expected_tvu: BalanceOf<T> = Default::default();

BondedPools::<T>::iter().try_for_each(|(id, inner)| -> Result<(), TryRuntimeError> {
let bonded_pool = BondedPool { id, inner };
ensure!(
Expand All @@ -3361,8 +3385,12 @@ impl<T: Config> Pallet<T> {
pool is being destroyed and the depositor is the last member",
);

expected_tvl +=
T::Staking::total_stake(&bonded_pool.bonded_account()).unwrap_or_default();
let bonded_account = bonded_pool.bonded_account();
let stake_total = T::Staking::total_stake(&bonded_account).unwrap_or_default();
let stake_active = T::Staking::active_stake(&bonded_account).unwrap_or_default();

expected_tvl += stake_total;
expected_tvu += stake_total - stake_active;

Ok(())
})?;
Expand All @@ -3378,10 +3406,20 @@ impl<T: Config> Pallet<T> {
);

ensure!(
TotalValueLocked::<T>::get() <= total_balance_members,
TotalValueLocked::<T>::get() <= members_balance_total,
"TVL must be equal to or less than the total balance of all PoolMembers."
);

ensure!(
TotalValueUnbonding::<T>::get() == expected_tvu,
"TVU must equal the sum of unbonding funds of all pools."
);

ensure!(
TotalValueUnbonding::<T>::get() <= members_balance_unbonding,
"TVU cannot surpass the sum of unbonding funds of members across all pools."
);

if level <= 1 {
return Ok(())
}
Expand Down Expand Up @@ -3529,6 +3567,9 @@ impl<T: Config> sp_staking::OnStakingUpdate<T::AccountId, BalanceOf<T>> for Pall
pool_id,
balance: *slashed_balance,
});
TotalValueUnbonding::<T>::mutate(|tvu| {
tvu.defensive_saturating_reduce(*slashed_balance);
})
}
});
SubPoolsStorage::<T>::insert(pool_id, sub_pools);
Expand Down
74 changes: 74 additions & 0 deletions substrate/frame/nomination-pools/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ use sp_runtime::TryRuntimeError;
pub mod versioned {
use super::*;

/// V7 to V8 migration, wrapped in [`frame_support::migrations::VersionedMigration`] to ensure
/// it is only performed when on-chain version is 7.
pub type V7ToV8<T> = frame_support::migrations::VersionedMigration<
7,
8,
v8::MigrateToV8<T>,
crate::pallet::Pallet<T>,
<T as frame_system::Config>::DbWeight,
>;

/// Migration V6 to V7 wrapped in a [`frame_support::migrations::VersionedMigration`], ensuring
/// the migration is only performed when on-chain version is 6.
pub type V6ToV7<T> = frame_support::migrations::VersionedMigration<
Expand All @@ -47,6 +57,70 @@ pub mod versioned {
>;
}

mod v8 {
use super::*;

pub struct MigrateToV8<T>(sp_std::marker::PhantomData<T>);

impl<T: Config> MigrateToV8<T> {
fn calculate_tvu() -> BalanceOf<T> {
BondedPools::<T>::iter()
.map(|(id, inner)| {
let bonded_account = BondedPool { id, inner: inner.clone() }.bonded_account();
let total_stake = T::Staking::total_stake(&bonded_account).unwrap_or_default();
let active_stake =
T::Staking::active_stake(&bonded_account).unwrap_or_default();
total_stake - active_stake
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should use safe math here I think

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

active_stake <= total_stake && active_stake >= 0 should always hold right? If that's the contract, I would rather let the migration fail than carry on with the wrong states in this case.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It wouldn't fail, it would silently underflow :P

})
.reduce(|acc, balance| acc + balance)
.unwrap_or_default()
}
}

impl<T: Config> OnRuntimeUpgrade for MigrateToV8<T> {
fn on_runtime_upgrade() -> Weight {
let pool_count = BondedPools::<T>::count();

// the sum of all funds that are in the unbonding process of each pool
let tvu = Self::calculate_tvu();
TotalValueUnbonding::<T>::set(tvu);

log!(info, "Migrating {} pools with TotalValueUnbonding of {:?}", pool_count, tvu);

// reads: pool_count * (BondedPool + total_stake + active_stake)
// + pool_count + storage_version
// writes: new storage_version + TotalValueUnbonding
T::DbWeight::get()
.reads_writes(pool_count.saturating_mul(3).saturating_add(2).into(), 2)
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(_data: Vec<u8>) -> Result<(), TryRuntimeError> {
ensure!(
Pallet::<T>::on_chain_storage_version() >= 8,
"nomination-pools::migration::v8: storage version must be no less than 8",
);

ensure!(
TotalValueUnbonding::<T>::get() == Self::calculate_tvu(),
"TotalValueUnbonding must equal the sum of unbonding balance of all pools.",
);

let members_balance_unbonding = PoolMembers::<T>::iter()
.map(|(_, member)| member.unbonding_balance())
.reduce(|acc, balance| acc + balance)
.unwrap_or_default();

ensure!(
TotalValueUnbonding::<T>::get() <= members_balance_unbonding,
"TotalValueUnbonding cannot surpass the sum of unbonding funds of members across all pools.",
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why's this <= not ==?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH, I'm not sure. :)) I'm just following the pattern above: TotalValueLocked <= members_balance_total


Ok(())
}
}
}

/// This migration accumulates and initializes the [`TotalValueLocked`] for all pools.
///
/// WARNING: This migration works under the assumption that the [`BondedPools`] cannot be inflated
Expand Down
Loading