frame_election_provider_support/
traits.rs1use crate::{Assignment, IdentifierT, IndexAssignmentOf, PerThing128, VoteWeight};
21use alloc::vec::Vec;
22use codec::Encode;
23use core::fmt::Debug;
24use scale_info::TypeInfo;
25use sp_arithmetic::traits::{Bounded, UniqueSaturatedInto};
26use sp_npos_elections::{ElectionScore, Error, EvaluateSupport};
27
28pub trait NposSolution
30where
31	Self: Sized + for<'a> TryFrom<&'a [IndexAssignmentOf<Self>], Error = Error>,
32{
33	const LIMIT: usize;
35
36	type VoterIndex: UniqueSaturatedInto<usize>
38		+ TryInto<usize>
39		+ TryFrom<usize>
40		+ Debug
41		+ Copy
42		+ Clone
43		+ Bounded
44		+ Encode
45		+ Ord
46		+ PartialOrd
47		+ TypeInfo;
48
49	type TargetIndex: UniqueSaturatedInto<usize>
51		+ TryInto<usize>
52		+ TryFrom<usize>
53		+ Debug
54		+ Copy
55		+ Clone
56		+ Bounded
57		+ Encode
58		+ Ord
59		+ PartialOrd
60		+ TypeInfo;
61
62	type Accuracy: PerThing128;
64
65	fn voter_count(&self) -> usize;
69
70	fn edge_count(&self) -> usize;
75
76	fn unique_targets(&self) -> Vec<Self::TargetIndex>;
81
82	fn average_edge_count(&self) -> usize {
84		self.edge_count().checked_div(self.voter_count()).unwrap_or(0)
85	}
86
87	fn score<A, FS>(
89		self,
90		stake_of: FS,
91		voter_at: impl Fn(Self::VoterIndex) -> Option<A>,
92		target_at: impl Fn(Self::TargetIndex) -> Option<A>,
93	) -> Result<ElectionScore, Error>
94	where
95		for<'r> FS: Fn(&'r A) -> VoteWeight,
96		A: IdentifierT,
97	{
98		let ratio = self.into_assignment(voter_at, target_at)?;
99		let staked =
100			sp_npos_elections::helpers::assignment_ratio_to_staked_normalized(ratio, stake_of)?;
101		let supports = sp_npos_elections::to_supports(&staked);
102		Ok(supports.evaluate())
103	}
104
105	fn remove_voter(&mut self, to_remove: Self::VoterIndex) -> bool;
112
113	fn from_assignment<FV, FT, A>(
115		assignments: &[Assignment<A, Self::Accuracy>],
116		voter_index: FV,
117		target_index: FT,
118	) -> Result<Self, Error>
119	where
120		A: IdentifierT,
121		for<'r> FV: Fn(&'r A) -> Option<Self::VoterIndex>,
122		for<'r> FT: Fn(&'r A) -> Option<Self::TargetIndex>;
123
124	fn into_assignment<A: IdentifierT>(
126		self,
127		voter_at: impl Fn(Self::VoterIndex) -> Option<A>,
128		target_at: impl Fn(Self::TargetIndex) -> Option<A>,
129	) -> Result<Vec<Assignment<A, Self::Accuracy>>, Error>;
130
131	fn sort<F>(&mut self, voter_stake: F)
135	where
136		F: FnMut(&Self::VoterIndex) -> VoteWeight;
137
138	fn remove_weakest_sorted<F>(&mut self, voter_stake: F) -> Option<Self::VoterIndex>
142	where
143		F: FnMut(&Self::VoterIndex) -> VoteWeight;
144
145	fn corrupt(&mut self);
149}