Skip to content

Commit

Permalink
more improvements (wip)
Browse files Browse the repository at this point in the history
  • Loading branch information
gpestana committed May 13, 2024
1 parent 75f06ce commit d68b3ac
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 120 deletions.
18 changes: 14 additions & 4 deletions polkadot/runtime/westend/src/weights/pallet_staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -828,12 +828,22 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
}

fn drop_dangling_nomination() -> Weight {
// todo
Weight::default()
// Proof Size summary in bytes:
// Measured: `1973`
// Estimated: `8631`
// Minimum execution time: 101_638_000 picoseconds.
Weight::from_parts(103_488_000, 8631)
.saturating_add(T::DbWeight::get().reads(14_u64))
.saturating_add(T::DbWeight::get().writes(5_u64))
}

fn v13_mmb_step() -> Weight {
// todo
Weight::default()
// Proof Size summary in bytes:
// Measured: `70141`
// Estimated: `477090`
// Minimum execution time: 2_703_732_000 picoseconds.
Weight::from_parts(2_779_206_000, 477090)
.saturating_add(T::DbWeight::get().reads(231_u64))
.saturating_add(T::DbWeight::get().writes(183_u64))
}
}
67 changes: 41 additions & 26 deletions substrate/frame/staking/src/migrations/v13_stake_tracker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use frame_support::{
migrations::{MigrationId, SteppedMigration, SteppedMigrationError},
traits::Defensive,
};
use pallet_stake_tracker::Config as STConfig;
use pallet_stake_tracker::{Config as STConfig, Pallet as STPallet};
use sp_staking::StakingInterface;
use sp_std::prelude::*;

Expand Down Expand Up @@ -69,25 +69,40 @@ impl<T: Config<CurrencyBalance = u128> + pallet_stake_tracker::Config, W: weight
return Err(SteppedMigrationError::InsufficientWeight { required });
}

log::info!("remaining step weight: {:?}", meter.remaining());

/*
// TODO(remove): configs and state for partial checks.
#[cfg(any(test, feature = "try-runtime"))]
const TRY_STATE_INTERVAL: usize = 15;
#[cfg(any(test, feature = "try-runtime"))]
let mut voters_processed: Vec<T::AccountId> = vec![];
*/

