referrerpolicy=no-referrer-when-downgrade

pallet_conviction_voting/
lib.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//! # Voting Pallet
19//!
20//! - [`Config`]
21//! - [`Call`]
22//!
23//! ## Overview
24//!
25//! Pallet for managing actual voting in polls.
26
27#![recursion_limit = "256"]
28#![cfg_attr(not(feature = "std"), no_std)]
29
30extern crate alloc;
31
32use frame_support::{
33	dispatch::DispatchResult,
34	ensure,
35	traits::{
36		fungible, Currency, Get, LockIdentifier, LockableCurrency, PollStatus, Polling,
37		ReservableCurrency, WithdrawReasons,
38	},
39};
40use sp_runtime::{
41	traits::{AtLeast32BitUnsigned, Saturating, StaticLookup, Zero},
42	ArithmeticError, DispatchError, Perbill,
43};
44
45mod conviction;
46mod traits;
47mod types;
48mod vote;
49pub mod weights;
50
51pub use self::{
52	conviction::Conviction,
53	pallet::*,
54	traits::{Status, VotingHooks},
55	types::{Delegations, Tally, UnvoteScope},
56	vote::{AccountVote, Casting, Delegating, Vote, Voting},
57	weights::WeightInfo,
58};
59use sp_runtime::traits::BlockNumberProvider;
60
61#[cfg(test)]
62mod tests;
63
64#[cfg(feature = "runtime-benchmarks")]
65pub mod benchmarking;
66
67const CONVICTION_VOTING_ID: LockIdentifier = *b"pyconvot";
68
69pub type BlockNumberFor<T, I> =
70	<<T as Config<I>>::BlockNumberProvider as BlockNumberProvider>::BlockNumber;
71
72type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
73pub type BalanceOf<T, I = ()> =
74	<<T as Config<I>>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
75pub type VotingOf<T, I = ()> = Voting<
76	BalanceOf<T, I>,
77	<T as frame_system::Config>::AccountId,
78	BlockNumberFor<T, I>,
79	PollIndexOf<T, I>,
80	<T as Config<I>>::MaxVotes,
81>;
82#[allow(dead_code)]
83type DelegatingOf<T, I = ()> =
84	Delegating<BalanceOf<T, I>, <T as frame_system::Config>::AccountId, BlockNumberFor<T, I>>;
85pub type TallyOf<T, I = ()> = Tally<BalanceOf<T, I>, <T as Config<I>>::MaxTurnout>;
86pub type VotesOf<T, I = ()> = BalanceOf<T, I>;
87pub type PollIndexOf<T, I = ()> = <<T as Config<I>>::Polls as Polling<TallyOf<T, I>>>::Index;
88#[cfg(feature = "runtime-benchmarks")]
89pub type IndexOf<T, I = ()> = <<T as Config<I>>::Polls as Polling<TallyOf<T, I>>>::Index;
90pub type ClassOf<T, I = ()> = <<T as Config<I>>::Polls as Polling<TallyOf<T, I>>>::Class;
91
92#[frame_support::pallet]
93pub mod pallet {
94	use super::*;
95	use frame_support::{
96		pallet_prelude::{
97			DispatchResultWithPostInfo, IsType, StorageDoubleMap, StorageMap, ValueQuery,
98		},
99		traits::ClassCountOf,
100		Twox64Concat,
101	};
102	use frame_system::pallet_prelude::{ensure_signed, OriginFor};
103	use sp_runtime::BoundedVec;
104
105	#[pallet::pallet]
106	pub struct Pallet<T, I = ()>(_);
107
108	#[pallet::config]
109	pub trait Config<I: 'static = ()>: frame_system::Config + Sized {
110		// System level stuff.
111		#[allow(deprecated)]
112		type RuntimeEvent: From<Event<Self, I>>
113			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
114		/// Weight information for extrinsics in this pallet.
115		type WeightInfo: WeightInfo;
116		/// Currency type with which voting happens.
117		type Currency: ReservableCurrency<Self::AccountId>
118			+ LockableCurrency<Self::AccountId, Moment = BlockNumberFor<Self, I>>
119			+ fungible::Inspect<Self::AccountId>;
120
121		/// The implementation of the logic which conducts polls.
122		type Polls: Polling<
123			TallyOf<Self, I>,
124			Votes = BalanceOf<Self, I>,
125			Moment = BlockNumberFor<Self, I>,
126		>;
127
128		/// The maximum amount of tokens which may be used for voting. May just be
129		/// `Currency::total_issuance`, but you might want to reduce this in order to account for
130		/// funds in the system which are unable to vote (e.g. parachain auction deposits).
131		type MaxTurnout: Get<BalanceOf<Self, I>>;
132
133		/// The maximum number of concurrent votes an account may have.
134		///
135		/// Also used to compute weight, an overly large value can lead to extrinsics with large
136		/// weight estimation: see `delegate` for instance.
137		#[pallet::constant]
138		type MaxVotes: Get<u32>;
139
140		/// The minimum period of vote locking.
141		///
142		/// It should be no shorter than enactment period to ensure that in the case of an approval,
143		/// those successful voters are locked into the consequences that their votes entail.
144		#[pallet::constant]
145		type VoteLockingPeriod: Get<BlockNumberFor<Self, I>>;
146		/// Provider for the block number. Normally this is the `frame_system` pallet.
147		type BlockNumberProvider: BlockNumberProvider;
148		/// Hooks are called when a new vote is registered or an existing vote is removed.
149		///
150		/// The trait does not expose weight information.
151		/// The weight of each hook is assumed to be benchmarked as part of the function that calls
152		/// it. Hooks should never recursively call into functions that called,
153		/// directly or indirectly, the function that called them.
154		/// This could lead to infinite recursion and stack overflow.
155		/// Note that this also means to not call into other generic functionality like batch or
156		/// similar. Also, anything that a hook did will be subject to the transactional semantics
157		/// of the calling function. This means that if the calling function fails, the hook will
158		/// be rolled back without further notice.
159		type VotingHooks: VotingHooks<Self::AccountId, PollIndexOf<Self, I>, BalanceOf<Self, I>>;
160	}
161
162	/// All voting for a particular voter in a particular voting class. We store the balance for the
163	/// number of votes that we have recorded.
164	#[pallet::storage]
165	pub type VotingFor<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
166		_,
167		Twox64Concat,
168		T::AccountId,
169		Twox64Concat,
170		ClassOf<T, I>,
171		VotingOf<T, I>,
172		ValueQuery,
173	>;
174
175	/// The voting classes which have a non-zero lock requirement and the lock amounts which they
176	/// require. The actual amount locked on behalf of this pallet should always be the maximum of
177	/// this list.
178	#[pallet::storage]
179	pub type ClassLocksFor<T: Config<I>, I: 'static = ()> = StorageMap<
180		_,
181		Twox64Concat,
182		T::AccountId,
183		BoundedVec<(ClassOf<T, I>, BalanceOf<T, I>), ClassCountOf<T::Polls, TallyOf<T, I>>>,
184		ValueQuery,
185	>;
186
187	#[pallet::event]
188	#[pallet::generate_deposit(pub(super) fn deposit_event)]
189	pub enum Event<T: Config<I>, I: 'static = ()> {
190		/// An account has delegated their vote to another account. \[who, target\]
191		Delegated(T::AccountId, T::AccountId),
192		/// An \[account\] has cancelled a previous delegation operation.
193		Undelegated(T::AccountId),
194		/// An account has voted
195		Voted { who: T::AccountId, vote: AccountVote<BalanceOf<T, I>> },
196		/// A vote has been removed
197		VoteRemoved { who: T::AccountId, vote: AccountVote<BalanceOf<T, I>> },
198		/// The lockup period of a conviction vote expired, and the funds have been unlocked.
199		VoteUnlocked { who: T::AccountId, class: ClassOf<T, I> },
200	}
201
202	#[pallet::error]
203	pub enum Error<T, I = ()> {
204		/// Poll is not ongoing.
205		NotOngoing,
206		/// The given account did not vote on the poll.
207		NotVoter,
208		/// The actor has no permission to conduct the action.
209		NoPermission,
210		/// The actor has no permission to conduct the action right now but will do in the future.
211		NoPermissionYet,
212		/// The account is already delegating.
213		AlreadyDelegating,
214		/// The account currently has votes attached to it and the operation cannot succeed until
215		/// these are removed through `remove_vote`.
216		AlreadyVoting,
217		/// Too high a balance was provided that the account cannot afford.
218		InsufficientFunds,
219		/// The account is not currently delegating.
220		NotDelegating,
221		/// Delegation to oneself makes no sense.
222		Nonsense,
223		/// Maximum number of votes reached.
224		MaxVotesReached,
225		/// The class must be supplied since it is not easily determinable from the state.
226		ClassNeeded,
227		/// The class ID supplied is invalid.
228		BadClass,
229	}
230
231	#[pallet::call]
232	impl<T: Config<I>, I: 'static> Pallet<T, I> {
233		/// Vote in a poll. If `vote.is_aye()`, the vote is to enact the proposal;
234		/// otherwise it is a vote to keep the status quo.
235		///
236		/// The dispatch origin of this call must be _Signed_.
237		///
238		/// - `poll_index`: The index of the poll to vote for.
239		/// - `vote`: The vote configuration.
240		///
241		/// Weight: `O(R)` where R is the number of polls the voter has voted on.
242		#[pallet::call_index(0)]
243		#[pallet::weight(T::WeightInfo::vote_new().max(T::WeightInfo::vote_existing()))]
244		pub fn vote(
245			origin: OriginFor<T>,
246			#[pallet::compact] poll_index: PollIndexOf<T, I>,
247			vote: AccountVote<BalanceOf<T, I>>,
248		) -> DispatchResult {
249			let who = ensure_signed(origin)?;
250			Self::try_vote(&who, poll_index, vote)
251		}
252
253		/// Delegate the voting power (with some given conviction) of the sending account for a
254		/// particular class of polls.
255		///
256		/// The balance delegated is locked for as long as it's delegated, and thereafter for the
257		/// time appropriate for the conviction's lock period.
258		///
259		/// The dispatch origin of this call must be _Signed_, and the signing account must either:
260		///   - be delegating already; or
261		///   - have no voting activity (if there is, then it will need to be removed through
262		///     `remove_vote`).
263		///
264		/// - `to`: The account whose voting the `target` account's voting power will follow.
265		/// - `class`: The class of polls to delegate. To delegate multiple classes, multiple calls
266		///   to this function are required.
267		/// - `conviction`: The conviction that will be attached to the delegated votes. When the
268		///   account is undelegated, the funds will be locked for the corresponding period.
269		/// - `balance`: The amount of the account's balance to be used in delegating. This must not
270		///   be more than the account's current balance.
271		///
272		/// Emits `Delegated`.
273		///
274		/// Weight: `O(R)` where R is the number of polls the voter delegating to has
275		///   voted on. Weight is initially charged as if maximum votes, but is refunded later.
276		// NOTE: weight must cover an incorrect voting of origin with max votes, this is ensure
277		// because a valid delegation cover decoding a direct voting with max votes.
278		#[pallet::call_index(1)]
279		#[pallet::weight(T::WeightInfo::delegate(T::MaxVotes::get()))]
280		pub fn delegate(
281			origin: OriginFor<T>,
282			class: ClassOf<T, I>,
283			to: AccountIdLookupOf<T>,
284			conviction: Conviction,
285			balance: BalanceOf<T, I>,
286		) -> DispatchResultWithPostInfo {
287			let who = ensure_signed(origin)?;
288			let to = T::Lookup::lookup(to)?;
289			let votes = Self::try_delegate(who, class, to, conviction, balance)?;
290
291			Ok(Some(T::WeightInfo::delegate(votes)).into())
292		}
293
294		/// Undelegate the voting power of the sending account for a particular class of polls.
295		///
296		/// Tokens may be unlocked following once an amount of time consistent with the lock period
297		/// of the conviction with which the delegation was issued has passed.
298		///
299		/// The dispatch origin of this call must be _Signed_ and the signing account must be
300		/// currently delegating.
301		///
302		/// - `class`: The class of polls to remove the delegation from.
303		///
304		/// Emits `Undelegated`.
305		///
306		/// Weight: `O(R)` where R is the number of polls the voter delegating to has
307		///   voted on. Weight is initially charged as if maximum votes, but is refunded later.
308		// NOTE: weight must cover an incorrect voting of origin with max votes, this is ensure
309		// because a valid delegation cover decoding a direct voting with max votes.
310		#[pallet::call_index(2)]
311		#[pallet::weight(T::WeightInfo::undelegate(T::MaxVotes::get().into()))]
312		pub fn undelegate(
313			origin: OriginFor<T>,
314			class: ClassOf<T, I>,
315		) -> DispatchResultWithPostInfo {
316			let who = ensure_signed(origin)?;
317			let votes = Self::try_undelegate(who, class)?;
318			Ok(Some(T::WeightInfo::undelegate(votes)).into())
319		}
320
321		/// Remove the lock caused by prior voting/delegating which has expired within a particular
322		/// class.
323		///
324		/// The dispatch origin of this call must be _Signed_.
325		///
326		/// - `class`: The class of polls to unlock.
327		/// - `target`: The account to remove the lock on.
328		///
329		/// Weight: `O(R)` with R number of vote of target.
330		#[pallet::call_index(3)]
331		#[pallet::weight(T::WeightInfo::unlock())]
332		pub fn unlock(
333			origin: OriginFor<T>,
334			class: ClassOf<T, I>,
335			target: AccountIdLookupOf<T>,
336		) -> DispatchResult {
337			ensure_signed(origin)?;
338			let target = T::Lookup::lookup(target)?;
339			Self::update_lock(&class, &target);
340			Self::deposit_event(Event::VoteUnlocked { who: target, class });
341			Ok(())
342		}
343
344		/// Remove a vote for a poll.
345		///
346		/// If:
347		/// - the poll was cancelled, or
348		/// - the poll is ongoing, or
349		/// - the poll has ended such that
350		///   - the vote of the account was in opposition to the result; or
351		///   - there was no conviction to the account's vote; or
352		///   - the account made a split vote
353		/// ...then the vote is removed cleanly and a following call to `unlock` may result in more
354		/// funds being available.
355		///
356		/// If, however, the poll has ended and:
357		/// - it finished corresponding to the vote of the account, and
358		/// - the account made a standard vote with conviction, and
359		/// - the lock period of the conviction is not over
360		/// ...then the lock will be aggregated into the overall account's lock, which may involve
361		/// *overlocking* (where the two locks are combined into a single lock that is the maximum
362		/// of both the amount locked and the time is it locked for).
363		///
364		/// The dispatch origin of this call must be _Signed_, and the signer must have a vote
365		/// registered for poll `index`.
366		///
367		/// - `index`: The index of poll of the vote to be removed.
368		/// - `class`: Optional parameter, if given it indicates the class of the poll. For polls
369		///   which have finished or are cancelled, this must be `Some`.
370		///
371		/// Weight: `O(R + log R)` where R is the number of polls that `target` has voted on.
372		///   Weight is calculated for the maximum number of vote.
373		#[pallet::call_index(4)]
374		#[pallet::weight(T::WeightInfo::remove_vote())]
375		pub fn remove_vote(
376			origin: OriginFor<T>,
377			class: Option<ClassOf<T, I>>,
378			index: PollIndexOf<T, I>,
379		) -> DispatchResult {
380			let who = ensure_signed(origin)?;
381			Self::try_remove_vote(&who, index, class, UnvoteScope::Any)
382		}
383
384		/// Remove a vote for a poll.
385		///
386		/// If the `target` is equal to the signer, then this function is exactly equivalent to
387		/// `remove_vote`. If not equal to the signer, then the vote must have expired,
388		/// either because the poll was cancelled, because the voter lost the poll or
389		/// because the conviction period is over.
390		///
391		/// The dispatch origin of this call must be _Signed_.
392		///
393		/// - `target`: The account of the vote to be removed; this account must have voted for poll
394		///   `index`.
395		/// - `index`: The index of poll of the vote to be removed.
396		/// - `class`: The class of the poll.
397		///
398		/// Weight: `O(R + log R)` where R is the number of polls that `target` has voted on.
399		///   Weight is calculated for the maximum number of vote.
400		#[pallet::call_index(5)]
401		#[pallet::weight(T::WeightInfo::remove_other_vote())]
402		pub fn remove_other_vote(
403			origin: OriginFor<T>,
404			target: AccountIdLookupOf<T>,
405			class: ClassOf<T, I>,
406			index: PollIndexOf<T, I>,
407		) -> DispatchResult {
408			let who = ensure_signed(origin)?;
409			let target = T::Lookup::lookup(target)?;
410			let scope = if target == who { UnvoteScope::Any } else { UnvoteScope::OnlyExpired };
411			Self::try_remove_vote(&target, index, Some(class), scope)?;
412			Ok(())
413		}
414	}
415}
416
417impl<T: Config<I>, I: 'static> Pallet<T, I> {
418	/// Actually enact a vote, if legit.
419	fn try_vote(
420		who: &T::AccountId,
421		poll_index: PollIndexOf<T, I>,
422		vote: AccountVote<BalanceOf<T, I>>,
423	) -> DispatchResult {
424		ensure!(
425			vote.balance() <= T::Currency::total_balance(who),
426			Error::<T, I>::InsufficientFunds
427		);
428		// Call on_vote hook
429		T::VotingHooks::on_before_vote(who, poll_index, vote)?;
430
431		T::Polls::try_access_poll(poll_index, |poll_status| {
432			let (tally, class) = poll_status.ensure_ongoing().ok_or(Error::<T, I>::NotOngoing)?;
433			VotingFor::<T, I>::try_mutate(who, &class, |voting| {
434				if let Voting::Casting(Casting { ref mut votes, delegations, .. }) = voting {
435					match votes.binary_search_by_key(&poll_index, |i| i.0) {
436						Ok(i) => {
437							// Shouldn't be possible to fail, but we handle it gracefully.
438							tally.remove(votes[i].1).ok_or(ArithmeticError::Underflow)?;
439							if let Some(approve) = votes[i].1.as_standard() {
440								tally.reduce(approve, *delegations);
441							}
442							votes[i].1 = vote;
443						},
444						Err(i) => {
445							votes
446								.try_insert(i, (poll_index, vote))
447								.map_err(|_| Error::<T, I>::MaxVotesReached)?;
448						},
449					}
450					// Shouldn't be possible to fail, but we handle it gracefully.
451					tally.add(vote).ok_or(ArithmeticError::Overflow)?;
452					if let Some(approve) = vote.as_standard() {
453						tally.increase(approve, *delegations);
454					}
455				} else {
456					return Err(Error::<T, I>::AlreadyDelegating.into());
457				}
458				// Extend the lock to `balance` (rather than setting it) since we don't know what
459				// other votes are in place.
460				Self::extend_lock(who, &class, vote.balance());
461				Self::deposit_event(Event::Voted { who: who.clone(), vote });
462				Ok(())
463			})
464		})
465	}
466
467	/// Remove the account's vote for the given poll if possible. This is possible when:
468	/// - The poll has not finished.
469	/// - The poll has finished and the voter lost their direction.
470	/// - The poll has finished and the voter's lock period is up.
471	///
472	/// This will generally be combined with a call to `unlock`.
473	fn try_remove_vote(
474		who: &T::AccountId,
475		poll_index: PollIndexOf<T, I>,
476		class_hint: Option<ClassOf<T, I>>,
477		scope: UnvoteScope,
478	) -> DispatchResult {
479		let class = class_hint
480			.or_else(|| Some(T::Polls::as_ongoing(poll_index)?.1))
481			.ok_or(Error::<T, I>::ClassNeeded)?;
482		VotingFor::<T, I>::try_mutate(who, class, |voting| {
483			if let Voting::Casting(Casting { ref mut votes, delegations, ref mut prior }) = voting {
484				let i = votes
485					.binary_search_by_key(&poll_index, |i| i.0)
486					.map_err(|_| Error::<T, I>::NotVoter)?;
487				let v = votes.remove(i);
488
489				T::Polls::try_access_poll(poll_index, |poll_status| match poll_status {
490					PollStatus::Ongoing(tally, _) => {
491						ensure!(matches!(scope, UnvoteScope::Any), Error::<T, I>::NoPermission);
492						// Shouldn't be possible to fail, but we handle it gracefully.
493						tally.remove(v.1).ok_or(ArithmeticError::Underflow)?;
494						if let Some(approve) = v.1.as_standard() {
495							tally.reduce(approve, *delegations);
496						}
497						Self::deposit_event(Event::VoteRemoved { who: who.clone(), vote: v.1 });
498						T::VotingHooks::on_remove_vote(who, poll_index, Status::Ongoing);
499						Ok(())
500					},
501					PollStatus::Completed(end, approved) => {
502						if let Some((lock_periods, balance)) =
503							v.1.locked_if(vote::LockedIf::Status(approved))
504						{
505							let unlock_at = end.saturating_add(
506								T::VoteLockingPeriod::get().saturating_mul(lock_periods.into()),
507							);
508							let now = T::BlockNumberProvider::current_block_number();
509							if now < unlock_at {
510								ensure!(
511									matches!(scope, UnvoteScope::Any),
512									Error::<T, I>::NoPermissionYet
513								);
514								prior.accumulate(unlock_at, balance)
515							}
516						} else if v.1.as_standard().is_some_and(|vote| vote != approved) {
517							// Unsuccessful vote, use special hook to lock the funds too in case of
518							// conviction.
519							if let Some(to_lock) =
520								T::VotingHooks::lock_balance_on_unsuccessful_vote(who, poll_index)
521							{
522								if let AccountVote::Standard { vote, .. } = v.1 {
523									let unlock_at = end.saturating_add(
524										T::VoteLockingPeriod::get()
525											.saturating_mul(vote.conviction.lock_periods().into()),
526									);
527									let now = T::BlockNumberProvider::current_block_number();
528									if now < unlock_at {
529										ensure!(
530											matches!(scope, UnvoteScope::Any),
531											Error::<T, I>::NoPermissionYet
532										);
533										prior.accumulate(unlock_at, to_lock)
534									}
535								}
536							}
537						}
538						// Call on_remove_vote hook
539						T::VotingHooks::on_remove_vote(who, poll_index, Status::Completed);
540						Ok(())
541					},
542					PollStatus::None => {
543						// Poll was cancelled.
544						T::VotingHooks::on_remove_vote(who, poll_index, Status::None);
545						Ok(())
546					},
547				})
548			} else {
549				Ok(())
550			}
551		})
552	}
553
554	/// Return the number of votes for `who`.
555	fn increase_upstream_delegation(
556		who: &T::AccountId,
557		class: &ClassOf<T, I>,
558		amount: Delegations<BalanceOf<T, I>>,
559	) -> u32 {
560		VotingFor::<T, I>::mutate(who, class, |voting| match voting {
561			Voting::Delegating(Delegating { delegations, .. }) => {
562				// We don't support second level delegating, so we don't need to do anything more.
563				*delegations = delegations.saturating_add(amount);
564				1
565			},
566			Voting::Casting(Casting { votes, delegations, .. }) => {
567				*delegations = delegations.saturating_add(amount);
568				for &(poll_index, account_vote) in votes.iter() {
569					if let AccountVote::Standard { vote, .. } = account_vote {
570						T::Polls::access_poll(poll_index, |poll_status| {
571							if let PollStatus::Ongoing(tally, _) = poll_status {
572								tally.increase(vote.aye, amount);
573							}
574						});
575					}
576				}
577				votes.len() as u32
578			},
579		})
580	}
581
582	/// Return the number of votes for `who`.
583	fn reduce_upstream_delegation(
584		who: &T::AccountId,
585		class: &ClassOf<T, I>,
586		amount: Delegations<BalanceOf<T, I>>,
587	) -> u32 {
588		VotingFor::<T, I>::mutate(who, class, |voting| match voting {
589			Voting::Delegating(Delegating { delegations, .. }) => {
590				// We don't support second level delegating, so we don't need to do anything more.
591				*delegations = delegations.saturating_sub(amount);
592				1
593			},
594			Voting::Casting(Casting { votes, delegations, .. }) => {
595				*delegations = delegations.saturating_sub(amount);
596				for &(poll_index, account_vote) in votes.iter() {
597					if let AccountVote::Standard { vote, .. } = account_vote {
598						T::Polls::access_poll(poll_index, |poll_status| {
599							if let PollStatus::Ongoing(tally, _) = poll_status {
600								tally.reduce(vote.aye, amount);
601							}
602						});
603					}
604				}
605				votes.len() as u32
606			},
607		})
608	}
609
610	/// Attempt to delegate `balance` times `conviction` of voting power from `who` to `target`.
611	///
612	/// Return the upstream number of votes.
613	fn try_delegate(
614		who: T::AccountId,
615		class: ClassOf<T, I>,
616		target: T::AccountId,
617		conviction: Conviction,
618		balance: BalanceOf<T, I>,
619	) -> Result<u32, DispatchError> {
620		ensure!(who != target, Error::<T, I>::Nonsense);
621		T::Polls::classes().binary_search(&class).map_err(|_| Error::<T, I>::BadClass)?;
622		ensure!(balance <= T::Currency::total_balance(&who), Error::<T, I>::InsufficientFunds);
623		let votes =
624			VotingFor::<T, I>::try_mutate(&who, &class, |voting| -> Result<u32, DispatchError> {
625				let old = core::mem::replace(
626					voting,
627					Voting::Delegating(Delegating {
628						balance,
629						target: target.clone(),
630						conviction,
631						delegations: Default::default(),
632						prior: Default::default(),
633					}),
634				);
635				match old {
636					Voting::Delegating(Delegating { .. }) =>
637						return Err(Error::<T, I>::AlreadyDelegating.into()),
638					Voting::Casting(Casting { votes, delegations, prior }) => {
639						// here we just ensure that we're currently idling with no votes recorded.
640						ensure!(votes.is_empty(), Error::<T, I>::AlreadyVoting);
641						voting.set_common(delegations, prior);
642					},
643				}
644
645				let votes =
646					Self::increase_upstream_delegation(&target, &class, conviction.votes(balance));
647				// Extend the lock to `balance` (rather than setting it) since we don't know what
648				// other votes are in place.
649				Self::extend_lock(&who, &class, balance);
650				Ok(votes)
651			})?;
652		Self::deposit_event(Event::<T, I>::Delegated(who, target));
653		Ok(votes)
654	}
655
656	/// Attempt to end the current delegation.
657	///
658	/// Return the number of votes of upstream.
659	fn try_undelegate(who: T::AccountId, class: ClassOf<T, I>) -> Result<u32, DispatchError> {
660		let votes =
661			VotingFor::<T, I>::try_mutate(&who, &class, |voting| -> Result<u32, DispatchError> {
662				match core::mem::replace(voting, Voting::default()) {
663					Voting::Delegating(Delegating {
664						balance,
665						target,
666						conviction,
667						delegations,
668						mut prior,
669					}) => {
670						// remove any delegation votes to our current target.
671						let votes = Self::reduce_upstream_delegation(
672							&target,
673							&class,
674							conviction.votes(balance),
675						);
676						let now = T::BlockNumberProvider::current_block_number();
677						let lock_periods = conviction.lock_periods().into();
678						prior.accumulate(
679							now.saturating_add(
680								T::VoteLockingPeriod::get().saturating_mul(lock_periods),
681							),
682							balance,
683						);
684						voting.set_common(delegations, prior);
685
686						Ok(votes)
687					},
688					Voting::Casting(_) => Err(Error::<T, I>::NotDelegating.into()),
689				}
690			})?;
691		Self::deposit_event(Event::<T, I>::Undelegated(who));
692		Ok(votes)
693	}
694
695	fn extend_lock(who: &T::AccountId, class: &ClassOf<T, I>, amount: BalanceOf<T, I>) {
696		ClassLocksFor::<T, I>::mutate(who, |locks| {
697			match locks.iter().position(|x| &x.0 == class) {
698				Some(i) => locks[i].1 = locks[i].1.max(amount),
699				None => {
700					let ok = locks.try_push((class.clone(), amount)).is_ok();
701					debug_assert!(
702						ok,
703						"Vec bounded by number of classes; \
704						all items in Vec associated with a unique class; \
705						qed"
706					);
707				},
708			}
709		});
710		T::Currency::extend_lock(
711			CONVICTION_VOTING_ID,
712			who,
713			amount,
714			WithdrawReasons::except(WithdrawReasons::RESERVE),
715		);
716	}
717
718	/// Rejig the lock on an account. It will never get more stringent (since that would indicate
719	/// a security hole) but may be reduced from what they are currently.
720	fn update_lock(class: &ClassOf<T, I>, who: &T::AccountId) {
721		let class_lock_needed = VotingFor::<T, I>::mutate(who, class, |voting| {
722			voting.rejig(T::BlockNumberProvider::current_block_number());
723			voting.locked_balance()
724		});
725		let lock_needed = ClassLocksFor::<T, I>::mutate(who, |locks| {
726			locks.retain(|x| &x.0 != class);
727			if !class_lock_needed.is_zero() {
728				let ok = locks.try_push((class.clone(), class_lock_needed)).is_ok();
729				debug_assert!(
730					ok,
731					"Vec bounded by number of classes; \
732					all items in Vec associated with a unique class; \
733					qed"
734				);
735			}
736			locks.iter().map(|x| x.1).max().unwrap_or(Zero::zero())
737		});
738		if lock_needed.is_zero() {
739			T::Currency::remove_lock(CONVICTION_VOTING_ID, who);
740		} else {
741			T::Currency::set_lock(
742				CONVICTION_VOTING_ID,
743				who,
744				lock_needed,
745				WithdrawReasons::except(WithdrawReasons::RESERVE),
746			);
747		}
748	}
749}