Skip to content

Commit 8cbda80

Browse files
kianenigmaemostov
andauthored
Incorporate the new electing/electable naming into the code (paritytech#10956)
* Incorporate the new electing/electable naming into the code * Update frame/election-provider-support/src/lib.rs Co-authored-by: Zeke Mostov <z.mostov@gmail.com> * Update frame/election-provider-support/src/lib.rs Co-authored-by: Zeke Mostov <z.mostov@gmail.com> * Some additional changes * fmt * update codec * revert lock file to master * fix doc test Co-authored-by: Zeke Mostov <z.mostov@gmail.com>
1 parent 4c9bf00 commit 8cbda80

File tree

9 files changed

+82
-70
lines changed

9 files changed

+82
-70
lines changed

bin/node/runtime/src/lib.rs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,12 @@ use frame_system::{
4646
pub use node_primitives::{AccountId, Signature};
4747
use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Index, Moment};
4848
use pallet_contracts::weights::WeightInfo;
49+
use pallet_election_provider_multi_phase::SolutionAccuracyOf;
4950
use pallet_grandpa::{
5051
fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList,
5152
};
5253
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
53-
use pallet_session::historical as pallet_session_historical;
54+
use pallet_session::historical::{self as pallet_session_historical};
5455
pub use pallet_transaction_payment::{CurrencyAdapter, Multiplier, TargetedFeeAdjustment};
5556
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
5657
use sp_api::impl_runtime_apis;
@@ -668,20 +669,17 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
668669
type DataProvider = Staking;
669670
type Solution = NposSolution16;
670671
type Fallback = pallet_election_provider_multi_phase::NoFallback<Self>;
671-
type GovernanceFallback =
672-
frame_election_provider_support::onchain::OnChainSequentialPhragmen<Self>;
672+
type GovernanceFallback = onchain::OnChainSequentialPhragmen<Self>;
673673
type Solver = frame_election_provider_support::SequentialPhragmen<
674674
AccountId,
675-
pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
675+
SolutionAccuracyOf<Self>,
676676
OffchainRandomBalancing,
677677
>;
678-
type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight<Self>;
679678
type ForceOrigin = EnsureRootOrHalfCouncil;
679+
type MaxElectableTargets = ConstU16<{ u16::MAX }>;
680+
type MaxElectingVoters = ConstU32<10_000>;
680681
type BenchmarkingConfig = ElectionProviderBenchmarkConfig;
681-
// BagsList allows a practically unbounded count of nominators to participate in NPoS elections.
682-
// To ensure we respect memory limits when using the BagsList this must be set to a number of
683-
// voters we know can fit into a single vec allocation.
684-
type VoterSnapshotPerBlock = ConstU32<10_000>;
682+
type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight<Self>;
685683
}
686684

687685
parameter_types! {

frame/bags-list/remote-tests/src/snapshot.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,8 @@ pub async fn execute<Runtime: crate::RuntimeT, Block: BlockT + DeserializeOwned>
5656
);
5757

5858
let voters =
59-
<pallet_staking::Pallet<Runtime> as ElectionDataProvider>::voters(voter_limit).unwrap();
59+
<pallet_staking::Pallet<Runtime> as ElectionDataProvider>::electing_voters(voter_limit)
60+
.unwrap();
6061

6162
let mut voters_nominator_only = voters
6263
.iter()