// Do as much progress as possible per step.
while meter.try_consume(required).is_ok() {
// 1. get next validator in the Validators map.
// fetch the next nominator to migrate.
let mut iter = if let Some(ref last_nom) = cursor {
Nominators::<T>::iter_from(Nominators::<T>::hashed_key_for(last_nom))
} else {
// first step, start from beginning of the validator's map.
Nominators::<T>::iter()
};

if let Some((nominator, _)) = iter.next() {
let nominator_stake =
Pallet::<T>::stake(&nominator).defensive_unwrap_or_default().total;
let nominator_stake = STPallet::<T>::vote_of(&nominator);

// TODO: clean up.
let nominations = Nominators::<T>::get(&nominator)
.map(|n| n.targets.into_inner())
.unwrap_or_default();
let original_noms_len = nominations.len();

let nominations = pallet_stake_tracker::Pallet::<T>::ensure_dedup(nominations);
// try to remove dangling and bad targets.
let nominations = Pallet::<T>::do_drop_dangling_nominations(&nominator, None)
.map(|n| n.into_inner())
.unwrap_or(nominations);
// ---

log!(
info,
Expand All @@ -98,6 +113,7 @@ impl<T: Config<CurrencyBalance = u128> + pallet_stake_tracker::Config, W: weight
iter.count()
);

// `Nominators` may have unbonded stashes -- chill them.
if Pallet::<T>::active_stake(&nominator).unwrap_or_default() <
Pallet::<T>::minimum_nominator_bond()
{
Expand All @@ -114,24 +130,10 @@ impl<T: Config<CurrencyBalance = u128> + pallet_stake_tracker::Config, W: weight

// iter over up to `MaxNominationsOf<T>` targets of `nominator`.
for target in nominations.into_iter() {
if Pallet::<T>::status(&target).is_err() {
// drop all dangling nominations for this nominator.
let res = Pallet::<T>::do_drop_dangling_nominations(&nominator, None);
log!(
info,
"mmb: dropped *all* dangling nominations (result with count: {:?})",
res
);

continue
};

log!(info, "mmb: processing {:?} - {:?}", target, Pallet::<T>::status(&target));

if let Ok(current_stake) = <T as STConfig>::TargetList::get_score(&target) {
// target is not in the target list. update with nominator's stake.

if let Some(total_stake) = current_stake.checked_add(nominator_stake) {
// target is in the target list. update with nominator's stake.
if let Some(total_stake) = current_stake.checked_add(nominator_stake.into())
{
let _ = <T as STConfig>::TargetList::on_update(&target, total_stake)
.defensive();
} else {
Expand All @@ -141,17 +143,30 @@ impl<T: Config<CurrencyBalance = u128> + pallet_stake_tracker::Config, W: weight
} else {
// target is not in the target list, insert new node and consider self
// stake.
let self_stake = Pallet::<T>::stake(&target).defensive_unwrap_or_default();
if let Some(total_stake) = self_stake.total.checked_add(nominator_stake) {
let _ = <T as STConfig>::TargetList::on_insert(target, total_stake)
.defensive();
let self_stake = STPallet::<T>::vote_of(&target);
if let Some(total_stake) = self_stake.checked_add(nominator_stake) {
let _ =
<T as STConfig>::TargetList::on_insert(target, total_stake.into())
.defensive();
} else {
log!(error, "target stake overflow. exit.");
return Err(SteppedMigrationError::Failed)
}
}
}

/*
// TODO(remove): performs partial checks.
#[cfg(any(test, feature = "try-runtime"))]
{
voters_processed.push(nominator.clone());
if voters_processed.len() % TRY_STATE_INTERVAL == 0 {
STPallet::<T>::do_try_state_approvals(Some(voters_processed.clone()))
.unwrap();
}
}
*/

// progress cursor.
cursor = Some(nominator)
} else {
Expand Down
24 changes: 10 additions & 14 deletions substrate/frame/staking/src/pallet/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,39 +418,35 @@ impl<T: Config> Pallet<T> {
pub(crate) fn do_drop_dangling_nominations(
nominator: &T::AccountId,
target: Option<&T::AccountId>,
) -> Result<u32, DispatchError> {
let (dropping_count, nominations_after) = match (target, Self::status(&nominator)) {
) -> Result<BoundedVec<T::AccountId, MaxNominationsOf<T>>, DispatchError> {
let nominations_after = match (target, Self::status(&nominator)) {
(None, Ok(StakerStatus::Nominator(nominations))) => {
// target not set, search for all the dangling nominations.
let dangling = nominations
.iter()
.filter(|n| Self::status(n) != Ok(StakerStatus::Validator))
.collect::<Vec<_>>();
let after = nominations

nominations
.iter()
.cloned()
.filter(|n| !dangling.contains(&n))
.collect::<Vec<_>>();

(nominations.len() - after.len(), after)
},
(Some(target), Ok(StakerStatus::Nominator(nominations))) => {
let after = nominations.iter().cloned().filter(|n| n != target).collect::<Vec<_>>();

(nominations.len() - after.len(), after)
.collect::<Vec<_>>()
},
(Some(target), Ok(StakerStatus::Nominator(nominations))) =>
nominations.iter().cloned().filter(|n| n != target).collect::<Vec<_>>(),
// not a nominator, return earlier.
(_, _) => return Err(Error::<T>::NotNominator.into()),
};

// no dangling nominations, return earlier.
if dropping_count.is_zero() {
if nominations_after.len().is_zero() {
return Err(Error::<T>::NotDanglingTarget.into());
}

<Self as StakingInterface>::nominate(nominator, nominations_after)?;
<Self as StakingInterface>::nominate(nominator, nominations_after.clone())?; // TODO remove clone?

Ok(dropping_count as u32)
Ok(BoundedVec::truncate_from(nominations_after))
}

/// Actually make a payment to a staker. This uses the currency's reward function
Expand Down
4 changes: 2 additions & 2 deletions substrate/frame/staking/src/pallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2122,10 +2122,10 @@ pub mod pallet {
);

Self::do_drop_dangling_nominations(&nominator, Some(&target))
.map(|count| {
.map(|nominations| {
Self::deposit_event(Event::<T>::DanglingNominationsDropped {
nominator,
count,
count: 0, // TODO
});

Pays::No.into()
Expand Down
Loading

0 comments on commit d68b3ac

Please sign in to comment.