referrerpolicy=no-referrer-when-downgrade

pallet_conviction_voting/
vote.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//! The vote datatype.
19
20use crate::{Conviction, Delegations};
21use codec::{Decode, DecodeWithMemTracking, Encode, EncodeLike, Input, MaxEncodedLen, Output};
22use frame_support::{pallet_prelude::Get, BoundedVec};
23use scale_info::TypeInfo;
24use sp_runtime::{
25	traits::{Saturating, Zero},
26	Debug,
27};
28
29/// A number of lock periods, plus a vote, one way or the other.
30#[derive(DecodeWithMemTracking, Copy, Clone, Eq, PartialEq, Default, Debug, MaxEncodedLen)]
31pub struct Vote {
32	pub aye: bool,
33	pub conviction: Conviction,
34}
35
36impl Encode for Vote {
37	fn encode_to<T: Output + ?Sized>(&self, output: &mut T) {
38		output.push_byte(u8::from(self.conviction) | if self.aye { 0b1000_0000 } else { 0 });
39	}
40}
41
42impl EncodeLike for Vote {}
43
44impl Decode for Vote {
45	fn decode<I: Input>(input: &mut I) -> Result<Self, codec::Error> {
46		let b = input.read_byte()?;
47		Ok(Vote {
48			aye: (b & 0b1000_0000) == 0b1000_0000,
49			conviction: Conviction::try_from(b & 0b0111_1111)
50				.map_err(|_| codec::Error::from("Invalid conviction"))?,
51		})
52	}
53}
54
55impl TypeInfo for Vote {
56	type Identity = Self;
57
58	fn type_info() -> scale_info::Type {
59		scale_info::Type::builder()
60			.path(scale_info::Path::new("Vote", module_path!()))
61			.composite(
62				scale_info::build::Fields::unnamed()
63					.field(|f| f.ty::<u8>().docs(&["Raw vote byte, encodes aye + conviction"])),
64			)
65	}
66}
67
68/// A vote for a referendum of a particular account.
69#[derive(
70	Encode,
71	Decode,
72	DecodeWithMemTracking,
73	Copy,
74	Clone,
75	Eq,
76	PartialEq,
77	Debug,
78	TypeInfo,
79	MaxEncodedLen,
80)]
81pub enum AccountVote<Balance> {
82	/// A standard vote, one-way (approve or reject) with a given amount of conviction.
83	Standard { vote: Vote, balance: Balance },
84	/// A split vote with balances given for both ways, and with no conviction, useful for
85	/// parachains when voting.
86	Split { aye: Balance, nay: Balance },
87	/// A split vote with balances given for both ways as well as abstentions, and with no
88	/// conviction, useful for parachains when voting, other off-chain aggregate accounts and
89	/// individuals who wish to abstain.
90	SplitAbstain { aye: Balance, nay: Balance, abstain: Balance },
91}
92
93/// Present the conditions under which an account's Funds are locked after a voting action.
94#[derive(Copy, Clone, Eq, PartialEq, Debug)]
95pub enum LockedIf {
96	/// Lock the funds if the outcome of the referendum matches the voting behavior of the user.
97	///
98	/// `true` means they voted `aye` and `false` means `nay`.
99	Status(bool),
100	/// Always lock the funds.
101	Always,
102}
103
104impl<Balance: Saturating> AccountVote<Balance> {
105	/// Returns `Some` of the lock periods that the account is locked for, assuming that the
106	/// referendum passed if `approved` is `true`.
107	pub fn locked_if(self, approved: LockedIf) -> Option<(u32, Balance)> {
108		// winning side: can only be removed after the lock period ends.
109		match (self, approved) {
110			// If the vote has no conviction, always return None
111			(AccountVote::Standard { vote: Vote { conviction: Conviction::None, .. }, .. }, _) =>
112				None,
113
114			// For Standard votes, check the approval condition
115			(AccountVote::Standard { vote, balance }, LockedIf::Status(is_approved))
116				if vote.aye == is_approved =>
117				Some((vote.conviction.lock_periods(), balance)),
118
119			// If LockedIf::Always, return the lock period regardless of the vote
120			(AccountVote::Standard { vote, balance }, LockedIf::Always) =>
121				Some((vote.conviction.lock_periods(), balance)),
122
123			// All other cases return None
124			_ => None,
125		}
126	}
127
128	/// The total balance involved in this vote.
129	pub fn balance(self) -> Balance {
130		match self {
131			AccountVote::Standard { balance, .. } => balance,
132			AccountVote::Split { aye, nay } => aye.saturating_add(nay),
133			AccountVote::SplitAbstain { aye, nay, abstain } =>
134				aye.saturating_add(nay).saturating_add(abstain),
135		}
136	}
137
138	/// Returns `Some` with whether the vote is an aye vote if it is standard, otherwise `None` if
139	/// it is split.
140	pub fn as_standard(self) -> Option<bool> {
141		match self {
142			AccountVote::Standard { vote, .. } => Some(vote.aye),
143			_ => None,
144		}
145	}
146}
147
148/// A "prior" lock, i.e. a lock for some now-forgotten reason.
149#[derive(
150	Encode,
151	Decode,
152	DecodeWithMemTracking,
153	Default,
154	Copy,
155	Clone,
156	Eq,
157	PartialEq,
158	Ord,
159	PartialOrd,
160	Debug,
161	TypeInfo,
162	MaxEncodedLen,
163)]
164pub struct PriorLock<BlockNumber, Balance>(BlockNumber, Balance);
165
166impl<BlockNumber: Ord + Copy + Zero, Balance: Ord + Copy + Zero> PriorLock<BlockNumber, Balance> {
167	/// Accumulates an additional lock.
168	pub fn accumulate(&mut self, until: BlockNumber, amount: Balance) {
169		self.0 = self.0.max(until);
170		self.1 = self.1.max(amount);
171	}
172
173	pub fn locked(&self) -> Balance {
174		self.1
175	}
176
177	pub fn rejig(&mut self, now: BlockNumber) {
178		if now >= self.0 {
179			self.0 = Zero::zero();
180			self.1 = Zero::zero();
181		}
182	}
183}
184
185/// Information concerning the delegation of some voting power.
186#[derive(
187	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
188)]
189pub struct Delegating<Balance, AccountId, BlockNumber> {
190	/// The amount of balance delegated.
191	pub balance: Balance,
192	/// The account to which the voting power is delegated.
193	pub target: AccountId,
194	/// The conviction with which the voting power is delegated. When this gets undelegated, the
195	/// relevant lock begins.
196	pub conviction: Conviction,
197	/// The total amount of delegations that this account has received, post-conviction-weighting.
198	pub delegations: Delegations<Balance>,
199	/// Any pre-existing locks from past voting/delegating activity.
200	pub prior: PriorLock<BlockNumber, Balance>,
201}
202
203/// Information concerning the direct vote-casting of some voting power.
204#[derive(
205	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
206)]
207#[scale_info(skip_type_params(MaxVotes))]
208#[codec(mel_bound(Balance: MaxEncodedLen, BlockNumber: MaxEncodedLen, PollIndex: MaxEncodedLen))]
209pub struct Casting<Balance, BlockNumber, PollIndex, MaxVotes>
210where
211	MaxVotes: Get<u32>,
212{
213	/// The current votes of the account.
214	pub votes: BoundedVec<(PollIndex, AccountVote<Balance>), MaxVotes>,
215	/// The total amount of delegations that this account has received, post-conviction-weighting.
216	pub delegations: Delegations<Balance>,
217	/// Any pre-existing locks from past voting/delegating activity.
218	pub prior: PriorLock<BlockNumber, Balance>,
219}
220
221/// An indicator for what an account is doing; it can either be delegating or voting.
222#[derive(
223	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
224)]
225#[scale_info(skip_type_params(MaxVotes))]
226#[codec(mel_bound(
227	Balance: MaxEncodedLen, AccountId: MaxEncodedLen, BlockNumber: MaxEncodedLen,
228	PollIndex: MaxEncodedLen,
229))]
230pub enum Voting<Balance, AccountId, BlockNumber, PollIndex, MaxVotes>
231where
232	MaxVotes: Get<u32>,
233{
234	/// The account is voting directly.
235	Casting(Casting<Balance, BlockNumber, PollIndex, MaxVotes>),
236	/// The account is delegating `balance` of its balance to a `target` account with `conviction`.
237	Delegating(Delegating<Balance, AccountId, BlockNumber>),
238}
239
240impl<Balance: Default, AccountId, BlockNumber: Zero, PollIndex, MaxVotes> Default
241	for Voting<Balance, AccountId, BlockNumber, PollIndex, MaxVotes>
242where
243	MaxVotes: Get<u32>,
244{
245	fn default() -> Self {
246		Voting::Casting(Casting {
247			votes: Default::default(),
248			delegations: Default::default(),
249			prior: PriorLock(Zero::zero(), Default::default()),
250		})
251	}
252}
253
254impl<Balance, AccountId, BlockNumber, PollIndex, MaxVotes> AsMut<PriorLock<BlockNumber, Balance>>
255	for Voting<Balance, AccountId, BlockNumber, PollIndex, MaxVotes>
256where
257	MaxVotes: Get<u32>,
258{
259	fn as_mut(&mut self) -> &mut PriorLock<BlockNumber, Balance> {
260		match self {
261			Voting::Casting(Casting { prior, .. }) => prior,
262			Voting::Delegating(Delegating { prior, .. }) => prior,
263		}
264	}
265}
266
267impl<
268		Balance: Saturating + Ord + Zero + Copy,
269		BlockNumber: Ord + Copy + Zero,
270		AccountId,
271		PollIndex,
272		MaxVotes,
273	> Voting<Balance, AccountId, BlockNumber, PollIndex, MaxVotes>
274where
275	MaxVotes: Get<u32>,
276{
277	pub fn rejig(&mut self, now: BlockNumber) {
278		AsMut::<PriorLock<BlockNumber, Balance>>::as_mut(self).rejig(now);
279	}
280
281	/// The amount of this account's balance that must currently be locked due to voting.
282	pub fn locked_balance(&self) -> Balance {
283		match self {
284			Voting::Casting(Casting { votes, prior, .. }) =>
285				votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)),
286			Voting::Delegating(Delegating { balance, prior, .. }) => *balance.max(&prior.locked()),
287		}
288	}
289
290	pub fn set_common(
291		&mut self,
292		delegations: Delegations<Balance>,
293		prior: PriorLock<BlockNumber, Balance>,
294	) {
295		let (d, p) = match self {
296			Voting::Casting(Casting { ref mut delegations, ref mut prior, .. }) =>
297				(delegations, prior),
298			Voting::Delegating(Delegating { ref mut delegations, ref mut prior, .. }) =>
299				(delegations, prior),
300		};
301		*d = delegations;
302		*p = prior;
303	}
304}