#![cfg_attr(not(feature = "std"), no_std)]
#![recursion_limit="128"]
use sp_std::prelude::*;
use sp_runtime::{
RuntimeDebug, DispatchResult, print,
traits::{Zero, One, StaticLookup, Saturating},
};
use frame_support::{
decl_storage, decl_event, ensure, decl_module, decl_error,
weights::{Weight, DispatchClass},
traits::{
Currency, ExistenceRequirement, Get, LockableCurrency, LockIdentifier, BalanceStatus,
OnUnbalanced, ReservableCurrency, WithdrawReasons, ChangeMembers,
}
};
use codec::{Encode, Decode};
use frame_system::{ensure_signed, ensure_root};
mod mock;
mod tests;
#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, Default, RuntimeDebug)]
pub struct VoterInfo<Balance> {
last_active: VoteIndex,
last_win: VoteIndex,
pot: Balance,
stake: Balance,
}
#[derive(PartialEq, Eq, RuntimeDebug)]
pub enum CellStatus {
Head,
Occupied,
Hole,
}
pub const VOTER_SET_SIZE: usize = 64;
pub const APPROVAL_SET_SIZE: usize = 8;
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type NegativeImbalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
type SetIndex = u32;
pub type VoteIndex = u32;
type ApprovalFlag = u32;
const APPROVAL_FLAG_LEN: usize = 32;
pub trait Config: frame_system::Config {
type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;
type ModuleId: Get<LockIdentifier>;
type Currency:
LockableCurrency<Self::AccountId, Moment=Self::BlockNumber>
+ ReservableCurrency<Self::AccountId>;
type BadPresentation: OnUnbalanced<NegativeImbalanceOf<Self>>;
type BadReaper: OnUnbalanced<NegativeImbalanceOf<Self>>;
type BadVoterIndex: OnUnbalanced<NegativeImbalanceOf<Self>>;
type LoserCandidate: OnUnbalanced<NegativeImbalanceOf<Self>>;
type ChangeMembers: ChangeMembers<Self::AccountId>;
type CandidacyBond: Get<BalanceOf<Self>>;
type VotingBond: Get<BalanceOf<Self>>;
type VotingFee: Get<BalanceOf<Self>>;
type MinimumVotingLock: Get<BalanceOf<Self>>;
type PresentSlashPerVoter: Get<BalanceOf<Self>>;
type CarryCount: Get<u32>;
type InactiveGracePeriod: Get<VoteIndex>;
type VotingPeriod: Get<Self::BlockNumber>;
type DecayRatio: Get<u32>;
}
decl_storage! {
trait Store for Module<T: Config> as Elections {
pub PresentationDuration get(fn presentation_duration) config(): T::BlockNumber;
pub TermDuration get(fn term_duration) config(): T::BlockNumber;
pub DesiredSeats get(fn desired_seats) config(): u32;
pub Members get(fn members) config(): Vec<(T::AccountId, T::BlockNumber)>;
pub VoteCount get(fn vote_index): VoteIndex;
pub ApprovalsOf get(fn approvals_of):
map hasher(twox_64_concat) (T::AccountId, SetIndex) => Vec<ApprovalFlag>;
pub RegisterInfoOf get(fn candidate_reg_info):
map hasher(twox_64_concat) T::AccountId => Option<(VoteIndex, u32)>;
pub VoterInfoOf get(fn voter_info):
map hasher(twox_64_concat) T::AccountId => Option<VoterInfo<BalanceOf<T>>>;
pub Voters get(fn voters): map hasher(twox_64_concat) SetIndex => Vec<Option<T::AccountId>>;
pub NextVoterSet get(fn next_nonfull_voter_set): SetIndex = 0;
pub VoterCount get(fn voter_count): SetIndex = 0;
pub Candidates get(fn candidates): Vec<T::AccountId>; pub CandidateCount get(fn candidate_count): u32;
pub NextFinalize get(fn next_finalize): Option<(T::BlockNumber, u32, Vec<T::AccountId>)>;
pub Leaderboard get(fn leaderboard): Option<Vec<(BalanceOf<T>, T::AccountId)> >;
}
}
decl_error! {
pub enum Error for Module<T: Config> {
NotVoter,
InactiveTarget,
CannotReapPresenting,
ReapGrace,
InvalidReporterIndex,
InvalidTargetIndex,
InvalidVoteIndex,
CannotRetractPresenting,
RetractNonVoter,
InvalidRetractionIndex,
DuplicatedCandidate,
InvalidCandidateSlot,
InsufficientCandidateFunds,
InsufficientPresenterFunds,
ZeroDeposit,
UnworthyCandidate,
LeaderboardMustExist,
NotPresentationPeriod,
InvalidCandidate,
DuplicatedPresentation,
IncorrectTotal,
InvalidVoterIndex,
InsufficientVoterFunds,
InsufficientLockedValue,
TooManyVotes,
ZeroCandidates,
ApprovalPresentation,
}
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
type Error = Error<T>;
const CandidacyBond: BalanceOf<T> = T::CandidacyBond::get();
const VotingBond: BalanceOf<T> = T::VotingBond::get();
const VotingFee: BalanceOf<T> = T::VotingFee::get();
const PresentSlashPerVoter: BalanceOf<T> = T::PresentSlashPerVoter::get();
const CarryCount: u32 = T::CarryCount::get();
const InactiveGracePeriod: VoteIndex = T::InactiveGracePeriod::get();
const VotingPeriod: T::BlockNumber = T::VotingPeriod::get();
const MinimumVotingLock: BalanceOf<T> = T::MinimumVotingLock::get();
const DecayRatio: u32 = T::DecayRatio::get();
const VOTER_SET_SIZE: u32 = VOTER_SET_SIZE as u32;
const APPROVAL_SET_SIZE: u32 = APPROVAL_SET_SIZE as u32;
const ModuleId: LockIdentifier = T::ModuleId::get();
fn deposit_event() = default;
#[weight = 2_500_000_000]
fn set_approvals(
origin,
votes: Vec<bool>,
#[compact] index: VoteIndex,
hint: SetIndex,
#[compact] value: BalanceOf<T>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::do_set_approvals(who, votes, index, hint, value)
}
#[weight = 2_500_000_000]
fn reap_inactive_voter(
origin,
#[compact] reporter_index: u32,
who: <T::Lookup as StaticLookup>::Source,
#[compact] who_index: u32,
#[compact] assumed_vote_index: VoteIndex,
) {
let reporter = ensure_signed(origin)?;
let who = T::Lookup::lookup(who)?;
ensure!(!Self::presentation_active(), Error::<T>::CannotReapPresenting);
ensure!(Self::voter_info(&reporter).is_some(), Error::<T>::NotVoter);
let info = Self::voter_info(&who).ok_or(Error::<T>::InactiveTarget)?;
let last_active = info.last_active;
ensure!(assumed_vote_index == Self::vote_index(), Error::<T>::InvalidVoteIndex);
ensure!(
assumed_vote_index > last_active + T::InactiveGracePeriod::get(),
Error::<T>::ReapGrace,
);
let reporter_index = reporter_index as usize;
let who_index = who_index as usize;
let assumed_reporter = Self::voter_at(reporter_index).ok_or(Error::<T>::InvalidReporterIndex)?;
let assumed_who = Self::voter_at(who_index).ok_or(Error::<T>::InvalidTargetIndex)?;
ensure!(assumed_reporter == reporter, Error::<T>::InvalidReporterIndex);
ensure!(assumed_who == who, Error::<T>::InvalidTargetIndex);
let valid = !Self::all_approvals_of(&who).iter()
.zip(Self::candidates().iter())
.any(|(&appr, addr)|
appr &&
*addr != T::AccountId::default() &&
Self::candidate_reg_info(addr).map_or(false, |x| x.0 <= last_active)
);
Self::remove_voter(
if valid { &who } else { &reporter },
if valid { who_index } else { reporter_index }
);
T::Currency::remove_lock(
T::ModuleId::get(),
if valid { &who } else { &reporter }
);
if valid {
T::Currency::repatriate_reserved(&who, &reporter, T::VotingBond::get(), BalanceStatus::Free)?;
Self::deposit_event(RawEvent::VoterReaped(who, reporter));
} else {
let imbalance = T::Currency::slash_reserved(&reporter, T::VotingBond::get()).0;
T::BadReaper::on_unbalanced(imbalance);
Self::deposit_event(RawEvent::BadReaperSlashed(reporter));
}
}
#[weight = 1_250_000_000]
fn retract_voter(origin, #[compact] index: u32) {
let who = ensure_signed(origin)?;
ensure!(!Self::presentation_active(), Error::<T>::CannotRetractPresenting);
ensure!(<VoterInfoOf<T>>::contains_key(&who), Error::<T>::RetractNonVoter);
let index = index as usize;
let voter = Self::voter_at(index).ok_or(Error::<T>::InvalidRetractionIndex)?;
ensure!(voter == who, Error::<T>::InvalidRetractionIndex);
Self::remove_voter(&who, index);
T::Currency::unreserve(&who, T::VotingBond::get());
T::Currency::remove_lock(T::ModuleId::get(), &who);
}
#[weight = 2_500_000_000]
fn submit_candidacy(origin, #[compact] slot: u32) {
let who = ensure_signed(origin)?;
ensure!(!Self::is_a_candidate(&who), Error::<T>::DuplicatedCandidate);
let slot = slot as usize;
let count = Self::candidate_count() as usize;
let candidates = Self::candidates();
ensure!(
(slot == count && count == candidates.len()) ||
(slot < candidates.len() && candidates[slot] == T::AccountId::default()),
Error::<T>::InvalidCandidateSlot,
);
T::Currency::reserve(&who, T::CandidacyBond::get())
.map_err(|_| Error::<T>::InsufficientCandidateFunds)?;
<RegisterInfoOf<T>>::insert(&who, (Self::vote_index(), slot as u32));
let mut candidates = candidates;
if slot == candidates.len() {
candidates.push(who);
} else {
candidates[slot] = who;
}
<Candidates<T>>::put(candidates);
CandidateCount::put(count as u32 + 1);
}
#[weight = 10_000_000_000]
fn present_winner(
origin,
candidate: <T::Lookup as StaticLookup>::Source,
#[compact] total: BalanceOf<T>,
#[compact] index: VoteIndex,
) -> DispatchResult {
let who = ensure_signed(origin)?;
ensure!(
!total.is_zero(),
Error::<T>::ZeroDeposit,
);
let candidate = T::Lookup::lookup(candidate)?;
ensure!(index == Self::vote_index(), Error::<T>::InvalidVoteIndex);
let (_, _, expiring) = Self::next_finalize()
.ok_or(Error::<T>::NotPresentationPeriod)?;
let bad_presentation_punishment =
T::PresentSlashPerVoter::get()
* BalanceOf::<T>::from(Self::voter_count() as u32);
ensure!(
T::Currency::can_slash(&who, bad_presentation_punishment),
Error::<T>::InsufficientPresenterFunds,
);
let mut leaderboard = Self::leaderboard()
.ok_or(Error::<T>::LeaderboardMustExist)?;
ensure!(total > leaderboard[0].0, Error::<T>::UnworthyCandidate);
if let Some(p) = Self::members().iter().position(|&(ref c, _)| c == &candidate) {
ensure!(
p < expiring.len(),
Error::<T>::DuplicatedCandidate,
);
}
let voters = Self::all_voters();
let (registered_since, candidate_index): (VoteIndex, u32) =
Self::candidate_reg_info(&candidate).ok_or(Error::<T>::InvalidCandidate)?;
let actual_total = voters.iter()
.filter_map(|maybe_voter| maybe_voter.as_ref())
.filter_map(|voter| match Self::voter_info(voter) {
Some(b) if b.last_active >= registered_since => {
let last_win = b.last_win;
let now = Self::vote_index();
let stake = b.stake;
let offset = Self::get_offset(stake, now - last_win);
let weight = stake + offset + b.pot;
if Self::approvals_of_at(voter, candidate_index as usize) {
Some(weight)
} else { None }
},
_ => None,
})
.fold(Zero::zero(), |acc, n| acc + n);
let dupe = leaderboard.iter().find(|&&(_, ref c)| c == &candidate).is_some();
if total == actual_total && !dupe {
leaderboard[0] = (total, candidate);
leaderboard.sort_by_key(|&(t, _)| t);
<Leaderboard<T>>::put(leaderboard);
Ok(())
} else {
let imbalance = T::Currency::slash(&who, bad_presentation_punishment).0;
T::BadPresentation::on_unbalanced(imbalance);
Err(if dupe { Error::<T>::DuplicatedPresentation } else { Error::<T>::IncorrectTotal })?
}
}
#[weight = (0, DispatchClass::Operational)]
fn set_desired_seats(origin, #[compact] count: u32) {
ensure_root(origin)?;
DesiredSeats::put(count);
}
#[weight = (0, DispatchClass::Operational)]
fn remove_member(origin, who: <T::Lookup as StaticLookup>::Source) {
ensure_root(origin)?;
let who = T::Lookup::lookup(who)?;
let new_set: Vec<(T::AccountId, T::BlockNumber)> = Self::members()
.into_iter()
.filter(|i| i.0 != who)
.collect();
<Members<T>>::put(&new_set);
let new_set = new_set.into_iter().map(|x| x.0).collect::<Vec<_>>();
T::ChangeMembers::change_members(&[], &[who], new_set);
}
#[weight = (0, DispatchClass::Operational)]
fn set_presentation_duration(origin, #[compact] count: T::BlockNumber) {
ensure_root(origin)?;
<PresentationDuration<T>>::put(count);
}
#[weight = (0, DispatchClass::Operational)]
fn set_term_duration(origin, #[compact] count: T::BlockNumber) {
ensure_root(origin)?;
<TermDuration<T>>::put(count);
}
fn on_initialize(n: T::BlockNumber) -> Weight {
if let Err(e) = Self::end_block(n) {
print("Guru meditation");
print(e);
}
0
}
}
}
decl_event!(
pub enum Event<T> where <T as frame_system::Config>::AccountId {
VoterReaped(AccountId, AccountId),
BadReaperSlashed(AccountId),
TallyStarted(u32),
TallyFinalized(Vec<AccountId>, Vec<AccountId>),
}
);
impl<T: Config> Module<T> {
pub fn presentation_active() -> bool {
<NextFinalize<T>>::exists()
}
pub fn is_a_candidate(who: &T::AccountId) -> bool {
<RegisterInfoOf<T>>::contains_key(who)
}
pub fn will_still_be_member_at(who: &T::AccountId, n: T::BlockNumber) -> bool {
Self::members().iter()
.find(|&&(ref a, _)| a == who)
.map(|&(_, expires)| expires > n)
.unwrap_or(false)
}
pub fn next_vote_from(n: T::BlockNumber) -> T::BlockNumber {
let voting_period = T::VotingPeriod::get();
(n + voting_period - One::one()) / voting_period * voting_period
}
pub fn next_tally() -> Option<T::BlockNumber> {
let desired_seats = Self::desired_seats();
if desired_seats == 0 {
None
} else {
let c = Self::members();
let (next_possible, count, coming) =
if let Some((tally_end, comers, leavers)) = Self::next_finalize() {
(tally_end, c.len() - leavers.len() + comers as usize, comers)
} else {
(<frame_system::Module<T>>::block_number(), c.len(), 0)
};
if count < desired_seats as usize {
Some(next_possible)
} else {
if desired_seats <= coming {
Some(next_possible + Self::term_duration())
} else {
Some(c[c.len() - (desired_seats - coming) as usize].1)
}
}.map(Self::next_vote_from)
}
}
fn end_block(block_number: T::BlockNumber) -> DispatchResult {
if (block_number % T::VotingPeriod::get()).is_zero() {
if let Some(number) = Self::next_tally() {
if block_number == number {
Self::start_tally();
}
}
}
if let Some((number, _, _)) = Self::next_finalize() {
if block_number == number {
Self::finalize_tally()?
}
}
Ok(())
}
fn remove_voter(voter: &T::AccountId, index: usize) {
let (set_index, vec_index) = Self::split_index(index, VOTER_SET_SIZE);
let mut set = Self::voters(set_index);
set[vec_index] = None;
<Voters<T>>::insert(set_index, set);
VoterCount::mutate(|c| *c = *c - 1);
Self::remove_all_approvals_of(voter);
<VoterInfoOf<T>>::remove(voter);
}
fn do_set_approvals(
who: T::AccountId,
votes: Vec<bool>,
index: VoteIndex,
hint: SetIndex,
value: BalanceOf<T>,
) -> DispatchResult {
let candidates_len = <Self as Store>::Candidates::decode_len().unwrap_or(0_usize);
ensure!(!Self::presentation_active(), Error::<T>::ApprovalPresentation);
ensure!(index == Self::vote_index(), Error::<T>::InvalidVoteIndex);
ensure!(
!candidates_len.is_zero(),
Error::<T>::ZeroCandidates,
);
ensure!(
candidates_len >= votes.len(),
Error::<T>::TooManyVotes,
);
ensure!(value >= T::MinimumVotingLock::get(), Error::<T>::InsufficientLockedValue);
let mut locked_balance = value.min(T::Currency::total_balance(&who));
let mut pot_to_set = Zero::zero();
let hint = hint as usize;
if let Some(info) = Self::voter_info(&who) {
let voter = Self::voter_at(hint).ok_or(Error::<T>::InvalidVoterIndex)?;
ensure!(voter == who, Error::<T>::InvalidVoterIndex);
let last_win = info.last_win;
let now = index;
let offset = Self::get_offset(info.stake, now - last_win);
pot_to_set = info.pot + offset;
} else {
ensure!(
T::Currency::free_balance(&who) > T::VotingBond::get(),
Error::<T>::InsufficientVoterFunds,
);
let (set_index, vec_index) = Self::split_index(hint, VOTER_SET_SIZE);
match Self::cell_status(set_index, vec_index) {
CellStatus::Hole => {
<Voters<T>>::mutate(set_index, |set| set[vec_index] = Some(who.clone()));
},
CellStatus::Head | CellStatus::Occupied => {
let next = Self::next_nonfull_voter_set();
let set_len = <Voters<T>>::decode_len(next).unwrap_or(0_usize);
if set_len == 0 {
let imbalance = T::Currency::withdraw(
&who,
T::VotingFee::get(),
WithdrawReasons::FEE,
ExistenceRequirement::KeepAlive,
)?;
T::BadVoterIndex::on_unbalanced(imbalance);
locked_balance -= T::VotingFee::get();
}
if set_len + 1 == VOTER_SET_SIZE {
NextVoterSet::put(next + 1);
}
<Voters<T>>::append(next, Some(who.clone()));
}
}
T::Currency::reserve(&who, T::VotingBond::get())?;
VoterCount::mutate(|c| *c = *c + 1);
}
T::Currency::set_lock(
T::ModuleId::get(),
&who,
locked_balance,
WithdrawReasons::all(),
);
<VoterInfoOf<T>>::insert(
&who,
VoterInfo::<BalanceOf<T>> {
last_active: index,
last_win: index,
stake: locked_balance,
pot: pot_to_set,
}
);
Self::set_approvals_chunked(&who, votes);
Ok(())
}
fn start_tally() {
let members = Self::members();
let desired_seats = Self::desired_seats() as usize;
let number = <frame_system::Module<T>>::block_number();
let expiring =
members.iter().take_while(|i| i.1 <= number).map(|i| i.0.clone()).collect::<Vec<_>>();
let retaining_seats = members.len() - expiring.len();
if retaining_seats < desired_seats {
let empty_seats = desired_seats - retaining_seats;
<NextFinalize<T>>::put(
(number + Self::presentation_duration(), empty_seats as u32, expiring)
);
let leaderboard_size = empty_seats + T::CarryCount::get() as usize;
<Leaderboard<T>>::put(vec![(BalanceOf::<T>::zero(), T::AccountId::default()); leaderboard_size]);
Self::deposit_event(RawEvent::TallyStarted(empty_seats as u32));
}
}
fn finalize_tally() -> DispatchResult {
let (_, coming, expiring): (T::BlockNumber, u32, Vec<T::AccountId>) =
<NextFinalize<T>>::take()
.ok_or("finalize can only be called after a tally is started.")?;
let leaderboard: Vec<(BalanceOf<T>, T::AccountId)> = <Leaderboard<T>>::take()
.unwrap_or_default();
let new_expiry = <frame_system::Module<T>>::block_number() + Self::term_duration();
let candidacy_bond = T::CandidacyBond::get();
let incoming: Vec<_> = leaderboard.iter()
.rev()
.take_while(|&&(b, _)| !b.is_zero())
.take(coming as usize)
.map(|(_, a)| a)
.cloned()
.inspect(|a| { T::Currency::unreserve(a, candidacy_bond); })
.collect();
incoming.iter().filter_map(|i| Self::candidate_reg_info(i)).for_each(|r| {
let index = r.1 as usize;
Self::all_voters()
.iter()
.filter_map(|mv| mv.as_ref())
.filter(|v| Self::approvals_of_at(*v, index))
.for_each(|v| <VoterInfoOf<T>>::mutate(v, |a| {
if let Some(activity) = a { activity.last_win = Self::vote_index() + 1; }
}));
});
let members = Self::members();
let outgoing: Vec<_> = members.iter()
.take(expiring.len())
.map(|a| a.0.clone()).collect();
let mut new_set: Vec<_> = members
.into_iter()
.skip(expiring.len())
.chain(incoming.iter().cloned().map(|a| (a, new_expiry)))
.collect();
new_set.sort_by_key(|&(_, expiry)| expiry);
<Members<T>>::put(&new_set);
let new_set = new_set.into_iter().map(|x| x.0).collect::<Vec<_>>();
T::ChangeMembers::change_members(&incoming, &outgoing, new_set);
let candidates = Self::candidates();
let mut new_candidates = vec![T::AccountId::default(); candidates.len()]; let runners_up = leaderboard.into_iter()
.rev()
.take_while(|&(b, _)| !b.is_zero())
.skip(coming as usize)
.filter_map(|(_, a)| Self::candidate_reg_info(&a).map(|i| (a, i.1)));
let mut count = 0u32;
for (address, slot) in runners_up {
new_candidates[slot as usize] = address;
count += 1;
}
for (old, new) in candidates.iter().zip(new_candidates.iter()) {
if old != new {
<RegisterInfoOf<T>>::remove(old);
if incoming.iter().find(|e| *e == old).is_none() {
let (imbalance, _) = T::Currency::slash_reserved(&old, T::CandidacyBond::get());
T::LoserCandidate::on_unbalanced(imbalance);
}
}
}
if let Some(last_index) = new_candidates
.iter()
.rposition(|c| *c != T::AccountId::default()) {
new_candidates.truncate(last_index + 1);
}
Self::deposit_event(RawEvent::TallyFinalized(incoming, outgoing));
<Candidates<T>>::put(new_candidates);
CandidateCount::put(count);
VoteCount::put(Self::vote_index() + 1);
Ok(())
}
fn split_index(index: usize, scale: usize) -> (SetIndex, usize) {
let set_index = (index / scale) as u32;
let vec_index = index % scale;
(set_index, vec_index)
}
fn all_voters() -> Vec<Option<T::AccountId>> {
let mut all = <Voters<T>>::get(0);
let mut index = 1;
loop {
let next_set = <Voters<T>>::get(index);
if next_set.is_empty() {
break;
} else {
index += 1;
all.extend(next_set);
}
}
all
}
fn voter_at(index: usize) -> Option<T::AccountId> {
let (set_index, vec_index) = Self::split_index(index, VOTER_SET_SIZE);
let set = Self::voters(set_index);
if vec_index < set.len() {
set[vec_index].clone()
} else {
None
}
}
fn cell_status(set_index: SetIndex, vec_index: usize) -> CellStatus {
let set = Self::voters(set_index);
if vec_index < set.len() {
if let Some(_) = set[vec_index] {
CellStatus::Occupied
} else {
CellStatus::Hole
}
} else {
CellStatus::Head
}
}
fn set_approvals_chunked(who: &T::AccountId, approvals: Vec<bool>) {
let approvals_flag_vec = Self::bool_to_flag(approvals);
approvals_flag_vec
.chunks(APPROVAL_SET_SIZE)
.enumerate()
.for_each(|(index, slice)| <ApprovalsOf<T>>::insert(
(&who, index as SetIndex), slice)
);
}
fn approvals_of_at(who: &T::AccountId, index: usize) -> bool {
let (flag_index, bit) = Self::split_index(index, APPROVAL_FLAG_LEN);
let (set_index, vec_index) = Self::split_index(flag_index as usize, APPROVAL_SET_SIZE);
let set = Self::approvals_of((who.clone(), set_index));
if vec_index < set.len() {
let reversed_index = set.len() - 1 - vec_index;
Self::bit_at(set[reversed_index], bit)
} else {
false
}
}
fn bit_at(x: ApprovalFlag, n: usize) -> bool {
if n < APPROVAL_FLAG_LEN {
x & ( 1 << n ) != 0
} else {
false
}
}
pub fn bool_to_flag(x: Vec<bool>) -> Vec<ApprovalFlag> {
let mut result: Vec<ApprovalFlag> = Vec::with_capacity(x.len() / APPROVAL_FLAG_LEN);
if x.is_empty() {
return result;
}
result.push(0);
let mut index = 0;
let mut counter = 0;
loop {
let shl_index = counter % APPROVAL_FLAG_LEN;
result[index] += (if x[counter] { 1 } else { 0 }) << shl_index;
counter += 1;
if counter > x.len() - 1 { break; }
if counter % APPROVAL_FLAG_LEN == 0 {
result.push(0);
index += 1;
}
}
result
}
pub fn flag_to_bool(chunk: Vec<ApprovalFlag>) -> Vec<bool> {
let mut result = Vec::with_capacity(chunk.len());
if chunk.is_empty() { return vec![] }
chunk.into_iter()
.map(|num|
(0..APPROVAL_FLAG_LEN).map(|bit| Self::bit_at(num, bit)).collect::<Vec<bool>>()
)
.for_each(|c| {
let last_approve = match c.iter().rposition(|n| *n) {
Some(index) => index + 1,
None => 0
};
result.extend(c.into_iter().take(last_approve));
});
result
}
fn all_approvals_of(who: &T::AccountId) -> Vec<bool> {
let mut all: Vec<bool> = vec![];
let mut index = 0_u32;
loop {
let chunk = Self::approvals_of((who.clone(), index));
if chunk.is_empty() { break; }
all.extend(Self::flag_to_bool(chunk));
index += 1;
}
all
}
fn remove_all_approvals_of(who: &T::AccountId) {
let mut index = 0;
loop {
let set = Self::approvals_of((who.clone(), index));
if set.len() > 0 {
<ApprovalsOf<T>>::remove((who.clone(), index));
index += 1;
} else {
break
}
}
}
fn get_offset(stake: BalanceOf<T>, t: VoteIndex) -> BalanceOf<T> {
let decay_ratio: BalanceOf<T> = T::DecayRatio::get().into();
if t > 150 { return stake * decay_ratio }
let mut offset = stake;
let mut r = Zero::zero();
let decay = decay_ratio + One::one();
for _ in 0..t {
offset = offset.saturating_sub(offset / decay);
r += offset
}
r
}
}