1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use crate::{ElectionDataProvider, ElectionProvider};
use frame_support::{traits::Get, weights::Weight};
use sp_npos_elections::*;
use sp_std::{collections::btree_map::BTreeMap, marker::PhantomData, prelude::*};
#[derive(Eq, PartialEq, Debug)]
pub enum Error {
NposElections(sp_npos_elections::Error),
DataProvider(&'static str),
}
impl From<sp_npos_elections::Error> for Error {
fn from(e: sp_npos_elections::Error) -> Self {
Error::NposElections(e)
}
}
pub struct OnChainSequentialPhragmen<T: Config>(PhantomData<T>);
pub trait Config {
type BlockWeights: Get<frame_system::limits::BlockWeights>;
type AccountId: IdentifierT;
type BlockNumber;
type Accuracy: PerThing128;
type DataProvider: ElectionDataProvider<Self::AccountId, Self::BlockNumber>;
}
impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for OnChainSequentialPhragmen<T> {
type Error = Error;
type DataProvider = T::DataProvider;
fn elect() -> Result<(Supports<T::AccountId>, Weight), Self::Error> {
let (voters, _) = Self::DataProvider::voters(None).map_err(Error::DataProvider)?;
let (targets, _) = Self::DataProvider::targets(None).map_err(Error::DataProvider)?;
let (desired_targets, _) =
Self::DataProvider::desired_targets().map_err(Error::DataProvider)?;
let mut stake_map: BTreeMap<T::AccountId, VoteWeight> = BTreeMap::new();
voters.iter().for_each(|(v, s, _)| {
stake_map.insert(v.clone(), *s);
});
let stake_of =
|w: &T::AccountId| -> VoteWeight { stake_map.get(w).cloned().unwrap_or_default() };
let ElectionResult { winners, assignments } =
seq_phragmen::<_, T::Accuracy>(desired_targets as usize, targets, voters, None)
.map_err(Error::from)?;
let staked = assignment_ratio_to_staked_normalized(assignments, &stake_of)?;
let winners = to_without_backing(winners);
to_supports(&winners, &staked)
.map_err(Error::from)
.map(|s| (s, T::BlockWeights::get().max_block))
}
}
#[cfg(test)]
mod tests {
use super::*;
use frame_support::weights::Weight;
use sp_npos_elections::Support;
use sp_runtime::Perbill;
type AccountId = u64;
type BlockNumber = u32;
struct Runtime;
impl Config for Runtime {
type BlockWeights = ();
type AccountId = AccountId;
type BlockNumber = BlockNumber;
type Accuracy = Perbill;
type DataProvider = mock_data_provider::DataProvider;
}
type OnChainPhragmen = OnChainSequentialPhragmen<Runtime>;
mod mock_data_provider {
use super::*;
use crate::data_provider;
pub struct DataProvider;
impl ElectionDataProvider<AccountId, BlockNumber> for DataProvider {
const MAXIMUM_VOTES_PER_VOTER: u32 = 2;
fn voters(
_: Option<usize>,
) -> data_provider::Result<(Vec<(AccountId, VoteWeight, Vec<AccountId>)>, Weight)> {
Ok((vec![(1, 10, vec![10, 20]), (2, 20, vec![30, 20]), (3, 30, vec![10, 30])], 0))
}
fn targets(_: Option<usize>) -> data_provider::Result<(Vec<AccountId>, Weight)> {
Ok((vec![10, 20, 30], 0))
}
fn desired_targets() -> data_provider::Result<(u32, Weight)> {
Ok((2, 0))
}
fn next_election_prediction(_: BlockNumber) -> BlockNumber {
0
}
}
}
#[test]
fn onchain_seq_phragmen_works() {
assert_eq!(
OnChainPhragmen::elect().unwrap().0,
vec![
(10, Support { total: 25, voters: vec![(1, 10), (3, 15)] }),
(30, Support { total: 35, voters: vec![(2, 20), (3, 15)] })
]
);
}
}