This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
lib.rs
3327 lines (2820 loc) · 110 KB
/
lib.rs
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Phragmén Election Module.
//!
//! An election module based on sequential phragmen.
//!
//! ### Term and Round
//!
//! The election happens in _rounds_: every `N` blocks, all previous members are retired and a new
//! set is elected (which may or may not have an intersection with the previous set). Each round
//! lasts for some number of blocks defined by [`Config::TermDuration`]. The words _term_ and
//! _round_ can be used interchangeably in this context.
//!
//! [`Config::TermDuration`] might change during a round. This can shorten or extend the length of
//! the round. The next election round's block number is never stored but rather always checked on
//! the fly. Based on the current block number and [`Config::TermDuration`], the condition
//! `BlockNumber % TermDuration == 0` being satisfied will always trigger a new election round.
//!
//! ### Bonds and Deposits
//!
//! Both voting and being a candidate requires deposits to be taken, in exchange for the data that
//! needs to be kept on-chain. The terms *bond* and *deposit* can be used interchangeably in this
//! context.
//!
//! Bonds will be unreserved only upon adhering to the protocol laws. Failing to do so will cause in
//! the bond to slashed.
//!
//! ### Voting
//!
//! Voters can vote for a limited number of the candidates by providing a list of account ids,
//! bounded by [`Config::MaxVotesPerVoter`]. Invalid votes (voting for non-candidates) and duplicate
//! votes are ignored during election. Yet, a voter _might_ vote for a future candidate. Voters
//! reserve a bond as they vote. Each vote defines a `value`. This amount is locked from the account
//! of the voter and indicates the weight of the vote. Voters can update their votes at any time by
//! calling `vote()` again. This can update the vote targets (which might update the deposit) or
//! update the vote's stake ([`Voter::stake`]). After a round, votes are kept and might still be
//! valid for further rounds. A voter is responsible for calling `remove_voter` once they are done
//! to have their bond back and remove the lock.
//!
//! See [`Call::vote`], [`Call::remove_voter`].
//!
//! ### Defunct Voter
//!
//! A voter is defunct once all of the candidates that they have voted for are not a valid candidate
//! (as seen further below, members and runners-up are also always candidates). Defunct voters can
//! be removed via a root call ([`Call::clean_defunct_voters`]). Upon being removed, their bond is
//! returned. This is an administrative operation and can be called only by the root origin in the
//! case of state bloat.
//!
//! ### Candidacy and Members
//!
//! Candidates also reserve a bond as they submit candidacy. A candidate can end up in one of the
//! below situations:
//! - **Members**: A winner is kept as a _member_. They must still have a bond in reserve and they
//! are automatically counted as a candidate for the next election. The number of desired
//! members is set by [`Config::DesiredMembers`].
//! - **Runner-up**: Runners-up are the best candidates immediately after the winners. The number
//! of runners up to keep is set by [`Config::DesiredRunnersUp`]. Runners-up are used, in the
//! same order as they are elected, as replacements when a candidate is kicked by
//! [`Call::remove_member`], or when an active member renounces their candidacy. Runners are
//! automatically counted as a candidate for the next election.
//! - **Loser**: Any of the candidate who are not member/runner-up are left as losers. A loser
//! might be an _outgoing member or runner-up_, meaning that they are an active member who
//! failed to keep their spot. **An outgoing candidate/member/runner-up will always lose their
//! bond**.
//!
//! #### Renouncing candidacy.
//!
//! All candidates, elected or not, can renounce their candidacy. A call to
//! [`Call::renounce_candidacy`] will always cause the candidacy bond to be refunded.
//!
//! Note that with the members being the default candidates for the next round and votes persisting
//! in storage, the election system is entirely stable given no further input. This means that if
//! the system has a particular set of candidates `C` and voters `V` that lead to a set of members
//! `M` being elected, as long as `V` and `C` don't remove their candidacy and votes, `M` will keep
//! being re-elected at the end of each round.
//!
//! ### Module Information
//!
//! - [`Config`]
//! - [`Call`]
//! - [`Module`]
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use frame_support::{
traits::{
defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency, Get,
InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency,
SortedMembers, WithdrawReasons,
},
weights::Weight,
};
use log;
use scale_info::TypeInfo;
use sp_npos_elections::{ElectionResult, ExtendedBalance};
use sp_runtime::{
traits::{Saturating, StaticLookup, Zero},
DispatchError, Perbill, RuntimeDebug,
};
use sp_staking::currency_to_vote::CurrencyToVote;
use sp_std::{cmp::Ordering, prelude::*};
#[cfg(any(feature = "try-runtime", test))]
use sp_runtime::TryRuntimeError;
mod benchmarking;
pub mod weights;
pub use weights::WeightInfo;
/// All migrations.
pub mod migrations;
const LOG_TARGET: &str = "runtime::elections-phragmen";
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
/// An indication that the renouncing account currently has which of the below roles.
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)]
pub enum Renouncing {
/// A member is renouncing.
Member,
/// A runner-up is renouncing.
RunnerUp,
/// A candidate is renouncing, while the given total number of candidates exists.
Candidate(#[codec(compact)] u32),
}
/// An active voter.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, TypeInfo)]
pub struct Voter<AccountId, Balance> {
/// The members being backed.
pub votes: Vec<AccountId>,
/// The amount of stake placed on this vote.
pub stake: Balance,
/// The amount of deposit reserved for this vote.
///
/// To be unreserved upon removal.
pub deposit: Balance,
}
impl<AccountId, Balance: Default> Default for Voter<AccountId, Balance> {
fn default() -> Self {
Self { votes: vec![], stake: Default::default(), deposit: Default::default() }
}
}
/// A holder of a seat as either a member or a runner-up.
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, TypeInfo)]
pub struct SeatHolder<AccountId, Balance> {
/// The holder.
pub who: AccountId,
/// The total backing stake.
pub stake: Balance,
/// The amount of deposit held on-chain.
///
/// To be unreserved upon renouncing, or slashed upon being a loser.
pub deposit: Balance,
}
pub use pallet::*;
type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
/// The current storage version.
const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Identifier for the elections-phragmen pallet's lock
#[pallet::constant]
type PalletId: Get<LockIdentifier>;
/// The currency that people are electing with.
type Currency: LockableCurrency<Self::AccountId, Moment = BlockNumberFor<Self>>
+ ReservableCurrency<Self::AccountId>;
/// What to do when the members change.
type ChangeMembers: ChangeMembers<Self::AccountId>;
/// What to do with genesis members
type InitializeMembers: InitializeMembers<Self::AccountId>;
/// Convert a balance into a number used for election calculation.
/// This must fit into a `u64` but is allowed to be sensibly lossy.
type CurrencyToVote: CurrencyToVote<BalanceOf<Self>>;
/// How much should be locked up in order to submit one's candidacy.
#[pallet::constant]
type CandidacyBond: Get<BalanceOf<Self>>;
/// Base deposit associated with voting.
///
/// This should be sensibly high to economically ensure the pallet cannot be attacked by
/// creating a gigantic number of votes.
#[pallet::constant]
type VotingBondBase: Get<BalanceOf<Self>>;
/// The amount of bond that need to be locked for each vote (32 bytes).
#[pallet::constant]
type VotingBondFactor: Get<BalanceOf<Self>>;
/// Handler for the unbalanced reduction when a candidate has lost (and is not a runner-up)
type LoserCandidate: OnUnbalanced<NegativeImbalanceOf<Self>>;
/// Handler for the unbalanced reduction when a member has been kicked.
type KickedMember: OnUnbalanced<NegativeImbalanceOf<Self>>;
/// Number of members to elect.
#[pallet::constant]
type DesiredMembers: Get<u32>;
/// Number of runners_up to keep.
#[pallet::constant]
type DesiredRunnersUp: Get<u32>;
/// How long each seat is kept. This defines the next block number at which an election
/// round will happen. If set to zero, no elections are ever triggered and the module will
/// be in passive mode.
#[pallet::constant]
type TermDuration: Get<BlockNumberFor<Self>>;
/// The maximum number of candidates in a phragmen election.
///
/// Warning: This impacts the size of the election which is run onchain. Chose wisely, and
/// consider how it will impact `T::WeightInfo::election_phragmen`.
///
/// When this limit is reached no more candidates are accepted in the election.
#[pallet::constant]
type MaxCandidates: Get<u32>;
/// The maximum number of voters to allow in a phragmen election.
///
/// Warning: This impacts the size of the election which is run onchain. Chose wisely, and
/// consider how it will impact `T::WeightInfo::election_phragmen`.
///
/// When the limit is reached the new voters are ignored.
#[pallet::constant]
type MaxVoters: Get<u32>;
/// Maximum numbers of votes per voter.
///
/// Warning: This impacts the size of the election which is run onchain. Chose wisely, and
/// consider how it will impact `T::WeightInfo::election_phragmen`.
#[pallet::constant]
type MaxVotesPerVoter: Get<u32>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
/// What to do at the end of each block.
///
/// Checks if an election needs to happen or not.
fn on_initialize(n: BlockNumberFor<T>) -> Weight {
let term_duration = T::TermDuration::get();
if !term_duration.is_zero() && (n % term_duration).is_zero() {
Self::do_phragmen()
} else {
Weight::zero()
}
}
fn integrity_test() {
let block_weight = T::BlockWeights::get().max_block;
// mind the order.
let election_weight = T::WeightInfo::election_phragmen(
T::MaxCandidates::get(),
T::MaxVoters::get(),
T::MaxVotesPerVoter::get() * T::MaxVoters::get(),
);
let to_seconds = |w: &Weight| {
w.ref_time() as f32 /
frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND as f32
};
log::debug!(
target: LOG_TARGET,
"election weight {}s ({:?}) // chain's block weight {}s ({:?})",
to_seconds(&election_weight),
election_weight,
to_seconds(&block_weight),
block_weight,
);
assert!(
election_weight.all_lt(block_weight),
"election weight {}s ({:?}) will exceed a {}s chain's block weight ({:?}) (MaxCandidates {}, MaxVoters {}, MaxVotesPerVoter {} -- tweak these parameters)",
election_weight,
to_seconds(&election_weight),
to_seconds(&block_weight),
block_weight,
T::MaxCandidates::get(),
T::MaxVoters::get(),
T::MaxVotesPerVoter::get(),
);
}
#[cfg(feature = "try-runtime")]
fn try_state(_n: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
Self::do_try_state()
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Vote for a set of candidates for the upcoming round of election. This can be called to
/// set the initial votes, or update already existing votes.
///
/// Upon initial voting, `value` units of `who`'s balance is locked and a deposit amount is
/// reserved. The deposit is based on the number of votes and can be updated over time.
///
/// The `votes` should:
/// - not be empty.
/// - be less than the number of possible candidates. Note that all current members and
/// runners-up are also automatically candidates for the next round.
///
/// If `value` is more than `who`'s free balance, then the maximum of the two is used.
///
/// The dispatch origin of this call must be signed.
///
/// ### Warning
///
/// It is the responsibility of the caller to **NOT** place all of their balance into the
/// lock and keep some for further operations.
#[pallet::call_index(0)]
#[pallet::weight(
T::WeightInfo::vote_more(votes.len() as u32)
.max(T::WeightInfo::vote_less(votes.len() as u32))
.max(T::WeightInfo::vote_equal(votes.len() as u32))
)]
pub fn vote(
origin: OriginFor<T>,
votes: Vec<T::AccountId>,
#[pallet::compact] value: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
ensure!(
votes.len() <= T::MaxVotesPerVoter::get() as usize,
Error::<T>::MaximumVotesExceeded
);
ensure!(!votes.is_empty(), Error::<T>::NoVotes);
let candidates_count = <Candidates<T>>::decode_len().unwrap_or(0);
let members_count = <Members<T>>::decode_len().unwrap_or(0);
let runners_up_count = <RunnersUp<T>>::decode_len().unwrap_or(0);
// can never submit a vote of there are no members, and cannot submit more votes than
// all potential vote targets.
// addition is valid: candidates, members and runners-up will never overlap.
let allowed_votes =
candidates_count.saturating_add(members_count).saturating_add(runners_up_count);
ensure!(!allowed_votes.is_zero(), Error::<T>::UnableToVote);
ensure!(votes.len() <= allowed_votes, Error::<T>::TooManyVotes);
ensure!(value > T::Currency::minimum_balance(), Error::<T>::LowBalance);
// Reserve bond.
let new_deposit = Self::deposit_of(votes.len());
let Voter { deposit: old_deposit, .. } = <Voting<T>>::get(&who);
match new_deposit.cmp(&old_deposit) {
Ordering::Greater => {
// Must reserve a bit more.
let to_reserve = new_deposit - old_deposit;
T::Currency::reserve(&who, to_reserve)
.map_err(|_| Error::<T>::UnableToPayBond)?;
},
Ordering::Equal => {},
Ordering::Less => {
// Must unreserve a bit.
let to_unreserve = old_deposit - new_deposit;
let _remainder = T::Currency::unreserve(&who, to_unreserve);
debug_assert!(_remainder.is_zero());
},
};
// Amount to be locked up.
let locked_stake = value.min(T::Currency::free_balance(&who));
T::Currency::set_lock(T::PalletId::get(), &who, locked_stake, WithdrawReasons::all());
Voting::<T>::insert(&who, Voter { votes, deposit: new_deposit, stake: locked_stake });
Ok(None::<Weight>.into())
}
/// Remove `origin` as a voter.
///
/// This removes the lock and returns the deposit.
///
/// The dispatch origin of this call must be signed and be a voter.
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::remove_voter())]
pub fn remove_voter(origin: OriginFor<T>) -> DispatchResult {
let who = ensure_signed(origin)?;
ensure!(Self::is_voter(&who), Error::<T>::MustBeVoter);
Self::do_remove_voter(&who);
Ok(())
}
/// Submit oneself for candidacy. A fixed amount of deposit is recorded.
///
/// All candidates are wiped at the end of the term. They either become a member/runner-up,
/// or leave the system while their deposit is slashed.
///
/// The dispatch origin of this call must be signed.
///
/// ### Warning
///
/// Even if a candidate ends up being a member, they must call [`Call::renounce_candidacy`]
/// to get their deposit back. Losing the spot in an election will always lead to a slash.
///
/// The number of current candidates must be provided as witness data.
/// ## Complexity
/// O(C + log(C)) where C is candidate_count.
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::submit_candidacy(*candidate_count))]
pub fn submit_candidacy(
origin: OriginFor<T>,
#[pallet::compact] candidate_count: u32,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let actual_count = <Candidates<T>>::decode_len().unwrap_or(0) as u32;
ensure!(actual_count <= candidate_count, Error::<T>::InvalidWitnessData);
ensure!(
actual_count <= <T as Config>::MaxCandidates::get(),
Error::<T>::TooManyCandidates
);
let index = Self::is_candidate(&who).err().ok_or(Error::<T>::DuplicatedCandidate)?;
ensure!(!Self::is_member(&who), Error::<T>::MemberSubmit);
ensure!(!Self::is_runner_up(&who), Error::<T>::RunnerUpSubmit);
T::Currency::reserve(&who, T::CandidacyBond::get())
.map_err(|_| Error::<T>::InsufficientCandidateFunds)?;
<Candidates<T>>::mutate(|c| c.insert(index, (who, T::CandidacyBond::get())));
Ok(())
}
/// Renounce one's intention to be a candidate for the next election round. 3 potential
/// outcomes exist:
///
/// - `origin` is a candidate and not elected in any set. In this case, the deposit is
/// unreserved, returned and origin is removed as a candidate.
/// - `origin` is a current runner-up. In this case, the deposit is unreserved, returned and
/// origin is removed as a runner-up.
/// - `origin` is a current member. In this case, the deposit is unreserved and origin is
/// removed as a member, consequently not being a candidate for the next round anymore.
/// Similar to [`remove_member`](Self::remove_member), if replacement runners exists, they
/// are immediately used. If the prime is renouncing, then no prime will exist until the
/// next round.
///
/// The dispatch origin of this call must be signed, and have one of the above roles.
/// The type of renouncing must be provided as witness data.
///
/// ## Complexity
/// - Renouncing::Candidate(count): O(count + log(count))
/// - Renouncing::Member: O(1)
/// - Renouncing::RunnerUp: O(1)
#[pallet::call_index(3)]
#[pallet::weight(match *renouncing {
Renouncing::Candidate(count) => T::WeightInfo::renounce_candidacy_candidate(count),
Renouncing::Member => T::WeightInfo::renounce_candidacy_members(),
Renouncing::RunnerUp => T::WeightInfo::renounce_candidacy_runners_up(),
})]
pub fn renounce_candidacy(origin: OriginFor<T>, renouncing: Renouncing) -> DispatchResult {
let who = ensure_signed(origin)?;
match renouncing {
Renouncing::Member => {
let _ = Self::remove_and_replace_member(&who, false)
.map_err(|_| Error::<T>::InvalidRenouncing)?;
Self::deposit_event(Event::Renounced { candidate: who });
},
Renouncing::RunnerUp => {
<RunnersUp<T>>::try_mutate::<_, Error<T>, _>(|runners_up| {
let index = runners_up
.iter()
.position(|SeatHolder { who: r, .. }| r == &who)
.ok_or(Error::<T>::InvalidRenouncing)?;
// can't fail anymore.
let SeatHolder { deposit, .. } = runners_up.remove(index);
let _remainder = T::Currency::unreserve(&who, deposit);
debug_assert!(_remainder.is_zero());
Self::deposit_event(Event::Renounced { candidate: who });
Ok(())
})?;
},
Renouncing::Candidate(count) => {
<Candidates<T>>::try_mutate::<_, Error<T>, _>(|candidates| {
ensure!(count >= candidates.len() as u32, Error::<T>::InvalidWitnessData);
let index = candidates
.binary_search_by(|(c, _)| c.cmp(&who))
.map_err(|_| Error::<T>::InvalidRenouncing)?;
let (_removed, deposit) = candidates.remove(index);
let _remainder = T::Currency::unreserve(&who, deposit);
debug_assert!(_remainder.is_zero());
Self::deposit_event(Event::Renounced { candidate: who });
Ok(())
})?;
},
};
Ok(())
}
/// Remove a particular member from the set. This is effective immediately and the bond of
/// the outgoing member is slashed.
///
/// If a runner-up is available, then the best runner-up will be removed and replaces the
/// outgoing member. Otherwise, if `rerun_election` is `true`, a new phragmen election is
/// started, else, nothing happens.
///
/// If `slash_bond` is set to true, the bond of the member being removed is slashed. Else,
/// it is returned.
///
/// The dispatch origin of this call must be root.
///
/// Note that this does not affect the designated block number of the next election.
///
/// ## Complexity
/// - Check details of remove_and_replace_member() and do_phragmen().
#[pallet::call_index(4)]
#[pallet::weight(if *rerun_election {
T::WeightInfo::remove_member_without_replacement()
} else {
T::WeightInfo::remove_member_with_replacement()
})]
pub fn remove_member(
origin: OriginFor<T>,
who: AccountIdLookupOf<T>,
slash_bond: bool,
rerun_election: bool,
) -> DispatchResult {
ensure_root(origin)?;
let who = T::Lookup::lookup(who)?;
let _ = Self::remove_and_replace_member(&who, slash_bond)?;
Self::deposit_event(Event::MemberKicked { member: who });
if rerun_election {
Self::do_phragmen();
}
// no refund needed.
Ok(())
}
/// Clean all voters who are defunct (i.e. they do not serve any purpose at all). The
/// deposit of the removed voters are returned.
///
/// This is an root function to be used only for cleaning the state.
///
/// The dispatch origin of this call must be root.
///
/// ## Complexity
/// - Check is_defunct_voter() details.
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::clean_defunct_voters(*_num_voters, *_num_defunct))]
pub fn clean_defunct_voters(
origin: OriginFor<T>,
_num_voters: u32,
_num_defunct: u32,
) -> DispatchResult {
let _ = ensure_root(origin)?;
<Voting<T>>::iter()
.filter(|(_, x)| Self::is_defunct_voter(&x.votes))
.for_each(|(dv, _)| Self::do_remove_voter(&dv));
Ok(())
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A new term with new_members. This indicates that enough candidates existed to run
/// the election, not that enough have has been elected. The inner value must be examined
/// for this purpose. A `NewTerm(\[\])` indicates that some candidates got their bond
/// slashed and none were elected, whilst `EmptyTerm` means that no candidates existed to
/// begin with.
NewTerm { new_members: Vec<(<T as frame_system::Config>::AccountId, BalanceOf<T>)> },
/// No (or not enough) candidates existed for this round. This is different from
/// `NewTerm(\[\])`. See the description of `NewTerm`.
EmptyTerm,
/// Internal error happened while trying to perform election.
ElectionError,
/// A member has been removed. This should always be followed by either `NewTerm` or
/// `EmptyTerm`.
MemberKicked { member: <T as frame_system::Config>::AccountId },
/// Someone has renounced their candidacy.
Renounced { candidate: <T as frame_system::Config>::AccountId },
/// A candidate was slashed by amount due to failing to obtain a seat as member or
/// runner-up.
///
/// Note that old members and runners-up are also candidates.
CandidateSlashed { candidate: <T as frame_system::Config>::AccountId, amount: BalanceOf<T> },
/// A seat holder was slashed by amount by being forcefully removed from the set.
SeatHolderSlashed {
seat_holder: <T as frame_system::Config>::AccountId,
amount: BalanceOf<T>,
},
}
#[pallet::error]
pub enum Error<T> {
/// Cannot vote when no candidates or members exist.
UnableToVote,
/// Must vote for at least one candidate.
NoVotes,
/// Cannot vote more than candidates.
TooManyVotes,
/// Cannot vote more than maximum allowed.
MaximumVotesExceeded,
/// Cannot vote with stake less than minimum balance.
LowBalance,
/// Voter can not pay voting bond.
UnableToPayBond,
/// Must be a voter.
MustBeVoter,
/// Duplicated candidate submission.
DuplicatedCandidate,
/// Too many candidates have been created.
TooManyCandidates,
/// Member cannot re-submit candidacy.
MemberSubmit,
/// Runner cannot re-submit candidacy.
RunnerUpSubmit,
/// Candidate does not have enough funds.
InsufficientCandidateFunds,
/// Not a member.
NotMember,
/// The provided count of number of candidates is incorrect.
InvalidWitnessData,
/// The provided count of number of votes is incorrect.
InvalidVoteCount,
/// The renouncing origin presented a wrong `Renouncing` parameter.
InvalidRenouncing,
/// Prediction regarding replacement after member removal is wrong.
InvalidReplacement,
}
/// The current elected members.
///
/// Invariant: Always sorted based on account id.
#[pallet::storage]
#[pallet::getter(fn members)]
pub type Members<T: Config> =
StorageValue<_, Vec<SeatHolder<T::AccountId, BalanceOf<T>>>, ValueQuery>;
/// The current reserved runners-up.
///
/// Invariant: Always sorted based on rank (worse to best). Upon removal of a member, the
/// last (i.e. _best_) runner-up will be replaced.
#[pallet::storage]
#[pallet::getter(fn runners_up)]
pub type RunnersUp<T: Config> =
StorageValue<_, Vec<SeatHolder<T::AccountId, BalanceOf<T>>>, ValueQuery>;
/// The present candidate list. A current member or runner-up can never enter this vector
/// and is always implicitly assumed to be a candidate.
///
/// Second element is the deposit.
///
/// Invariant: Always sorted based on account id.
#[pallet::storage]
#[pallet::getter(fn candidates)]
pub type Candidates<T: Config> = StorageValue<_, Vec<(T::AccountId, BalanceOf<T>)>, ValueQuery>;
/// The total number of vote rounds that have happened, excluding the upcoming one.
#[pallet::storage]
#[pallet::getter(fn election_rounds)]
pub type ElectionRounds<T: Config> = StorageValue<_, u32, ValueQuery>;
/// Votes and locked stake of a particular voter.
///
/// TWOX-NOTE: SAFE as `AccountId` is a crypto hash.
#[pallet::storage]
#[pallet::getter(fn voting)]
pub type Voting<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, Voter<T::AccountId, BalanceOf<T>>, ValueQuery>;
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config> {
pub members: Vec<(T::AccountId, BalanceOf<T>)>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
assert!(
self.members.len() as u32 <= T::DesiredMembers::get(),
"Cannot accept more than DesiredMembers genesis member",
);
let members = self
.members
.iter()
.map(|(ref member, ref stake)| {
// make sure they have enough stake.
assert!(
T::Currency::free_balance(member) >= *stake,
"Genesis member does not have enough stake.",
);
// Note: all members will only vote for themselves, hence they must be given
// exactly their own stake as total backing. Any sane election should behave as
// such. Nonetheless, stakes will be updated for term 1 onwards according to the
// election.
Members::<T>::mutate(|members| {
match members.binary_search_by(|m| m.who.cmp(member)) {
Ok(_) => {
panic!(
"Duplicate member in elections-phragmen genesis: {:?}",
member
)
},
Err(pos) => members.insert(
pos,
SeatHolder {
who: member.clone(),
stake: *stake,
deposit: Zero::zero(),
},
),
}
});
// set self-votes to make persistent. Genesis voters don't have any bond, nor do
// they have any lock. NOTE: this means that we will still try to remove a lock
// once this genesis voter is removed, and for now it is okay because
// remove_lock is noop if lock is not there.
<Voting<T>>::insert(
&member,
Voter { votes: vec![member.clone()], stake: *stake, deposit: Zero::zero() },
);
member.clone()
})
.collect::<Vec<T::AccountId>>();
// report genesis members to upstream, if any.
T::InitializeMembers::initialize_members(&members);
}
}
}
impl<T: Config> Pallet<T> {
/// The deposit value of `count` votes.
fn deposit_of(count: usize) -> BalanceOf<T> {
T::VotingBondBase::get()
.saturating_add(T::VotingBondFactor::get().saturating_mul((count as u32).into()))
}
/// Attempts to remove a member `who`. If a runner-up exists, it is used as the replacement.
///
/// Returns:
///
/// - `Ok(true)` if the member was removed and a replacement was found.
/// - `Ok(false)` if the member was removed and but no replacement was found.
/// - `Err(_)` if the member was no found.
///
/// Both `Members` and `RunnersUp` storage is updated accordingly. `T::ChangeMember` is called
/// if needed. If `slash` is true, the deposit of the potentially removed member is slashed,
/// else, it is unreserved.
///
/// ### Note: Prime preservation
///
/// This function attempts to preserve the prime. If the removed members is not the prime, it is
/// set again via [`Config::ChangeMembers`].
fn remove_and_replace_member(who: &T::AccountId, slash: bool) -> Result<bool, DispatchError> {
// closure will return:
// - `Ok(Option(replacement))` if member was removed and replacement was replaced.
// - `Ok(None)` if member was removed but no replacement was found
// - `Err(_)` if who is not a member.
let maybe_replacement = <Members<T>>::try_mutate::<_, Error<T>, _>(|members| {
let remove_index = members
.binary_search_by(|m| m.who.cmp(who))
.map_err(|_| Error::<T>::NotMember)?;
// we remove the member anyhow, regardless of having a runner-up or not.
let removed = members.remove(remove_index);
// slash or unreserve
if slash {
let (imbalance, _remainder) = T::Currency::slash_reserved(who, removed.deposit);
debug_assert!(_remainder.is_zero());
T::LoserCandidate::on_unbalanced(imbalance);
Self::deposit_event(Event::SeatHolderSlashed {
seat_holder: who.clone(),
amount: removed.deposit,
});
} else {
T::Currency::unreserve(who, removed.deposit);
}
let maybe_next_best = <RunnersUp<T>>::mutate(|r| r.pop()).map(|next_best| {
// defensive-only: Members and runners-up are disjoint. This will always be err and
// give us an index to insert.
if let Err(index) = members.binary_search_by(|m| m.who.cmp(&next_best.who)) {
members.insert(index, next_best.clone());
} else {
// overlap. This can never happen. If so, it seems like our intended replacement
// is already a member, so not much more to do.
log::error!(target: LOG_TARGET, "A member seems to also be a runner-up.");
}
next_best
});
Ok(maybe_next_best)
})?;
let remaining_member_ids_sorted =
Self::members().into_iter().map(|x| x.who).collect::<Vec<_>>();
let outgoing = &[who.clone()];
let maybe_current_prime = T::ChangeMembers::get_prime();
let return_value = match maybe_replacement {
// member ids are already sorted, other two elements have one item.
Some(incoming) => {
T::ChangeMembers::change_members_sorted(
&[incoming.who],
outgoing,
&remaining_member_ids_sorted[..],
);
true
},
None => {
T::ChangeMembers::change_members_sorted(
&[],
outgoing,
&remaining_member_ids_sorted[..],
);
false
},
};
// if there was a prime before and they are not the one being removed, then set them
// again.
if let Some(current_prime) = maybe_current_prime {
if ¤t_prime != who {
T::ChangeMembers::set_prime(Some(current_prime));
}
}
Ok(return_value)
}
/// Check if `who` is a candidate. It returns the insert index if the element does not exists as
/// an error.
fn is_candidate(who: &T::AccountId) -> Result<(), usize> {
Self::candidates().binary_search_by(|c| c.0.cmp(who)).map(|_| ())
}
/// Check if `who` is a voter. It may or may not be a _current_ one.
fn is_voter(who: &T::AccountId) -> bool {
Voting::<T>::contains_key(who)
}
/// Check if `who` is currently an active member.
fn is_member(who: &T::AccountId) -> bool {
Self::members().binary_search_by(|m| m.who.cmp(who)).is_ok()
}
/// Check if `who` is currently an active runner-up.
fn is_runner_up(who: &T::AccountId) -> bool {
Self::runners_up().iter().any(|r| &r.who == who)
}
/// Get the members' account ids.
pub(crate) fn members_ids() -> Vec<T::AccountId> {
Self::members().into_iter().map(|m| m.who).collect::<Vec<T::AccountId>>()
}
/// Get a concatenation of previous members and runners-up and their deposits.
///
/// These accounts are essentially treated as candidates.
fn implicit_candidates_with_deposit() -> Vec<(T::AccountId, BalanceOf<T>)> {
// invariant: these two are always without duplicates.
Self::members()
.into_iter()
.map(|m| (m.who, m.deposit))
.chain(Self::runners_up().into_iter().map(|r| (r.who, r.deposit)))
.collect::<Vec<_>>()
}
/// Check if `votes` will correspond to a defunct voter. As no origin is part of the inputs,
/// this function does not check the origin at all.
///
/// O(NLogM) with M candidates and `who` having voted for `N` of them.
/// Reads Members, RunnersUp, Candidates and Voting(who) from database.
fn is_defunct_voter(votes: &[T::AccountId]) -> bool {
votes.iter().all(|v| {
!Self::is_member(v) && !Self::is_runner_up(v) && Self::is_candidate(v).is_err()
})
}
/// Remove a certain someone as a voter.
fn do_remove_voter(who: &T::AccountId) {
let Voter { deposit, .. } = <Voting<T>>::take(who);
// remove storage, lock and unreserve.
T::Currency::remove_lock(T::PalletId::get(), who);
// NOTE: we could check the deposit amount before removing and skip if zero, but it will be
// a noop anyhow.
let _remainder = T::Currency::unreserve(who, deposit);
debug_assert!(_remainder.is_zero());
}
/// Run the phragmen election with all required side processes and state updates, if election
/// succeeds. Else, it will emit an `ElectionError` event.
///
/// Calls the appropriate [`ChangeMembers`] function variant internally.
fn do_phragmen() -> Weight {
let desired_seats = T::DesiredMembers::get() as usize;
let desired_runners_up = T::DesiredRunnersUp::get() as usize;
let num_to_elect = desired_runners_up + desired_seats;
let mut candidates_and_deposit = Self::candidates();
// add all the previous members and runners-up as candidates as well.
candidates_and_deposit.append(&mut Self::implicit_candidates_with_deposit());
if candidates_and_deposit.len().is_zero() {
Self::deposit_event(Event::EmptyTerm);
return T::DbWeight::get().reads(3)
}
// All of the new winners that come out of phragmen will thus have a deposit recorded.
let candidate_ids =
candidates_and_deposit.iter().map(|(x, _)| x).cloned().collect::<Vec<_>>();
// helper closures to deal with balance/stake.
let total_issuance = T::Currency::total_issuance();
let to_votes = |b: BalanceOf<T>| T::CurrencyToVote::to_vote(b, total_issuance);
let to_balance = |e: ExtendedBalance| T::CurrencyToVote::to_currency(e, total_issuance);
let mut num_edges: u32 = 0;
let max_voters = <T as Config>::MaxVoters::get() as usize;
// used for prime election.
let mut voters_and_stakes = Vec::new();
match Voting::<T>::iter().try_for_each(|(voter, Voter { stake, votes, .. })| {
if voters_and_stakes.len() < max_voters {
voters_and_stakes.push((voter, stake, votes));
Ok(())
} else {
Err(())
}
}) {
Ok(_) => (),
Err(_) => {
log::error!(
target: LOG_TARGET,
"Failed to run election. Number of voters exceeded",
);
Self::deposit_event(Event::ElectionError);
return T::DbWeight::get().reads(3 + max_voters as u64)
},
}
// used for phragmen.
let voters_and_votes = voters_and_stakes
.iter()
.cloned()
.map(|(voter, stake, votes)| {
num_edges = num_edges.saturating_add(votes.len() as u32);
(voter, to_votes(stake), votes)