use crate::{Conviction, Delegations};
use codec::{Decode, Encode, EncodeLike, Input, MaxEncodedLen, Output};
use frame_support::{pallet_prelude::Get, BoundedVec};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{Saturating, Zero},
RuntimeDebug,
};
#[derive(Copy, Clone, Eq, PartialEq, Default, RuntimeDebug, MaxEncodedLen)]
pub struct Vote {
pub aye: bool,
pub conviction: Conviction,
}
impl Encode for Vote {
fn encode_to<T: Output + ?Sized>(&self, output: &mut T) {
output.push_byte(u8::from(self.conviction) | if self.aye { 0b1000_0000 } else { 0 });
}
}
impl EncodeLike for Vote {}
impl Decode for Vote {
fn decode<I: Input>(input: &mut I) -> Result<Self, codec::Error> {
let b = input.read_byte()?;
Ok(Vote {
aye: (b & 0b1000_0000) == 0b1000_0000,
conviction: Conviction::try_from(b & 0b0111_1111)
.map_err(|_| codec::Error::from("Invalid conviction"))?,
})
}
}
impl TypeInfo for Vote {
type Identity = Self;
fn type_info() -> scale_info::Type {
scale_info::Type::builder()
.path(scale_info::Path::new("Vote", module_path!()))
.composite(
scale_info::build::Fields::unnamed()
.field(|f| f.ty::<u8>().docs(&["Raw vote byte, encodes aye + conviction"])),
)
}
}
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub enum AccountVote<Balance> {
Standard { vote: Vote, balance: Balance },
Split { aye: Balance, nay: Balance },
SplitAbstain { aye: Balance, nay: Balance, abstain: Balance },
}
impl<Balance: Saturating> AccountVote<Balance> {
pub fn locked_if(self, approved: bool) -> Option<(u32, Balance)> {
match self {
AccountVote::Standard { vote: Vote { conviction: Conviction::None, .. }, .. } => None,
AccountVote::Standard { vote, balance } if vote.aye == approved =>
Some((vote.conviction.lock_periods(), balance)),
_ => None,
}
}
pub fn balance(self) -> Balance {
match self {
AccountVote::Standard { balance, .. } => balance,
AccountVote::Split { aye, nay } => aye.saturating_add(nay),
AccountVote::SplitAbstain { aye, nay, abstain } =>
aye.saturating_add(nay).saturating_add(abstain),
}
}
pub fn as_standard(self) -> Option<bool> {
match self {
AccountVote::Standard { vote, .. } => Some(vote.aye),
_ => None,
}
}
}
#[derive(
Encode,
Decode,
Default,
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
RuntimeDebug,
TypeInfo,
MaxEncodedLen,
)]
pub struct PriorLock<BlockNumber, Balance>(BlockNumber, Balance);
impl<BlockNumber: Ord + Copy + Zero, Balance: Ord + Copy + Zero> PriorLock<BlockNumber, Balance> {
pub fn accumulate(&mut self, until: BlockNumber, amount: Balance) {
self.0 = self.0.max(until);
self.1 = self.1.max(amount);
}
pub fn locked(&self) -> Balance {
self.1
}
pub fn rejig(&mut self, now: BlockNumber) {
if now >= self.0 {
self.0 = Zero::zero();
self.1 = Zero::zero();
}
}
}
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub struct Delegating<Balance, AccountId, BlockNumber> {
pub balance: Balance,
pub target: AccountId,
pub conviction: Conviction,
pub delegations: Delegations<Balance>,
pub prior: PriorLock<BlockNumber, Balance>,
}
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(MaxVotes))]
#[codec(mel_bound(Balance: MaxEncodedLen, BlockNumber: MaxEncodedLen, PollIndex: MaxEncodedLen))]
pub struct Casting<Balance, BlockNumber, PollIndex, MaxVotes>
where
MaxVotes: Get<u32>,
{
pub votes: BoundedVec<(PollIndex, AccountVote<Balance>), MaxVotes>,
pub delegations: Delegations<Balance>,
pub prior: PriorLock<BlockNumber, Balance>,
}
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(MaxVotes))]
#[codec(mel_bound(
Balance: MaxEncodedLen, AccountId: MaxEncodedLen, BlockNumber: MaxEncodedLen,
PollIndex: MaxEncodedLen,
))]
pub enum Voting<Balance, AccountId, BlockNumber, PollIndex, MaxVotes>
where
MaxVotes: Get<u32>,
{
Casting(Casting<Balance, BlockNumber, PollIndex, MaxVotes>),
Delegating(Delegating<Balance, AccountId, BlockNumber>),
}
impl<Balance: Default, AccountId, BlockNumber: Zero, PollIndex, MaxVotes> Default
for Voting<Balance, AccountId, BlockNumber, PollIndex, MaxVotes>
where
MaxVotes: Get<u32>,
{
fn default() -> Self {
Voting::Casting(Casting {
votes: Default::default(),
delegations: Default::default(),
prior: PriorLock(Zero::zero(), Default::default()),
})
}
}
impl<Balance, AccountId, BlockNumber, PollIndex, MaxVotes> AsMut<PriorLock<BlockNumber, Balance>>
for Voting<Balance, AccountId, BlockNumber, PollIndex, MaxVotes>
where
MaxVotes: Get<u32>,
{
fn as_mut(&mut self) -> &mut PriorLock<BlockNumber, Balance> {
match self {
Voting::Casting(Casting { prior, .. }) => prior,
Voting::Delegating(Delegating { prior, .. }) => prior,
}
}
}
impl<
Balance: Saturating + Ord + Zero + Copy,
BlockNumber: Ord + Copy + Zero,
AccountId,
PollIndex,
MaxVotes,
> Voting<Balance, AccountId, BlockNumber, PollIndex, MaxVotes>
where
MaxVotes: Get<u32>,
{
pub fn rejig(&mut self, now: BlockNumber) {
AsMut::<PriorLock<BlockNumber, Balance>>::as_mut(self).rejig(now);
}
pub fn locked_balance(&self) -> Balance {
match self {
Voting::Casting(Casting { votes, prior, .. }) =>
votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)),
Voting::Delegating(Delegating { balance, prior, .. }) => *balance.max(&prior.locked()),
}
}
pub fn set_common(
&mut self,
delegations: Delegations<Balance>,
prior: PriorLock<BlockNumber, Balance>,
) {
let (d, p) = match self {
Voting::Casting(Casting { ref mut delegations, ref mut prior, .. }) =>
(delegations, prior),
Voting::Delegating(Delegating { ref mut delegations, ref mut prior, .. }) =>
(delegations, prior),
};
*d = delegations;
*p = prior;
}
}