frame_support/traits/voting.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Traits and associated data structures concerned with voting, and moving between tokens and
19//! votes.
20
21use crate::dispatch::Parameter;
22use alloc::vec::Vec;
23use codec::{HasCompact, MaxEncodedLen};
24use sp_arithmetic::Perbill;
25use sp_runtime::{traits::Member, DispatchError};
26
27pub trait VoteTally<Votes, Class> {
28 /// Initializes a new tally.
29 fn new(_: Class) -> Self;
30 /// Returns the number of positive votes for the tally.
31 fn ayes(&self, class: Class) -> Votes;
32 /// Returns the approval ratio (positive to total votes) for the tally, without multipliers
33 /// (e.g. conviction, ranks, etc.).
34 fn support(&self, class: Class) -> Perbill;
35 /// Returns the approval ratio (positive to total votes) for the tally.
36 fn approval(&self, class: Class) -> Perbill;
37 /// Returns an instance of the tally representing a unanimous approval, for benchmarking
38 /// purposes.
39 #[cfg(feature = "runtime-benchmarks")]
40 fn unanimity(class: Class) -> Self;
41 /// Returns an instance of the tally representing a rejecting state, for benchmarking purposes.
42 #[cfg(feature = "runtime-benchmarks")]
43 fn rejection(class: Class) -> Self;
44 /// Returns an instance of the tally given some `approval` and `support`, for benchmarking
45 /// purposes.
46 #[cfg(feature = "runtime-benchmarks")]
47 fn from_requirements(support: Perbill, approval: Perbill, class: Class) -> Self;
48 #[cfg(feature = "runtime-benchmarks")]
49 /// A function that should be called before any use of the `runtime-benchmarks` gated functions
50 /// of the `VoteTally` trait.
51 ///
52 /// Should be used to set up any needed state in a Pallet which implements `VoteTally` so that
53 /// benchmarks that execute will complete successfully. `class` can be used to set up a
54 /// particular class of voters, and `granularity` is used to determine the weight of one vote
55 /// relative to total unanimity.
56 ///
57 /// For example, in the case where there are a number of unique voters, and each voter has equal
58 /// voting weight, a granularity of `Perbill::from_rational(1, 1000)` should create `1_000`
59 /// users.
60 fn setup(class: Class, granularity: Perbill);
61}
62pub enum PollStatus<Tally, Moment, Class> {
63 None,
64 Ongoing(Tally, Class),
65 Completed(Moment, bool),
66}
67
68impl<Tally, Moment, Class> PollStatus<Tally, Moment, Class> {
69 pub fn ensure_ongoing(self) -> Option<(Tally, Class)> {
70 match self {
71 Self::Ongoing(t, c) => Some((t, c)),
72 _ => None,
73 }
74 }
75}
76
77pub struct ClassCountOf<P, T>(core::marker::PhantomData<(P, T)>);
78impl<T, P: Polling<T>> sp_runtime::traits::Get<u32> for ClassCountOf<P, T> {
79 fn get() -> u32 {
80 P::classes().len() as u32
81 }
82}
83
84pub trait Polling<Tally> {
85 type Index: Parameter + Member + Ord + PartialOrd + Copy + HasCompact + MaxEncodedLen;
86 type Votes: Parameter + Member + Ord + PartialOrd + Copy + HasCompact + MaxEncodedLen;
87 type Class: Parameter + Member + Ord + PartialOrd + MaxEncodedLen;
88 type Moment;
89
90 /// Provides a vec of values that `T` may take.
91 fn classes() -> Vec<Self::Class>;
92
93 /// `Some` if the referendum `index` can be voted on, along with the tally and class of
94 /// referendum.
95 ///
96 /// Don't use this if you might mutate - use `try_access_poll` instead.
97 fn as_ongoing(index: Self::Index) -> Option<(Tally, Self::Class)>;
98
99 fn access_poll<R>(
100 index: Self::Index,
101 f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> R,
102 ) -> R;
103
104 fn try_access_poll<R>(
105 index: Self::Index,
106 f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> Result<R, DispatchError>,
107 ) -> Result<R, DispatchError>;
108
109 /// Create an ongoing majority-carries poll of given class lasting given period for the purpose
110 /// of benchmarking.
111 ///
112 /// May return `Err` if it is impossible.
113 #[cfg(feature = "runtime-benchmarks")]
114 fn create_ongoing(class: Self::Class) -> Result<Self::Index, ()>;
115
116 /// End the given ongoing poll and return the result.
117 ///
118 /// Returns `Err` if `index` is not an ongoing poll.
119 #[cfg(feature = "runtime-benchmarks")]
120 fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()>;
121
122 /// The maximum amount of ongoing polls within any single class. By default it practically
123 /// unlimited (`u32::max_value()`).
124 #[cfg(feature = "runtime-benchmarks")]
125 fn max_ongoing() -> (Self::Class, u32) {
126 (Self::classes().into_iter().next().expect("Always one class"), u32::max_value())
127 }
128}