Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 7f68a8b

Browse files
authored
move generics of election trait to associated types (#10475)
* move generics of election trait to associated types * fix doctest
1 parent 4db2f22 commit 7f68a8b

File tree

9 files changed

+101
-54
lines changed

9 files changed

+101
-54
lines changed

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

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,8 @@ pub async fn execute<Runtime: crate::RuntimeT, Block: BlockT + DeserializeOwned>
5555
<Runtime as pallet_staking::Config>::SortedListProvider::count(),
5656
);
5757

58-
let voters = <pallet_staking::Pallet<Runtime> as ElectionDataProvider<
59-
Runtime::AccountId,
60-
Runtime::BlockNumber,
61-
>>::voters(voter_limit)
62-
.unwrap();
58+
let voters =
59+
<pallet_staking::Pallet<Runtime> as ElectionDataProvider>::voters(voter_limit).unwrap();
6360

6461
let mut voters_nominator_only = voters
6562
.iter()

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ frame_benchmarking::benchmarks! {
289289
assert!(<Snapshot<T>>::get().is_some());
290290
assert!(<SnapshotMetadata<T>>::get().is_some());
291291
}: {
292-
assert_ok!(<MultiPhase<T> as ElectionProvider<T::AccountId, T::BlockNumber>>::elect());
292+
assert_ok!(<MultiPhase<T> as ElectionProvider>::elect());
293293
} verify {
294294
assert!(<MultiPhase<T>>::queued_solution().is_none());
295295
assert!(<DesiredTargets<T>>::get().is_none());

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

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@
139139
//! To generate an emergency solution, one must only provide one argument: [`Supports`]. This is
140140
//! essentially a collection of elected winners for the election, and voters who support them. The
141141
//! supports can be generated by any means. In the simplest case, it could be manual. For example,
142-
//! in the case of massive network failure or misbehaviour, [`Config::ForceOrigin`] might decide to
142+
//! in the case of massive network failure or misbehavior, [`Config::ForceOrigin`] might decide to
143143
//! select only a small number of emergency winners (which would greatly restrict the next validator
144144
//! set, if this pallet is used with `pallet-staking`). If the failure is for other technical
145145
//! reasons, then a simple and safe way to generate supports is using the staking-miner binary
@@ -286,10 +286,7 @@ pub type SolutionTargetIndexOf<T> = <SolutionOf<T> as NposSolution>::TargetIndex
286286
/// The accuracy of the election, when submitted from offchain. Derived from [`SolutionOf`].
287287
pub type SolutionAccuracyOf<T> = <SolutionOf<T> as NposSolution>::Accuracy;
288288
/// The fallback election type.
289-
pub type FallbackErrorOf<T> = <<T as crate::Config>::Fallback as ElectionProvider<
290-
<T as frame_system::Config>::AccountId,
291-
<T as frame_system::Config>::BlockNumber,
292-
>>::Error;
289+
pub type FallbackErrorOf<T> = <<T as crate::Config>::Fallback as ElectionProvider>::Error;
293290

294291
/// Configuration for the benchmarks of the pallet.
295292
pub trait BenchmarkingConfig {
@@ -312,7 +309,9 @@ pub trait BenchmarkingConfig {
312309
/// A fallback implementation that transitions the pallet to the emergency phase.
313310
pub struct NoFallback<T>(sp_std::marker::PhantomData<T>);
314311

315-
impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for NoFallback<T> {
312+
impl<T: Config> ElectionProvider for NoFallback<T> {
313+
type AccountId = T::AccountId;
314+
type BlockNumber = T::BlockNumber;
316315
type DataProvider = T::DataProvider;
317316
type Error = &'static str;
318317

@@ -654,7 +653,10 @@ pub mod pallet {
654653
type MinerMaxLength: Get<u32>;
655654

656655
/// Something that will provide the election data.
657-
type DataProvider: ElectionDataProvider<Self::AccountId, Self::BlockNumber>;
656+
type DataProvider: ElectionDataProvider<
657+
AccountId = Self::AccountId,
658+
BlockNumber = Self::BlockNumber,
659+
>;
658660

659661
/// The solution type.
660662
type Solution: codec::Codec
@@ -669,8 +671,8 @@ pub mod pallet {
669671

670672
/// Configuration for the fallback
671673
type Fallback: ElectionProvider<
672-
Self::AccountId,
673-
Self::BlockNumber,
674+
AccountId = Self::AccountId,
675+
BlockNumber = Self::BlockNumber,
674676
DataProvider = Self::DataProvider,
675677
>;
676678

@@ -818,7 +820,7 @@ pub mod pallet {
818820
// NOTE that this pallet does not really need to enforce this in runtime. The
819821
// solution cannot represent any voters more than `LIMIT` anyhow.
820822
assert_eq!(
821-
<T::DataProvider as ElectionDataProvider<T::AccountId, T::BlockNumber>>::MAXIMUM_VOTES_PER_VOTER,
823+
<T::DataProvider as ElectionDataProvider>::MAXIMUM_VOTES_PER_VOTER,
822824
<SolutionOf<T> as NposSolution>::LIMIT as u32,
823825
);
824826
}
@@ -1492,7 +1494,9 @@ impl<T: Config> Pallet<T> {
14921494
}
14931495
}
14941496

1495-
impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for Pallet<T> {
1497+
impl<T: Config> ElectionProvider for Pallet<T> {
1498+
type AccountId = T::AccountId;
1499+
type BlockNumber = T::BlockNumber;
14961500
type Error = ElectionError<T>;
14971501
type DataProvider = T::DataProvider;
14981502

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,9 @@ impl onchain::Config for Runtime {
285285
}
286286

287287
pub struct MockFallback;
288-
impl ElectionProvider<AccountId, u64> for MockFallback {
288+
impl ElectionProvider for MockFallback {
289+
type AccountId = AccountId;
290+
type BlockNumber = u64;
289291
type Error = &'static str;
290292
type DataProvider = StakingMock;
291293

@@ -438,7 +440,9 @@ pub type Extrinsic = sp_runtime::testing::TestXt<Call, ()>;
438440
pub struct ExtBuilder {}
439441

440442
pub struct StakingMock;
441-
impl ElectionDataProvider<AccountId, u64> for StakingMock {
443+
impl ElectionDataProvider for StakingMock {
444+
type AccountId = AccountId;
445+
type BlockNumber = u64;
442446
const MAXIMUM_VOTES_PER_VOTER: u32 = <TestNposSolution as NposSolution>::LIMIT as u32;
443447
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
444448
let targets = Targets::get();

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

Lines changed: 57 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -90,21 +90,24 @@
9090
//!
9191
//! pub trait Config: Sized {
9292
//! type ElectionProvider: ElectionProvider<
93-
//! AccountId,
94-
//! BlockNumber,
95-
//! DataProvider = Module<Self>,
93+
//! AccountId = AccountId,
94+
//! BlockNumber = BlockNumber,
95+
//! DataProvider = Pallet<Self>,
9696
//! >;
9797
//! }
9898
//!
99-
//! pub struct Module<T: Config>(std::marker::PhantomData<T>);
99+
//! pub struct Pallet<T: Config>(std::marker::PhantomData<T>);
100100
//!
101-
//! impl<T: Config> ElectionDataProvider<AccountId, BlockNumber> for Module<T> {
101+
//! impl<T: Config> ElectionDataProvider for Pallet<T> {
102+
//! type AccountId = AccountId;
103+
//! type BlockNumber = BlockNumber;
102104
//! const MAXIMUM_VOTES_PER_VOTER: u32 = 1;
105+
//!
103106
//! fn desired_targets() -> data_provider::Result<u32> {
104107
//! Ok(1)
105108
//! }
106109
//! fn voters(maybe_max_len: Option<usize>)
107-
//! -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>>
110+
//! -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>>
108111
//! {
109112
//! Ok(Default::default())
110113
//! }
@@ -124,10 +127,12 @@
124127
//! pub struct GenericElectionProvider<T: Config>(std::marker::PhantomData<T>);
125128
//!
126129
//! pub trait Config {
127-
//! type DataProvider: ElectionDataProvider<AccountId, BlockNumber>;
130+
//! type DataProvider: ElectionDataProvider<AccountId=AccountId, BlockNumber = BlockNumber>;
128131
//! }
129132
//!
130-
//! impl<T: Config> ElectionProvider<AccountId, BlockNumber> for GenericElectionProvider<T> {
133+
//! impl<T: Config> ElectionProvider for GenericElectionProvider<T> {
134+
//! type AccountId = AccountId;
135+
//! type BlockNumber = BlockNumber;
131136
//! type Error = &'static str;
132137
//! type DataProvider = T::DataProvider;
133138
//!
@@ -146,7 +151,7 @@
146151
//!
147152
//! struct Runtime;
148153
//! impl generic_election_provider::Config for Runtime {
149-
//! type DataProvider = data_provider_mod::Module<Runtime>;
154+
//! type DataProvider = data_provider_mod::Pallet<Runtime>;
150155
//! }
151156
//!
152157
//! impl data_provider_mod::Config for Runtime {
@@ -178,7 +183,13 @@ pub mod data_provider {
178183
}
179184

180185
/// Something that can provide the data to an [`ElectionProvider`].
181-
pub trait ElectionDataProvider<AccountId, BlockNumber> {
186+
pub trait ElectionDataProvider {
187+
/// The account identifier type.
188+
type AccountId;
189+
190+
/// The block number type.
191+
type BlockNumber;
192+
182193
/// Maximum number of votes per voter that this data provider is providing.
183194
const MAXIMUM_VOTES_PER_VOTER: u32;
184195

@@ -189,7 +200,7 @@ pub trait ElectionDataProvider<AccountId, BlockNumber> {
189200
///
190201
/// This should be implemented as a self-weighing function. The implementor should register its
191202
/// appropriate weight at the end of execution with the system pallet directly.
192-
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>>;
203+
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<Self::AccountId>>;
193204

194205
/// All possible voters for the election.
195206
///
@@ -202,7 +213,7 @@ pub trait ElectionDataProvider<AccountId, BlockNumber> {
202213
/// appropriate weight at the end of execution with the system pallet directly.
203214
fn voters(
204215
maybe_max_len: Option<usize>,
205-
) -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>>;
216+
) -> data_provider::Result<Vec<(Self::AccountId, VoteWeight, Vec<Self::AccountId>)>>;
206217

207218
/// The number of targets to elect.
208219
///
@@ -216,14 +227,14 @@ pub trait ElectionDataProvider<AccountId, BlockNumber> {
216227
/// [`ElectionProvider::elect`].
217228
///
218229
/// This is only useful for stateful election providers.
219-
fn next_election_prediction(now: BlockNumber) -> BlockNumber;
230+
fn next_election_prediction(now: Self::BlockNumber) -> Self::BlockNumber;
220231

221232
/// Utility function only to be used in benchmarking scenarios, to be implemented optionally,
222233
/// else a noop.
223234
#[cfg(any(feature = "runtime-benchmarks", test))]
224235
fn put_snapshot(
225-
_voters: Vec<(AccountId, VoteWeight, Vec<AccountId>)>,
226-
_targets: Vec<AccountId>,
236+
_voters: Vec<(Self::AccountId, VoteWeight, Vec<Self::AccountId>)>,
237+
_targets: Vec<Self::AccountId>,
227238
_target_stake: Option<VoteWeight>,
228239
) {
229240
}
@@ -233,22 +244,29 @@ pub trait ElectionDataProvider<AccountId, BlockNumber> {
233244
///
234245
/// Same as `put_snapshot`, but can add a single voter one by one.
235246
#[cfg(any(feature = "runtime-benchmarks", test))]
236-
fn add_voter(_voter: AccountId, _weight: VoteWeight, _targets: Vec<AccountId>) {}
247+
fn add_voter(_voter: Self::AccountId, _weight: VoteWeight, _targets: Vec<Self::AccountId>) {}
237248

238249
/// Utility function only to be used in benchmarking scenarios, to be implemented optionally,
239250
/// else a noop.
240251
///
241252
/// Same as `put_snapshot`, but can add a single voter one by one.
242253
#[cfg(any(feature = "runtime-benchmarks", test))]
243-
fn add_target(_target: AccountId) {}
254+
fn add_target(_target: Self::AccountId) {}
244255

245256
/// Clear all voters and targets.
246257
#[cfg(any(feature = "runtime-benchmarks", test))]
247258
fn clear() {}
248259
}
249260

261+
/// An election data provider that should only be used for testing.
250262
#[cfg(feature = "std")]
251-
impl<AccountId, BlockNumber> ElectionDataProvider<AccountId, BlockNumber> for () {
263+
pub struct TestDataProvider<X>(sp_std::marker::PhantomData<X>);
264+
265+
#[cfg(feature = "std")]
266+
impl<AccountId, BlockNumber> ElectionDataProvider for TestDataProvider<(AccountId, BlockNumber)> {
267+
type AccountId = AccountId;
268+
type BlockNumber = BlockNumber;
269+
252270
const MAXIMUM_VOTES_PER_VOTER: u32 = 0;
253271
fn targets(_maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
254272
Ok(Default::default())
@@ -271,29 +289,44 @@ impl<AccountId, BlockNumber> ElectionDataProvider<AccountId, BlockNumber> for ()
271289
/// This trait only provides an interface to _request_ an election, i.e.
272290
/// [`ElectionProvider::elect`]. That data required for the election need to be passed to the
273291
/// implemented of this trait through [`ElectionProvider::DataProvider`].
274-
pub trait ElectionProvider<AccountId, BlockNumber> {
292+
pub trait ElectionProvider {
293+
/// The account identifier type.
294+
type AccountId;
295+
296+
/// The block number type.
297+
type BlockNumber;
298+
275299
/// The error type that is returned by the provider.
276300
type Error: Debug;
277301

278302
/// The data provider of the election.
279-
type DataProvider: ElectionDataProvider<AccountId, BlockNumber>;
303+
type DataProvider: ElectionDataProvider<
304+
AccountId = Self::AccountId,
305+
BlockNumber = Self::BlockNumber,
306+
>;
280307

281308
/// Elect a new set of winners.
282309
///
283310
/// The result is returned in a target major format, namely as vector of supports.
284311
///
285312
/// This should be implemented as a self-weighing function. The implementor should register its
286313
/// appropriate weight at the end of execution with the system pallet directly.
287-
fn elect() -> Result<Supports<AccountId>, Self::Error>;
314+
fn elect() -> Result<Supports<Self::AccountId>, Self::Error>;
288315
}
289316

317+
/// An election provider to be used only for testing.
290318
#[cfg(feature = "std")]
291-
impl<AccountId, BlockNumber> ElectionProvider<AccountId, BlockNumber> for () {
319+
pub struct NoElection<X>(sp_std::marker::PhantomData<X>);
320+
321+
#[cfg(feature = "std")]
322+
impl<AccountId, BlockNumber> ElectionProvider for NoElection<(AccountId, BlockNumber)> {
323+
type AccountId = AccountId;
324+
type BlockNumber = BlockNumber;
292325
type Error = &'static str;
293-
type DataProvider = ();
326+
type DataProvider = TestDataProvider<(AccountId, BlockNumber)>;
294327

295328
fn elect() -> Result<Supports<AccountId>, Self::Error> {
296-
Err("<() as ElectionProvider> cannot do anything.")
329+
Err("<NoElection as ElectionProvider> cannot do anything.")
297330
}
298331
}
299332

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,15 @@ pub trait Config: frame_system::Config {
6262
/// The accuracy used to compute the election:
6363
type Accuracy: PerThing128;
6464
/// Something that provides the data for election.
65-
type DataProvider: ElectionDataProvider<Self::AccountId, Self::BlockNumber>;
65+
type DataProvider: ElectionDataProvider<
66+
AccountId = Self::AccountId,
67+
BlockNumber = Self::BlockNumber,
68+
>;
6669
}
6770

68-
impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for OnChainSequentialPhragmen<T> {
71+
impl<T: Config> ElectionProvider for OnChainSequentialPhragmen<T> {
72+
type AccountId = T::AccountId;
73+
type BlockNumber = T::BlockNumber;
6974
type Error = Error;
7075
type DataProvider = T::DataProvider;
7176

@@ -160,7 +165,9 @@ mod tests {
160165
use crate::data_provider;
161166

162167
pub struct DataProvider;
163-
impl ElectionDataProvider<AccountId, BlockNumber> for DataProvider {
168+
impl ElectionDataProvider for DataProvider {
169+
type AccountId = AccountId;
170+
type BlockNumber = BlockNumber;
164171
const MAXIMUM_VOTES_PER_VOTER: u32 = 2;
165172
fn voters(
166173
_: Option<usize>,

frame/staking/src/pallet/impls.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -844,7 +844,9 @@ impl<T: Config> Pallet<T> {
844844
}
845845
}
846846

847-
impl<T: Config> ElectionDataProvider<T::AccountId, BlockNumberFor<T>> for Pallet<T> {
847+
impl<T: Config> ElectionDataProvider for Pallet<T> {
848+
type AccountId = T::AccountId;
849+
type BlockNumber = BlockNumberFor<T>;
848850
const MAXIMUM_VOTES_PER_VOTER: u32 = T::MAX_NOMINATIONS;
849851

850852
fn desired_targets() -> data_provider::Result<u32> {

frame/staking/src/pallet/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,16 @@ pub mod pallet {
7979

8080
/// Something that provides the election functionality.
8181
type ElectionProvider: frame_election_provider_support::ElectionProvider<
82-
Self::AccountId,
83-
Self::BlockNumber,
82+
AccountId = Self::AccountId,
83+
BlockNumber = Self::BlockNumber,
8484
// we only accept an election provider that has staking as data provider.
8585
DataProvider = Pallet<Self>,
8686
>;
8787

8888
/// Something that provides the election functionality at genesis.
8989
type GenesisElectionProvider: frame_election_provider_support::ElectionProvider<
90-
Self::AccountId,
91-
Self::BlockNumber,
90+
AccountId = Self::AccountId,
91+
BlockNumber = Self::BlockNumber,
9292
DataProvider = Pallet<Self>,
9393
>;
9494

frame/staking/src/tests.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4013,7 +4013,7 @@ mod election_data_provider {
40134013
ExtBuilder::default().build_and_execute(|| {
40144014
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
40154015
assert_eq!(
4016-
<Staking as ElectionDataProvider<AccountId, BlockNumber>>::voters(None)
4016+
<Staking as ElectionDataProvider>::voters(None)
40174017
.unwrap()
40184018
.iter()
40194019
.find(|x| x.0 == 101)
@@ -4028,7 +4028,7 @@ mod election_data_provider {
40284028
// 11 is gone.
40294029
start_active_era(2);
40304030
assert_eq!(
4031-
<Staking as ElectionDataProvider<AccountId, BlockNumber>>::voters(None)
4031+
<Staking as ElectionDataProvider>::voters(None)
40324032
.unwrap()
40334033
.iter()
40344034
.find(|x| x.0 == 101)
@@ -4040,7 +4040,7 @@ mod election_data_provider {
40404040
// resubmit and it is back
40414041
assert_ok!(Staking::nominate(Origin::signed(100), vec![11, 21]));
40424042
assert_eq!(
4043-
<Staking as ElectionDataProvider<AccountId, BlockNumber>>::voters(None)
4043+
<Staking as ElectionDataProvider>::voters(None)
40444044
.unwrap()
40454045
.iter()
40464046
.find(|x| x.0 == 101)

0 commit comments

Comments
 (0)