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
2035 lines (1854 loc) · 74.6 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.
//! # Society Pallet
//!
//! - [`Config`]
//! - [`Call`]
//!
//! ## Overview
//!
//! The Society pallet is an economic game which incentivizes users to participate
//! and maintain a membership society.
//!
//! ### User Types
//!
//! At any point, a user in the society can be one of a:
//! * Bidder - A user who has submitted intention of joining the society.
//! * Candidate - A user who will be voted on to join the society.
//! * Member - A user who is a member of the society.
//! * Suspended Member - A member of the society who has accumulated too many strikes
//! or failed their membership challenge.
//!
//! Of the non-suspended members, there is always a:
//! * Head - A member who is exempt from suspension.
//! * Defender - A member whose membership is under question and voted on again.
//!
//! Of the non-suspended members of the society, a random set of them are chosen as
//! "skeptics". The mechanics of skeptics is explained in the
//! [member phase](#member-phase) below.
//!
//! ### Mechanics
//!
//! #### Rewards
//!
//! Members are incentivized to participate in the society through rewards paid
//! by the Society treasury. These payments have a maturity period that the user
//! must wait before they are able to access the funds.
//!
//! #### Punishments
//!
//! Members can be punished by slashing the reward payouts that have not been
//! collected. Additionally, members can accumulate "strikes", and when they
//! reach a max strike limit, they become suspended.
//!
//! #### Skeptics
//!
//! During the voting period, a random set of members are selected as "skeptics".
//! These skeptics are expected to vote on the current candidates. If they do not vote,
//! their skeptic status is treated as a rejection vote, the member is deemed
//! "lazy", and are given a strike per missing vote.
//!
//! #### Membership Challenges
//!
//! Every challenge rotation period, an existing member will be randomly selected
//! to defend their membership into society. Then, other members can vote whether
//! this defender should stay in society. A simple majority wins vote will determine
//! the outcome of the user. Ties are treated as a failure of the challenge, but
//! assuming no one else votes, the defender always get a free vote on their
//! own challenge keeping them in the society. The Head member is exempt from the
//! negative outcome of a membership challenge.
//!
//! #### Society Treasury
//!
//! The membership society is independently funded by a treasury managed by this
//! pallet. Some subset of this treasury is placed in a Society Pot, which is used
//! to determine the number of accepted bids.
//!
//! #### Rate of Growth
//!
//! The membership society can grow at a rate of 10 accepted candidates per rotation period up
//! to the max membership threshold. Once this threshold is met, candidate selections
//! are stalled until there is space for new members to join. This can be resolved by
//! voting out existing members through the random challenges or by using governance
//! to increase the maximum membership count.
//!
//! ### User Life Cycle
//!
//! A user can go through the following phases:
//!
//! ```ignore
//! +-------> User <----------+
//! | + |
//! | | |
//! +----------------------------------------------+
//! | | | | |
//! | | v | |
//! | | Bidder <-----------+ |
//! | | + | |
//! | | | + |
//! | | v Suspended |
//! | | Candidate +----> Candidate |
//! | | + + |
//! | | | | |
//! | + | | |
//! | Suspended +------>| | |
//! | Member | | |
//! | ^ | | |
//! | | v | |
//! | +-------+ Member <----------+ |
//! | |
//! | |
//! +------------------Society---------------------+
//! ```
//!
//! #### Initialization
//!
//! The society is initialized with a single member who is automatically chosen as the Head.
//!
//! #### Bid Phase
//!
//! New users must have a bid to join the society.
//!
//! A user can make a bid by reserving a deposit. Alternatively, an already existing member
//! can create a bid on a user's behalf by "vouching" for them.
//!
//! A bid includes reward information that the user would like to receive for joining
//! the society. A vouching bid can additionally request some portion of that reward as a tip
//! to the voucher for vouching for the prospective candidate.
//!
//! Every rotation period, Bids are ordered by reward amount, and the pallet
//! selects as many bids the Society Pot can support for that period.
//!
//! These selected bids become candidates and move on to the Candidate phase.
//! Bids that were not selected stay in the bidder pool until they are selected or
//! a user chooses to "unbid".
//!
//! #### Candidate Phase
//!
//! Once a bidder becomes a candidate, members vote whether to approve or reject
//! that candidate into society. This voting process also happens during a rotation period.
//!
//! The approval and rejection criteria for candidates are not set on chain,
//! and may change for different societies.
//!
//! At the end of the rotation period, we collect the votes for a candidate
//! and randomly select a vote as the final outcome.
//!
//! ```ignore
//! [ a-accept, r-reject, s-skeptic ]
//! +----------------------------------+
//! | |
//! | Member |0|1|2|3|4|5|6|7|8|9| |
//! | ----------------------------- |
//! | Vote |a|a|a|r|s|r|a|a|s|a| |
//! | ----------------------------- |
//! | Selected | | | |x| | | | | | | |
//! | |
//! +----------------------------------+
//!
//! Result: Rejected
//! ```
//!
//! Each member that voted opposite to this randomly selected vote is punished by
//! slashing their unclaimed payouts and increasing the number of strikes they have.
//!
//! These slashed funds are given to a random user who voted the same as the
//! selected vote as a reward for participating in the vote.
//!
//! If the candidate wins the vote, they receive their bid reward as a future payout.
//! If the bid was placed by a voucher, they will receive their portion of the reward,
//! before the rest is paid to the winning candidate.
//!
//! One winning candidate is selected as the Head of the members. This is randomly
//! chosen, weighted by the number of approvals the winning candidates accumulated.
//!
//! If the candidate loses the vote, they are suspended and it is up to the Suspension
//! Judgement origin to determine if the candidate should go through the bidding process
//! again, should be accepted into the membership society, or rejected and their deposit
//! slashed.
//!
//! #### Member Phase
//!
//! Once a candidate becomes a member, their role is to participate in society.
//!
//! Regular participation involves voting on candidates who want to join the membership
//! society, and by voting in the right way, a member will accumulate future payouts.
//! When a payout matures, members are able to claim those payouts.
//!
//! Members can also vouch for users to join the society, and request a "tip" from
//! the fees the new member would collect by joining the society. This vouching
//! process is useful in situations where a user may not have enough balance to
//! satisfy the bid deposit. A member can only vouch one user at a time.
//!
//! During rotation periods, a random group of members are selected as "skeptics".
//! These skeptics are expected to vote on the current candidates. If they do not vote,
//! their skeptic status is treated as a rejection vote, the member is deemed
//! "lazy", and are given a strike per missing vote.
//!
//! There is a challenge period in parallel to the rotation period. During a challenge period,
//! a random member is selected to defend their membership to the society. Other members
//! make a traditional majority-wins vote to determine if the member should stay in the society.
//! Ties are treated as a failure of the challenge.
//!
//! If a member accumulates too many strikes or fails their membership challenge,
//! they will become suspended. While a member is suspended, they are unable to
//! claim matured payouts. It is up to the Suspension Judgement origin to determine
//! if the member should re-enter society or be removed from society with all their
//! future payouts slashed.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! #### For General Users
//!
//! * `bid` - A user can make a bid to join the membership society by reserving a deposit.
//! * `unbid` - A user can withdraw their bid for entry, the deposit is returned.
//!
//! #### For Members
//!
//! * `vouch` - A member can place a bid on behalf of a user to join the membership society.
//! * `unvouch` - A member can revoke their vouch for a user.
//! * `vote` - A member can vote to approve or reject a candidate's request to join the society.
//! * `defender_vote` - A member can vote to approve or reject a defender's continued membership
//! to the society.
//! * `payout` - A member can claim their first matured payment.
//! * `unfound` - Allow the founder to unfound the society when they are the only member.
//!
//! #### For Super Users
//!
//! * `found` - The founder origin can initiate this society. Useful for bootstrapping the Society
//! pallet on an already running chain.
//! * `judge_suspended_member` - The suspension judgement origin is able to make
//! judgement on a suspended member.
//! * `judge_suspended_candidate` - The suspension judgement origin is able to
//! make judgement on a suspended candidate.
//! * `set_max_membership` - The ROOT origin can update the maximum member count for the society.
//! The max membership count must be greater than 1.
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub mod weights;
pub mod migrations;
use frame_support::{
impl_ensure_origin_with_arg_ignoring_arg,
pallet_prelude::*,
storage::KeyLenOf,
traits::{
BalanceStatus, Currency, EnsureOrigin, EnsureOriginWithArg,
ExistenceRequirement::AllowDeath, Imbalance, OnUnbalanced, Randomness, ReservableCurrency,
StorageVersion,
},
PalletId,
};
use frame_system::pallet_prelude::*;
use rand_chacha::{
rand_core::{RngCore, SeedableRng},
ChaChaRng,
};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{
AccountIdConversion, CheckedAdd, CheckedSub, Hash, Saturating, StaticLookup,
TrailingZeroInput, Zero,
},
ArithmeticError::Overflow,
Percent, RuntimeDebug,
};
use sp_std::prelude::*;
pub use weights::WeightInfo;
pub use pallet::*;
type BalanceOf<T, I> =
<<T as Config<I>>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type NegativeImbalanceOf<T, I> = <<T as Config<I>>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Vote {
approve: bool,
weight: u32,
}
/// A judgement by the suspension judgement origin on a suspended candidate.
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum Judgement {
/// The suspension judgement origin takes no direct judgment
/// and places the candidate back into the bid pool.
Rebid,
/// The suspension judgement origin has rejected the candidate's application.
Reject,
/// The suspension judgement origin approves of the candidate's application.
Approve,
}
/// Details of a payout given as a per-block linear "trickle".
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, Default, TypeInfo)]
pub struct Payout<Balance, BlockNumber> {
/// Total value of the payout.
value: Balance,
/// Block number at which the payout begins.
begin: BlockNumber,
/// Total number of blocks over which the payout is spread.
duration: BlockNumber,
/// Total value paid out so far.
paid: Balance,
}
/// Status of a vouching member.
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum VouchingStatus {
/// Member is currently vouching for a user.
Vouching,
/// Member is banned from vouching for other members.
Banned,
}
/// Number of strikes that a member has against them.
pub type StrikeCount = u32;
/// A bid for entry into society.
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Bid<AccountId, Balance> {
/// The bidder/candidate trying to enter society
who: AccountId,
/// The kind of bid placed for this bidder/candidate. See `BidKind`.
kind: BidKind<AccountId, Balance>,
/// The reward that the bidder has requested for successfully joining the society.
value: Balance,
}
/// The index of a round of candidates.
pub type RoundIndex = u32;
/// The rank of a member.
pub type Rank = u32;
/// The number of votes.
pub type VoteCount = u32;
/// Tally of votes.
#[derive(Default, Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Tally {
/// The approval votes.
approvals: VoteCount,
/// The rejection votes.
rejections: VoteCount,
}
impl Tally {
fn more_approvals(&self) -> bool {
self.approvals > self.rejections
}
fn more_rejections(&self) -> bool {
self.rejections > self.approvals
}
fn clear_approval(&self) -> bool {
self.approvals >= (2 * self.rejections).max(1)
}
fn clear_rejection(&self) -> bool {
self.rejections >= (2 * self.approvals).max(1)
}
}
/// A bid for entry into society.
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Candidacy<AccountId, Balance> {
/// The index of the round where the candidacy began.
round: RoundIndex,
/// The kind of bid placed for this bidder/candidate. See `BidKind`.
kind: BidKind<AccountId, Balance>,
/// The reward that the bidder has requested for successfully joining the society.
bid: Balance,
/// The tally of votes so far.
tally: Tally,
/// True if the skeptic was already punished for note voting.
skeptic_struck: bool,
}
/// A vote by a member on a candidate application.
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum BidKind<AccountId, Balance> {
/// The given deposit was paid for this bid.
Deposit(Balance),
/// A member vouched for this bid. The account should be reinstated into `Members` once the
/// bid is successful (or if it is rescinded prior to launch).
Vouch(AccountId, Balance),
}
impl<AccountId: PartialEq, Balance> BidKind<AccountId, Balance> {
fn is_vouch(&self, v: &AccountId) -> bool {
matches!(self, BidKind::Vouch(ref a, _) if a == v)
}
}
pub type PayoutsFor<T, I> =
BoundedVec<(BlockNumberFor<T>, BalanceOf<T, I>), <T as Config<I>>::MaxPayouts>;
/// Information concerning a member.
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct MemberRecord {
rank: Rank,
strikes: StrikeCount,
vouching: Option<VouchingStatus>,
index: u32,
}
/// Information concerning a member.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, Default)]
pub struct PayoutRecord<Balance, PayoutsVec> {
paid: Balance,
payouts: PayoutsVec,
}
pub type PayoutRecordFor<T, I> = PayoutRecord<
BalanceOf<T, I>,
BoundedVec<(BlockNumberFor<T>, BalanceOf<T, I>), <T as Config<I>>::MaxPayouts>,
>;
/// Record for an individual new member who was elevated from a candidate recently.
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct IntakeRecord<AccountId, Balance> {
who: AccountId,
bid: Balance,
round: RoundIndex,
}
pub type IntakeRecordFor<T, I> =
IntakeRecord<<T as frame_system::Config>::AccountId, BalanceOf<T, I>>;
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct GroupParams<Balance> {
max_members: u32,
max_intake: u32,
max_strikes: u32,
candidate_deposit: Balance,
}
pub type GroupParamsFor<T, I> = GroupParams<BalanceOf<T, I>>;
pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T, I = ()>(_);
#[pallet::config]
pub trait Config<I: 'static = ()>: frame_system::Config {
/// The overarching event type.
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The societies's pallet id
#[pallet::constant]
type PalletId: Get<PalletId>;
/// The currency type used for bidding.
type Currency: ReservableCurrency<Self::AccountId>;
/// Something that provides randomness in the runtime.
type Randomness: Randomness<Self::Hash, BlockNumberFor<Self>>;
/// The maximum number of strikes before a member gets funds slashed.
#[pallet::constant]
type GraceStrikes: Get<u32>;
/// The amount of incentive paid within each period. Doesn't include VoterTip.
#[pallet::constant]
type PeriodSpend: Get<BalanceOf<Self, I>>;
/// The number of blocks on which new candidates should be voted on. Together with
/// `ClaimPeriod`, this sums to the number of blocks between candidate intake periods.
#[pallet::constant]
type VotingPeriod: Get<BlockNumberFor<Self>>;
/// The number of blocks on which new candidates can claim their membership and be the
/// named head.
#[pallet::constant]
type ClaimPeriod: Get<BlockNumberFor<Self>>;
/// The maximum duration of the payout lock.
#[pallet::constant]
type MaxLockDuration: Get<BlockNumberFor<Self>>;
/// The origin that is allowed to call `found`.
type FounderSetOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The number of blocks between membership challenges.
#[pallet::constant]
type ChallengePeriod: Get<BlockNumberFor<Self>>;
/// The maximum number of payouts a member may have waiting unclaimed.
#[pallet::constant]
type MaxPayouts: Get<u32>;
/// The maximum number of bids at once.
#[pallet::constant]
type MaxBids: Get<u32>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}
#[pallet::error]
pub enum Error<T, I = ()> {
/// User is not a member.
NotMember,
/// User is already a member.
AlreadyMember,
/// User is suspended.
Suspended,
/// User is not suspended.
NotSuspended,
/// Nothing to payout.
NoPayout,
/// Society already founded.
AlreadyFounded,
/// Not enough in pot to accept candidate.
InsufficientPot,
/// Member is already vouching or banned from vouching again.
AlreadyVouching,
/// Member is not vouching.
NotVouchingOnBidder,
/// Cannot remove the head of the chain.
Head,
/// Cannot remove the founder.
Founder,
/// User has already made a bid.
AlreadyBid,
/// User is already a candidate.
AlreadyCandidate,
/// User is not a candidate.
NotCandidate,
/// Too many members in the society.
MaxMembers,
/// The caller is not the founder.
NotFounder,
/// The caller is not the head.
NotHead,
/// The membership cannot be claimed as the candidate was not clearly approved.
NotApproved,
/// The candidate cannot be kicked as the candidate was not clearly rejected.
NotRejected,
/// The candidacy cannot be dropped as the candidate was clearly approved.
Approved,
/// The candidacy cannot be bestowed as the candidate was clearly rejected.
Rejected,
/// The candidacy cannot be concluded as the voting is still in progress.
InProgress,
/// The candidacy cannot be pruned until a full additional intake period has passed.
TooEarly,
/// The skeptic already voted.
Voted,
/// The skeptic need not vote on candidates from expired rounds.
Expired,
/// User is not a bidder.
NotBidder,
/// There is no defender currently.
NoDefender,
/// Group doesn't exist.
NotGroup,
/// The member is already elevated to this rank.
AlreadyElevated,
/// The skeptic has already been punished for this offence.
AlreadyPunished,
/// Funds are insufficient to pay off society debts.
InsufficientFunds,
/// The candidate/defender has no stale votes to remove.
NoVotes,
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// The society is founded by the given identity.
Founded { founder: T::AccountId },
/// A membership bid just happened. The given account is the candidate's ID and their offer
/// is the second.
Bid { candidate_id: T::AccountId, offer: BalanceOf<T, I> },
/// A membership bid just happened by vouching. The given account is the candidate's ID and
/// their offer is the second. The vouching party is the third.
Vouch { candidate_id: T::AccountId, offer: BalanceOf<T, I>, vouching: T::AccountId },
/// A candidate was dropped (due to an excess of bids in the system).
AutoUnbid { candidate: T::AccountId },
/// A candidate was dropped (by their request).
Unbid { candidate: T::AccountId },
/// A candidate was dropped (by request of who vouched for them).
Unvouch { candidate: T::AccountId },
/// A group of candidates have been inducted. The batch's primary is the first value, the
/// batch in full is the second.
Inducted { primary: T::AccountId, candidates: Vec<T::AccountId> },
/// A suspended member has been judged.
SuspendedMemberJudgement { who: T::AccountId, judged: bool },
/// A candidate has been suspended
CandidateSuspended { candidate: T::AccountId },
/// A member has been suspended
MemberSuspended { member: T::AccountId },
/// A member has been challenged
Challenged { member: T::AccountId },
/// A vote has been placed
Vote { candidate: T::AccountId, voter: T::AccountId, vote: bool },
/// A vote has been placed for a defending member
DefenderVote { voter: T::AccountId, vote: bool },
/// A new set of \[params\] has been set for the group.
NewParams { params: GroupParamsFor<T, I> },
/// Society is unfounded.
Unfounded { founder: T::AccountId },
/// Some funds were deposited into the society account.
Deposit { value: BalanceOf<T, I> },
/// A \[member\] got elevated to \[rank\].
Elevated { member: T::AccountId, rank: Rank },
}
/// Old name generated by `decl_event`.
#[deprecated(note = "use `Event` instead")]
pub type RawEvent<T, I = ()> = Event<T, I>;
/// The max number of members for the society at one time.
#[pallet::storage]
pub(super) type Parameters<T: Config<I>, I: 'static = ()> =
StorageValue<_, GroupParamsFor<T, I>, OptionQuery>;
/// Amount of our account balance that is specifically for the next round's bid(s).
#[pallet::storage]
pub type Pot<T: Config<I>, I: 'static = ()> = StorageValue<_, BalanceOf<T, I>, ValueQuery>;
/// The first member.
#[pallet::storage]
pub type Founder<T: Config<I>, I: 'static = ()> = StorageValue<_, T::AccountId>;
/// The most primary from the most recently approved rank 0 members in the society.
#[pallet::storage]
pub type Head<T: Config<I>, I: 'static = ()> = StorageValue<_, T::AccountId>;
/// A hash of the rules of this society concerning membership. Can only be set once and
/// only by the founder.
#[pallet::storage]
pub type Rules<T: Config<I>, I: 'static = ()> = StorageValue<_, T::Hash>;
/// The current members and their rank. Doesn't include `SuspendedMembers`.
#[pallet::storage]
pub type Members<T: Config<I>, I: 'static = ()> =
StorageMap<_, Twox64Concat, T::AccountId, MemberRecord, OptionQuery>;
/// Information regarding rank-0 payouts, past and future.
#[pallet::storage]
pub type Payouts<T: Config<I>, I: 'static = ()> =
StorageMap<_, Twox64Concat, T::AccountId, PayoutRecordFor<T, I>, ValueQuery>;
/// The number of items in `Members` currently. (Doesn't include `SuspendedMembers`.)
#[pallet::storage]
pub type MemberCount<T: Config<I>, I: 'static = ()> = StorageValue<_, u32, ValueQuery>;
/// The current items in `Members` keyed by their unique index. Keys are densely populated
/// `0..MemberCount` (does not include `MemberCount`).
#[pallet::storage]
pub type MemberByIndex<T: Config<I>, I: 'static = ()> =
StorageMap<_, Twox64Concat, u32, T::AccountId, OptionQuery>;
/// The set of suspended members, with their old membership record.
#[pallet::storage]
pub type SuspendedMembers<T: Config<I>, I: 'static = ()> =
StorageMap<_, Twox64Concat, T::AccountId, MemberRecord, OptionQuery>;
/// The number of rounds which have passed.
#[pallet::storage]
pub type RoundCount<T: Config<I>, I: 'static = ()> = StorageValue<_, RoundIndex, ValueQuery>;
/// The current bids, stored ordered by the value of the bid.
#[pallet::storage]
pub(super) type Bids<T: Config<I>, I: 'static = ()> =
StorageValue<_, BoundedVec<Bid<T::AccountId, BalanceOf<T, I>>, T::MaxBids>, ValueQuery>;
#[pallet::storage]
pub type Candidates<T: Config<I>, I: 'static = ()> = StorageMap<
_,
Blake2_128Concat,
T::AccountId,
Candidacy<T::AccountId, BalanceOf<T, I>>,
OptionQuery,
>;
/// The current skeptic.
#[pallet::storage]
pub type Skeptic<T: Config<I>, I: 'static = ()> = StorageValue<_, T::AccountId, OptionQuery>;
/// Double map from Candidate -> Voter -> (Maybe) Vote.
#[pallet::storage]
pub(super) type Votes<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Twox64Concat,
T::AccountId,
Twox64Concat,
T::AccountId,
Vote,
OptionQuery,
>;
/// Clear-cursor for Vote, map from Candidate -> (Maybe) Cursor.
#[pallet::storage]
pub(super) type VoteClearCursor<T: Config<I>, I: 'static = ()> =
StorageMap<_, Twox64Concat, T::AccountId, BoundedVec<u8, KeyLenOf<Votes<T, I>>>>;
/// At the end of the claim period, this contains the most recently approved members (along with
/// their bid and round ID) who is from the most recent round with the lowest bid. They will
/// become the new `Head`.
#[pallet::storage]
pub type NextHead<T: Config<I>, I: 'static = ()> =
StorageValue<_, IntakeRecordFor<T, I>, OptionQuery>;
/// The number of challenge rounds there have been. Used to identify stale DefenderVotes.
#[pallet::storage]
pub(super) type ChallengeRoundCount<T: Config<I>, I: 'static = ()> =
StorageValue<_, RoundIndex, ValueQuery>;
/// The defending member currently being challenged, along with a running tally of votes.
#[pallet::storage]
pub(super) type Defending<T: Config<I>, I: 'static = ()> =
StorageValue<_, (T::AccountId, T::AccountId, Tally)>;
/// Votes for the defender, keyed by challenge round.
#[pallet::storage]
pub(super) type DefenderVotes<T: Config<I>, I: 'static = ()> =
StorageDoubleMap<_, Twox64Concat, RoundIndex, Twox64Concat, T::AccountId, Vote>;
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
fn on_initialize(n: BlockNumberFor<T>) -> Weight {
let mut weight = Weight::zero();
let weights = T::BlockWeights::get();
let phrase = b"society_rotation";
// we'll need a random seed here.
// TODO: deal with randomness freshness
// https://github.com/paritytech/substrate/issues/8312
let (seed, _) = T::Randomness::random(phrase);
// seed needs to be guaranteed to be 32 bytes.
let seed = <[u8; 32]>::decode(&mut TrailingZeroInput::new(seed.as_ref()))
.expect("input is padded with zeroes; qed");
let mut rng = ChaChaRng::from_seed(seed);
// Run a candidate/membership rotation
match Self::period() {
Period::Voting { elapsed, .. } if elapsed.is_zero() => {
Self::rotate_intake(&mut rng);
weight.saturating_accrue(weights.max_block / 20);
},
_ => {},
}
// Run a challenge rotation
if (n % T::ChallengePeriod::get()).is_zero() {
Self::rotate_challenge(&mut rng);
weight.saturating_accrue(weights.max_block / 20);
}
weight
}
}
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
pub pot: BalanceOf<T, I>,
}
#[pallet::genesis_build]
impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
fn build(&self) {
Pot::<T, I>::put(self.pot);
}
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// A user outside of the society can make a bid for entry.
///
/// Payment: The group's Candidate Deposit will be reserved for making a bid. It is returned
/// when the bid becomes a member, or if the bid calls `unbid`.
///
/// The dispatch origin for this call must be _Signed_.
///
/// Parameters:
/// - `value`: A one time payment the bid would like to receive when joining the society.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::bid())]
pub fn bid(origin: OriginFor<T>, value: BalanceOf<T, I>) -> DispatchResult {
let who = ensure_signed(origin)?;
let mut bids = Bids::<T, I>::get();
ensure!(!Self::has_bid(&bids, &who), Error::<T, I>::AlreadyBid);
ensure!(!Candidates::<T, I>::contains_key(&who), Error::<T, I>::AlreadyCandidate);
ensure!(!Members::<T, I>::contains_key(&who), Error::<T, I>::AlreadyMember);
ensure!(!SuspendedMembers::<T, I>::contains_key(&who), Error::<T, I>::Suspended);
let params = Parameters::<T, I>::get().ok_or(Error::<T, I>::NotGroup)?;
let deposit = params.candidate_deposit;
// NOTE: Reserve must happen before `insert_bid` since that could end up unreserving.
T::Currency::reserve(&who, deposit)?;
Self::insert_bid(&mut bids, &who, value, BidKind::Deposit(deposit));
Bids::<T, I>::put(bids);
Self::deposit_event(Event::<T, I>::Bid { candidate_id: who, offer: value });
Ok(())
}
/// A bidder can remove their bid for entry into society.
/// By doing so, they will have their candidate deposit returned or
/// they will unvouch their voucher.
///
/// Payment: The bid deposit is unreserved if the user made a bid.
///
/// The dispatch origin for this call must be _Signed_ and a bidder.
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::unbid())]
pub fn unbid(origin: OriginFor<T>) -> DispatchResult {
let who = ensure_signed(origin)?;
let mut bids = Bids::<T, I>::get();
let pos = bids.iter().position(|bid| bid.who == who).ok_or(Error::<T, I>::NotBidder)?;
Self::clean_bid(&bids.remove(pos));
Bids::<T, I>::put(bids);
Self::deposit_event(Event::<T, I>::Unbid { candidate: who });
Ok(())
}
/// As a member, vouch for someone to join society by placing a bid on their behalf.
///
/// There is no deposit required to vouch for a new bid, but a member can only vouch for
/// one bid at a time. If the bid becomes a suspended candidate and ultimately rejected by
/// the suspension judgement origin, the member will be banned from vouching again.
///
/// As a vouching member, you can claim a tip if the candidate is accepted. This tip will
/// be paid as a portion of the reward the member will receive for joining the society.
///
/// The dispatch origin for this call must be _Signed_ and a member.
///
/// Parameters:
/// - `who`: The user who you would like to vouch for.
/// - `value`: The total reward to be paid between you and the candidate if they become
/// a member in the society.
/// - `tip`: Your cut of the total `value` payout when the candidate is inducted into
/// the society. Tips larger than `value` will be saturated upon payout.
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::vouch())]
pub fn vouch(
origin: OriginFor<T>,
who: AccountIdLookupOf<T>,
value: BalanceOf<T, I>,
tip: BalanceOf<T, I>,
) -> DispatchResult {
let voucher = ensure_signed(origin)?;
let who = T::Lookup::lookup(who)?;
// Get bids and check user is not bidding.
let mut bids = Bids::<T, I>::get();
ensure!(!Self::has_bid(&bids, &who), Error::<T, I>::AlreadyBid);
// Check user is not already a candidate, member or suspended member.
ensure!(!Candidates::<T, I>::contains_key(&who), Error::<T, I>::AlreadyCandidate);
ensure!(!Members::<T, I>::contains_key(&who), Error::<T, I>::AlreadyMember);
ensure!(!SuspendedMembers::<T, I>::contains_key(&who), Error::<T, I>::Suspended);
// Check sender can vouch.
let mut record = Members::<T, I>::get(&voucher).ok_or(Error::<T, I>::NotMember)?;
ensure!(record.vouching.is_none(), Error::<T, I>::AlreadyVouching);
// Update voucher record.
record.vouching = Some(VouchingStatus::Vouching);
// Update bids
Self::insert_bid(&mut bids, &who, value, BidKind::Vouch(voucher.clone(), tip));
// Write new state.
Members::<T, I>::insert(&voucher, &record);
Bids::<T, I>::put(bids);
Self::deposit_event(Event::<T, I>::Vouch {
candidate_id: who,
offer: value,
vouching: voucher,
});
Ok(())
}
/// As a vouching member, unvouch a bid. This only works while vouched user is
/// only a bidder (and not a candidate).
///
/// The dispatch origin for this call must be _Signed_ and a vouching member.
///
/// Parameters:
/// - `pos`: Position in the `Bids` vector of the bid who should be unvouched.
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::unvouch())]
pub fn unvouch(origin: OriginFor<T>) -> DispatchResult {
let voucher = ensure_signed(origin)?;
let mut bids = Bids::<T, I>::get();
let pos = bids
.iter()
.position(|bid| bid.kind.is_vouch(&voucher))
.ok_or(Error::<T, I>::NotVouchingOnBidder)?;
let bid = bids.remove(pos);
Self::clean_bid(&bid);
Bids::<T, I>::put(bids);
Self::deposit_event(Event::<T, I>::Unvouch { candidate: bid.who });
Ok(())
}
/// As a member, vote on a candidate.
///
/// The dispatch origin for this call must be _Signed_ and a member.
///
/// Parameters:
/// - `candidate`: The candidate that the member would like to bid on.
/// - `approve`: A boolean which says if the candidate should be approved (`true`) or
/// rejected (`false`).
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::vote())]
pub fn vote(
origin: OriginFor<T>,
candidate: AccountIdLookupOf<T>,
approve: bool,
) -> DispatchResultWithPostInfo {
let voter = ensure_signed(origin)?;
let candidate = T::Lookup::lookup(candidate)?;
let mut candidacy =
Candidates::<T, I>::get(&candidate).ok_or(Error::<T, I>::NotCandidate)?;
let record = Members::<T, I>::get(&voter).ok_or(Error::<T, I>::NotMember)?;
let first_time = Votes::<T, I>::mutate(&candidate, &voter, |v| {
let first_time = v.is_none();
*v = Some(Self::do_vote(*v, approve, record.rank, &mut candidacy.tally));
first_time
});
Candidates::<T, I>::insert(&candidate, &candidacy);
Self::deposit_event(Event::<T, I>::Vote { candidate, voter, vote: approve });
Ok(if first_time { Pays::No } else { Pays::Yes }.into())
}
/// As a member, vote on the defender.
///
/// The dispatch origin for this call must be _Signed_ and a member.
///
/// Parameters:
/// - `approve`: A boolean which says if the candidate should be
/// approved (`true`) or rejected (`false`).
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::defender_vote())]
pub fn defender_vote(origin: OriginFor<T>, approve: bool) -> DispatchResultWithPostInfo {
let voter = ensure_signed(origin)?;
let mut defending = Defending::<T, I>::get().ok_or(Error::<T, I>::NoDefender)?;
let record = Members::<T, I>::get(&voter).ok_or(Error::<T, I>::NotMember)?;
let round = ChallengeRoundCount::<T, I>::get();
let first_time = DefenderVotes::<T, I>::mutate(round, &voter, |v| {
let first_time = v.is_none();
*v = Some(Self::do_vote(*v, approve, record.rank, &mut defending.2));
first_time
});
Defending::<T, I>::put(defending);
Self::deposit_event(Event::<T, I>::DefenderVote { voter, vote: approve });
Ok(if first_time { Pays::No } else { Pays::Yes }.into())
}
/// Transfer the first matured payout for the sender and remove it from the records.
///
/// NOTE: This extrinsic needs to be called multiple times to claim multiple matured
/// payouts.