Skip to main content

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::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	///
37	/// If no votes have been cast (i.e. `ayes + nays == 0`), it should resolve to `0%`.
38	fn approval(&self, class: Class) -> Perbill;
39	/// Returns an instance of the tally representing a unanimous approval, for benchmarking
40	/// purposes.
41	#[cfg(feature = "runtime-benchmarks")]
42	fn unanimity(class: Class) -> Self;
43	/// Returns an instance of the tally representing a rejecting state, for benchmarking purposes.
44	#[cfg(feature = "runtime-benchmarks")]
45	fn rejection(class: Class) -> Self;
46	/// Returns an instance of the tally given some `approval` and `support`, for benchmarking
47	/// purposes.
48	#[cfg(feature = "runtime-benchmarks")]
49	fn from_requirements(support: Perbill, approval: Perbill, class: Class) -> Self;
50	#[cfg(feature = "runtime-benchmarks")]
51	/// A function that should be called before any use of the `runtime-benchmarks` gated functions
52	/// of the `VoteTally` trait.
53	///
54	/// Should be used to set up any needed state in a Pallet which implements `VoteTally` so that
55	/// benchmarks that execute will complete successfully. `class` can be used to set up a
56	/// particular class of voters, and `granularity` is used to determine the weight of one vote
57	/// relative to total unanimity.
58	///
59	/// For example, in the case where there are a number of unique voters, and each voter has equal
60	/// voting weight, a granularity of `Perbill::from_rational(1, 1000)` should create `1_000`
61	/// users.
62	fn setup(class: Class, granularity: Perbill);
63}
64pub enum PollStatus<Tally, Moment, Class> {
65	None,
66	Ongoing(Tally, Class),
67	Completed(Moment, bool),
68}
69
70impl<Tally, Moment, Class> PollStatus<Tally, Moment, Class> {
71	pub fn ensure_ongoing(self) -> Option<(Tally, Class)> {
72		match self {
73			Self::Ongoing(t, c) => Some((t, c)),
74			_ => None,
75		}
76	}
77}
78
79pub struct ClassCountOf<P, T>(core::marker::PhantomData<(P, T)>);
80impl<T, P: Polling<T>> sp_runtime::traits::Get<u32> for ClassCountOf<P, T> {
81	fn get() -> u32 {
82		P::classes().len() as u32
83	}
84}
85
86pub trait Polling<Tally> {
87	type Index: Parameter + Member + Ord + PartialOrd + Copy + HasCompact + MaxEncodedLen;
88	type Votes: Parameter + Member + Ord + PartialOrd + Copy + HasCompact + MaxEncodedLen;
89	type Class: Parameter + Member + Ord + PartialOrd + MaxEncodedLen;
90	type Moment;
91
92	/// Provides a vec of values that `T` may take.
93	fn classes() -> Vec<Self::Class>;
94
95	/// `Some` if the referendum `index` can be voted on, along with the tally and class of
96	/// referendum.
97	///
98	/// Don't use this if you might mutate - use `try_access_poll` instead.
99	fn as_ongoing(index: Self::Index) -> Option<(Tally, Self::Class)>;
100
101	fn access_poll<R>(
102		index: Self::Index,
103		f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> R,
104	) -> R;
105
106	fn try_access_poll<R>(
107		index: Self::Index,
108		f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> Result<R, DispatchError>,
109	) -> Result<R, DispatchError>;
110
111	/// Create an ongoing majority-carries poll of given class lasting given period for the purpose
112	/// of benchmarking.
113	///
114	/// May return `Err` if it is impossible.
115	#[cfg(feature = "runtime-benchmarks")]
116	fn create_ongoing(class: Self::Class) -> Result<Self::Index, ()>;
117
118	/// End the given ongoing poll and return the result.
119	///
120	/// Returns `Err` if `index` is not an ongoing poll.
121	#[cfg(feature = "runtime-benchmarks")]
122	fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()>;
123
124	/// The maximum amount of ongoing polls within any single class. By default it practically
125	/// unlimited (`u32::max_value()`).
126	#[cfg(feature = "runtime-benchmarks")]
127	fn max_ongoing() -> (Self::Class, u32) {
128		(Self::classes().into_iter().next().expect("Always one class"), u32::max_value())
129	}
130}
131
132/// NoOp polling is required if pallet-referenda functionality not needed.
133pub struct NoOpPoll;
134impl<Tally> Polling<Tally> for NoOpPoll {
135	type Index = u8;
136	type Votes = u32;
137	type Class = u16;
138	type Moment = u64;
139
140	fn classes() -> Vec<Self::Class> {
141		vec![]
142	}
143
144	fn as_ongoing(_index: Self::Index) -> Option<(Tally, Self::Class)> {
145		None
146	}
147
148	fn access_poll<R>(
149		_index: Self::Index,
150		f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> R,
151	) -> R {
152		f(PollStatus::None)
153	}
154
155	fn try_access_poll<R>(
156		_index: Self::Index,
157		f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> Result<R, DispatchError>,
158	) -> Result<R, DispatchError> {
159		f(PollStatus::None)
160	}
161
162	#[cfg(feature = "runtime-benchmarks")]
163	fn create_ongoing(_class: Self::Class) -> Result<Self::Index, ()> {
164		Err(())
165	}
166
167	#[cfg(feature = "runtime-benchmarks")]
168	fn end_ongoing(_index: Self::Index, _approved: bool) -> Result<(), ()> {
169		Err(())
170	}
171
172	#[cfg(feature = "runtime-benchmarks")]
173	fn max_ongoing() -> (Self::Class, u32) {
174		(0, 0)
175	}
176}