use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{pallet_prelude::Get, BoundedVec};
use scale_info::TypeInfo;
use sp_runtime::RuntimeDebug;
use sp_std::prelude::*;
pub const DKG_DEFAULT_PROPOSER_THRESHOLD: u32 = 1;
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub enum ProposalStatus {
Initiated,
Approved,
Rejected,
}
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub struct ProposalVotes<AccountId, BlockNumber, MaxVotes: Get<u32> + Clone> {
pub votes_for: BoundedVec<AccountId, MaxVotes>,
pub votes_against: BoundedVec<AccountId, MaxVotes>,
pub status: ProposalStatus,
pub expiry: BlockNumber,
}
impl<A: PartialEq, B: PartialOrd + Default, MaxVotes: Get<u32> + Clone>
ProposalVotes<A, B, MaxVotes>
{
pub fn try_to_complete(&mut self, threshold: u32, total: u32) -> ProposalStatus {
if self.votes_for.len() >= threshold as usize {
self.status = ProposalStatus::Approved;
ProposalStatus::Approved
} else if total >= threshold && self.votes_against.len() as u32 + threshold > total {
self.status = ProposalStatus::Rejected;
ProposalStatus::Rejected
} else {
ProposalStatus::Initiated
}
}
pub fn is_complete(&self) -> bool {
self.status != ProposalStatus::Initiated
}
pub fn has_voted(&self, who: &A) -> bool {
self.votes_for.contains(who) || self.votes_against.contains(who)
}
pub fn is_expired(&self, now: B) -> bool {
self.expiry <= now
}
}
impl<AccountId, BlockNumber: Default, MaxVotes: Get<u32> + Clone> Default
for ProposalVotes<AccountId, BlockNumber, MaxVotes>
{
fn default() -> Self {
Self {
votes_for: Default::default(),
votes_against: Default::default(),
status: ProposalStatus::Initiated,
expiry: BlockNumber::default(),
}
}
}