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

Optimize compute_top_candidates #2123

Merged
merged 4 commits into from
Mar 14, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
54 changes: 40 additions & 14 deletions pallets/parachain-staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1716,22 +1716,48 @@ pub mod pallet {
}

/// Compute the top `TotalSelected` candidates in the CandidatePool and return
/// a vec of their AccountIds (in the order of selection)
/// a vec of their AccountIds (sorted by AccountId)
pub fn compute_top_candidates() -> Vec<T::AccountId> {
let mut candidates = <CandidatePool<T>>::get().0;
// order candidates by stake (least to greatest so requires `rev()`)
candidates.sort_by(|a, b| a.amount.cmp(&b.amount));
let top_n = <TotalSelected<T>>::get() as usize;
// choose the top TotalSelected qualified candidates, ordered by stake
let mut collators = candidates
.into_iter()
.rev()
.take(top_n)
.filter(|x| x.amount >= T::MinCollatorStk::get())
.map(|x| x.owner)
.collect::<Vec<T::AccountId>>();
collators.sort();
collators
if top_n == 0 {
return vec![];
}

let candidates = <CandidatePool<T>>::get().0;

// If the number of candidates is greater than top_n, select the candidates with higher
// amount. Otherwise, return all the candidates.
if candidates.len() > top_n {
// Append candidate index to each candidate, this allows us to use
// select_nth_unstable in a stable way.
let mut candidates: Vec<_> = candidates
.into_iter()
.enumerate()
.map(|(i, x)| (Reverse(x.amount), Reverse(i), x.owner))
.collect();
// Partially sort candidates such that element at index `top_n - 1` is sorted, and
// all the elements in the range 0..top_n are the top n elements.
candidates.select_nth_unstable(top_n - 1);

let mut collators = candidates
.into_iter()
.take(top_n)
.filter(|(amount, _i, _owner)| amount.0 >= T::MinCollatorStk::get())
.map(|(_amount, _i, owner)| owner)
.collect::<Vec<T::AccountId>>();
// Sort collators by AccountId
collators.sort();

collators
} else {
// Return all candidates
// The candidates are already sorted by AccountId, so no need to sort again
candidates
.into_iter()
.filter(|x| x.amount >= T::MinCollatorStk::get())
.map(|x| x.owner)
.collect::<Vec<T::AccountId>>()
}
}
/// Best as in most cumulatively supported in terms of stake
/// Returns [collator_count, delegation_count, total staked]
Expand Down
18 changes: 18 additions & 0 deletions pallets/parachain-staking/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9023,3 +9023,21 @@ fn test_on_initialize_weights() {
assert_eq!(expected_on_init, expected_weight); // magic number == independent accounting
});
}

#[test]
fn test_compute_top_candidates_is_stable() {
ExtBuilder::default()
.with_balances(vec![(1, 30), (2, 30), (3, 30), (4, 30), (5, 30), (6, 30)])
.with_candidates(vec![(1, 30), (2, 30), (3, 30), (4, 30), (5, 30), (6, 30)])
.build()
.execute_with(|| {
// There are 6 candidates with equal amount, but only 5 can be selected
assert_eq!(ParachainStaking::candidate_pool().0.len(), 6);
assert_eq!(ParachainStaking::total_selected(), 5);
// Returns the 5 candidates with greater AccountId, because they are iterated in reverse
assert_eq!(
ParachainStaking::compute_top_candidates(),
vec![2, 3, 4, 5, 6]
);
});
}