use crate::Tally;
use codec::{Decode, Encode, MaxEncodedLen};
use core::ops::{Add, Div, Mul, Rem};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_runtime::traits::{IntegerSquareRoot, Zero};
#[derive(
Clone, Copy, PartialEq, Eq, Encode, MaxEncodedLen, Decode, sp_runtime::RuntimeDebug, TypeInfo,
)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum VoteThreshold {
SuperMajorityApprove,
SuperMajorityAgainst,
SimpleMajority,
}
pub trait Approved<Balance> {
fn approved(&self, tally: Tally<Balance>, electorate: Balance) -> bool;
}
fn compare_rationals<
T: Zero + Mul<T, Output = T> + Div<T, Output = T> + Rem<T, Output = T> + Ord + Copy,
>(
mut n1: T,
mut d1: T,
mut n2: T,
mut d2: T,
) -> bool {
loop {
let q1 = n1 / d1;
let q2 = n2 / d2;
if q1 < q2 {
return true
}
if q2 < q1 {
return false
}
let r1 = n1 % d1;
let r2 = n2 % d2;
if r2.is_zero() {
return false
}
if r1.is_zero() {
return true
}
n1 = d2;
n2 = d1;
d1 = r2;
d2 = r1;
}
}
impl<
Balance: IntegerSquareRoot
+ Zero
+ Ord
+ Add<Balance, Output = Balance>
+ Mul<Balance, Output = Balance>
+ Div<Balance, Output = Balance>
+ Rem<Balance, Output = Balance>
+ Copy,
> Approved<Balance> for VoteThreshold
{
fn approved(&self, tally: Tally<Balance>, electorate: Balance) -> bool {
let sqrt_voters = tally.turnout.integer_sqrt();
let sqrt_electorate = electorate.integer_sqrt();
if sqrt_voters.is_zero() {
return false
}
match *self {
VoteThreshold::SuperMajorityApprove =>
compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate),
VoteThreshold::SuperMajorityAgainst =>
compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters),
VoteThreshold::SimpleMajority => tally.ayes > tally.nays,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_work() {
assert!(!VoteThreshold::SuperMajorityApprove
.approved(Tally { ayes: 60, nays: 50, turnout: 110 }, 210));
assert!(VoteThreshold::SuperMajorityApprove
.approved(Tally { ayes: 100, nays: 50, turnout: 150 }, 210));
}
}