frame/election-provider-multi-phase/src/benchmarking.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,8 @@ frame_benchmarking::benchmarks! {
260260

261261
// we don't directly need the data-provider to be populated, but it is just easy to use it.
262262
set_up_data_provider::<T>(v, t);
263-
let targets = T::DataProvider::targets(None)?;
264-
let voters = T::DataProvider::voters(None)?;
263+
let targets = T::DataProvider::electable_targets(None)?;
264+
let voters = T::DataProvider::electing_voters(None)?;
265265
let desired_targets = T::DataProvider::desired_targets()?;
266266
assert!(<MultiPhase<T>>::snapshot().is_none());
267267
}: {

frame/election-provider-multi-phase/src/lib.rs

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
//! Upon the end of the signed phase, the solutions are examined from best to worse (i.e. `pop()`ed
7070
//! until drained). Each solution undergoes an expensive `Pallet::feasibility_check`, which ensures
7171
//! the score claimed by this score was correct, and it is valid based on the election data (i.e.
72-
//! votes and candidates). At each step, if the current best solution passes the feasibility check,
72+
//! votes and targets). At each step, if the current best solution passes the feasibility check,
7373
//! it is considered to be the best one. The sender of the origin is rewarded, and the rest of the
7474
//! queued solutions get their deposit back and are discarded, without being checked.
7575
//!
@@ -249,7 +249,6 @@ use sp_npos_elections::{
249249
assignment_ratio_to_staked_normalized, ElectionScore, EvaluateSupport, Supports, VoteWeight,
250250
};
251251
use sp_runtime::{
252-
traits::Bounded,
253252
transaction_validity::{
254253
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
255254
TransactionValidityError, ValidTransaction,
@@ -643,14 +642,15 @@ pub mod pallet {
643642
#[pallet::constant]
644643
type SignedDepositWeight: Get<BalanceOf<Self>>;
645644

646-
/// The maximum number of voters to put in the snapshot. At the moment, snapshots are only
647-
/// over a single block, but once multi-block elections are introduced they will take place
648-
/// over multiple blocks.
649-
///
650-
/// Also, note the data type: If the voters are represented by a `u32` in `type
651-
/// CompactSolution`, the same `u32` is used here to ensure bounds are respected.
645+
/// The maximum number of electing voters to put in the snapshot. At the moment, snapshots
646+
/// are only over a single block, but once multi-block elections are introduced they will
647+
/// take place over multiple blocks.
648+
#[pallet::constant]
649+
type MaxElectingVoters: Get<SolutionVoterIndexOf<Self>>;
650+
651+
/// The maximum number of electable targets to put in the snapshot.
652652
#[pallet::constant]
653-
type VoterSnapshotPerBlock: Get<SolutionVoterIndexOf<Self>>;
653+
type MaxElectableTargets: Get<SolutionTargetIndexOf<Self>>;
654654

655655
/// Handler for the slashed deposits.
656656
type SlashHandler: OnUnbalanced<NegativeImbalanceOf<Self>>;
@@ -817,7 +817,7 @@ pub mod pallet {
817817
fn integrity_test() {
818818
use sp_std::mem::size_of;
819819
// The index type of both voters and targets need to be smaller than that of usize (very
820-
// unlikely to be the case, but anyhow).
820+
// unlikely to be the case, but anyhow)..
821821
assert!(size_of::<SolutionVoterIndexOf<T>>() <= size_of::<usize>());
822822
assert!(size_of::<SolutionTargetIndexOf<T>>() <= size_of::<usize>());
823823

@@ -1338,14 +1338,13 @@ impl<T: Config> Pallet<T> {
13381338
/// Extracted for easier weight calculation.
13391339
fn create_snapshot_external(
13401340
) -> Result<(Vec<T::AccountId>, Vec<VoterOf<T>>, u32), ElectionError<T>> {
1341-
let target_limit = <SolutionTargetIndexOf<T>>::max_value().saturated_into::<usize>();
1342-
// for now we have just a single block snapshot.
1343-
let voter_limit = T::VoterSnapshotPerBlock::get().saturated_into::<usize>();
1344-
1345-
let targets =
1346-
T::DataProvider::targets(Some(target_limit)).map_err(ElectionError::DataProvider)?;
1347-
let voters =
1348-
T::DataProvider::voters(Some(voter_limit)).map_err(ElectionError::DataProvider)?;
1341+
let target_limit = T::MaxElectableTargets::get().saturated_into::<usize>();
1342+
let voter_limit = T::MaxElectingVoters::get().saturated_into::<usize>();
1343+
1344+
let targets = T::DataProvider::electable_targets(Some(target_limit))
1345+
.map_err(ElectionError::DataProvider)?;
1346+
let voters = T::DataProvider::electing_voters(Some(voter_limit))
1347+
.map_err(ElectionError::DataProvider)?;
13491348
let mut desired_targets =
13501349
T::DataProvider::desired_targets().map_err(ElectionError::DataProvider)?;
13511350

@@ -2090,7 +2089,7 @@ mod tests {
20902089
// we have 8 voters in total.
20912090
assert_eq!(crate::mock::Voters::get().len(), 8);
20922091
// but we want to take 2.
2093-
crate::mock::VoterSnapshotPerBlock::set(2);
2092+
crate::mock::MaxElectingVoters::set(2);
20942093

20952094
// Signed phase opens just fine.
20962095
roll_to(15);

frame/election-provider-multi-phase/src/mock.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,8 @@ parameter_types! {
263263
pub static MinerMaxWeight: Weight = BlockWeights::get().max_block;
264264
pub static MinerMaxLength: u32 = 256;
265265
pub static MockWeightInfo: bool = false;
266-
pub static VoterSnapshotPerBlock: VoterIndex = u32::max_value();
266+
pub static MaxElectingVoters: VoterIndex = u32::max_value();
267+
pub static MaxElectableTargets: TargetIndex = TargetIndex::max_value();
267268

268269
pub static EpochLength: u64 = 30;
269270
pub static OnChianFallback: bool = true;
@@ -413,7 +414,8 @@ impl crate::Config for Runtime {
413414
type GovernanceFallback = NoFallback<Self>;
414415
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
415416
type Solution = TestNposSolution;
416-
type VoterSnapshotPerBlock = VoterSnapshotPerBlock;
417+
type MaxElectingVoters = MaxElectingVoters;
418+
type MaxElectableTargets = MaxElectableTargets;
417419
type Solver = SequentialPhragmen<AccountId, SolutionAccuracyOf<Runtime>, Balancing>;
418420
}
419421

@@ -439,7 +441,8 @@ impl ElectionDataProvider for StakingMock {
439441
type AccountId = AccountId;
440442
type BlockNumber = u64;
441443
type MaxVotesPerVoter = MaxNominations;
442-
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
444+
445+
fn electable_targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
443446
let targets = Targets::get();
444447

445448
if maybe_max_len.map_or(false, |max_len| targets.len() > max_len) {
@@ -449,7 +452,9 @@ impl ElectionDataProvider for StakingMock {
449452
Ok(targets)
450453
}
451454

452-
fn voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Runtime>>> {
455+
fn electing_voters(
456+
maybe_max_len: Option<usize>,
457+
) -> data_provider::Result<Vec<VoterOf<Runtime>>> {
453458
let mut voters = Voters::get();
454459
if let Some(max_len) = maybe_max_len {
455460
voters.truncate(max_len)

frame/election-provider-support/src/lib.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,12 @@
107107
//! fn desired_targets() -> data_provider::Result<u32> {
108108
//! Ok(1)
109109
//! }
110-
//! fn voters(maybe_max_len: Option<usize>)
110+
//! fn electing_voters(maybe_max_len: Option<usize>)
111111
//! -> data_provider::Result<Vec<VoterOf<Self>>>
112112
//! {
113113
//! Ok(Default::default())
114114
//! }
115-
//! fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
115+
//! fn electable_targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
116116
//! Ok(vec![10, 20, 30])
117117
//! }
118118
//! fn next_election_prediction(now: BlockNumber) -> BlockNumber {
@@ -138,7 +138,7 @@
138138
//! type DataProvider = T::DataProvider;
139139
//!
140140
//! fn elect() -> Result<Supports<AccountId>, Self::Error> {
141-
//! Self::DataProvider::targets(None)
141+
//! Self::DataProvider::electable_targets(None)
142142
//! .map_err(|_| "failed to elect")
143143
//! .map(|t| vec![(t[0], Support::default())])
144144
//! }
@@ -265,16 +265,19 @@ pub trait ElectionDataProvider {
265265
/// Maximum number of votes per voter that this data provider is providing.
266266
type MaxVotesPerVoter: Get<u32>;
267267

268-
/// All possible targets for the election, i.e. the candidates.
268+
/// All possible targets for the election, i.e. the targets that could become elected, thus
269+
/// "electable".
269270
///
270271
/// If `maybe_max_len` is `Some(v)` then the resulting vector MUST NOT be longer than `v` items
271272
/// long.
272273
///
273274
/// This should be implemented as a self-weighing function. The implementor should register its
274275
/// appropriate weight at the end of execution with the system pallet directly.
275-
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<Self::AccountId>>;
276+
fn electable_targets(
277+
maybe_max_len: Option<usize>,
278+
) -> data_provider::Result<Vec<Self::AccountId>>;
276279

277-
/// All possible voters for the election.
280+
/// All the voters that participate in the election, thus "electing".
278281
///
279282
/// Note that if a notion of self-vote exists, it should be represented here.
280283
///
@@ -283,7 +286,7 @@ pub trait ElectionDataProvider {
283286
///
284287
/// This should be implemented as a self-weighing function. The implementor should register its
285288
/// appropriate weight at the end of execution with the system pallet directly.
286-
fn voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>>;
289+
fn electing_voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>>;
287290

288291
/// The number of targets to elect.
289292
///

frame/election-provider-support/src/onchain.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,11 @@ impl<T: Config> OnChainSequentialPhragmen<T> {
7979
maybe_max_voters: Option<usize>,
8080
maybe_max_targets: Option<usize>,
8181
) -> Result<Supports<T::AccountId>, Error> {
82-
let voters = <Self as ElectionProvider>::DataProvider::voters(maybe_max_voters)
83-
.map_err(Error::DataProvider)?;
84-
let targets = <Self as ElectionProvider>::DataProvider::targets(maybe_max_targets)
82+
let voters = <Self as ElectionProvider>::DataProvider::electing_voters(maybe_max_voters)
8583
.map_err(Error::DataProvider)?;
84+
let targets =
85+
<Self as ElectionProvider>::DataProvider::electable_targets(maybe_max_targets)
86+
.map_err(Error::DataProvider)?;
8687
let desired_targets = <Self as ElectionProvider>::DataProvider::desired_targets()
8788
.map_err(Error::DataProvider)?;
8889

@@ -197,15 +198,15 @@ mod tests {
197198
type AccountId = AccountId;
198199
type BlockNumber = BlockNumber;
199200
type MaxVotesPerVoter = ConstU32<2>;
200-
fn voters(_: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>> {
201+
fn electing_voters(_: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>> {
201202
Ok(vec![
202203
(1, 10, bounded_vec![10, 20]),
203204
(2, 20, bounded_vec![30, 20]),
204205
(3, 30, bounded_vec![10, 30]),
205206
])
206207
}
207208

208-
fn targets(_: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
209+
fn electable_targets(_: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
209210
Ok(vec![10, 20, 30])
210211
}
211212

frame/staking/src/pallet/impls.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -860,15 +860,15 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
860860
Ok(Self::validator_count())
861861
}
862862

863-
fn voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>> {
863+
fn electing_voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>> {
864864
// This can never fail -- if `maybe_max_len` is `Some(_)` we handle it.
865865
let voters = Self::get_npos_voters(maybe_max_len);
866866
debug_assert!(maybe_max_len.map_or(true, |max| voters.len() <= max));
867867

868868
Ok(voters)
869869
}
870870

871-
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<T::AccountId>> {
871+
fn electable_targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<T::AccountId>> {
872872
let target_count = Validators::<T>::count();
873873

874874
// We can't handle this case yet -- return an error.

0 commit comments

Comments
 (0)