Redesign Democracy pallet (#5294)

* Repot a bit of democracy code

* Basic logic is drafted

* Lazy democracy builds.

* Add non-locked split-voting and instant-scheduling.

* Introduce delegation that works.

* Builds again.

* Indentation

* Building.

* Docs and migration

* Fix half of the tests

* Fix up & repot tests

* Fix runtime build

* Update docs

* Docs

* Nits.

* Turnout counts full capital

* Delegations could towards capital

* proxy delegation & proxy unvoting

* Fix

* Tests for split-voting

* Add missing file

* Persistent locking.
This commit is contained in:
Gavin Wood
2020-03-21 16:08:48 +01:00
committed by GitHub
parent 40f57f8ffa
commit 22f88bf9d1
19 changed files with 3080 additions and 1821 deletions
+6 -2
View File
@@ -68,6 +68,7 @@ use impls::{CurrencyToVoteHandler, Author, LinearWeightToFee, TargetedFeeAdjustm
/// Constant values used within the runtime.
pub mod constants;
use constants::{time::*, currency::*};
use frame_system::Trait;
// Make the WASM binary available.
#[cfg(feature = "std")]
@@ -302,7 +303,8 @@ impl pallet_staking::Trait for Runtime {
parameter_types! {
pub const LaunchPeriod: BlockNumber = 28 * 24 * 60 * MINUTES;
pub const VotingPeriod: BlockNumber = 28 * 24 * 60 * MINUTES;
pub const EmergencyVotingPeriod: BlockNumber = 3 * 24 * 60 * MINUTES;
pub const FastTrackVotingPeriod: BlockNumber = 3 * 24 * 60 * MINUTES;
pub const InstantAllowed: bool = true;
pub const MinimumDeposit: Balance = 100 * DOLLARS;
pub const EnactmentPeriod: BlockNumber = 30 * 24 * 60 * MINUTES;
pub const CooloffPeriod: BlockNumber = 28 * 24 * 60 * MINUTES;
@@ -328,7 +330,9 @@ impl pallet_democracy::Trait for Runtime {
/// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote
/// be tabled immediately and with a shorter voting/enactment period.
type FastTrackOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>;
type EmergencyVotingPeriod = EmergencyVotingPeriod;
type InstantOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>;
type InstantAllowed = InstantAllowed;
type FastTrackVotingPeriod = FastTrackVotingPeriod;
// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
type CancellationOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>;
// Any single technical committee member may veto a coming council proposal, however they can
+113
View File
@@ -0,0 +1,113 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The conviction datatype.
use sp_std::{result::Result, convert::TryFrom};
use sp_runtime::{RuntimeDebug, traits::{Zero, Bounded, CheckedMul, CheckedDiv}};
use codec::{Encode, Decode};
use crate::types::Delegations;
/// A value denoting the strength of conviction of a vote.
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug)]
pub enum Conviction {
/// 0.1x votes, unlocked.
None,
/// 1x votes, locked for an enactment period following a successful vote.
Locked1x,
/// 2x votes, locked for 2x enactment periods following a successful vote.
Locked2x,
/// 3x votes, locked for 4x...
Locked3x,
/// 4x votes, locked for 8x...
Locked4x,
/// 5x votes, locked for 16x...
Locked5x,
/// 6x votes, locked for 32x...
Locked6x,
}
impl Default for Conviction {
fn default() -> Self {
Conviction::None
}
}
impl From<Conviction> for u8 {
fn from(c: Conviction) -> u8 {
match c {
Conviction::None => 0,
Conviction::Locked1x => 1,
Conviction::Locked2x => 2,
Conviction::Locked3x => 3,
Conviction::Locked4x => 4,
Conviction::Locked5x => 5,
Conviction::Locked6x => 6,
}
}
}
impl TryFrom<u8> for Conviction {
type Error = ();
fn try_from(i: u8) -> Result<Conviction, ()> {
Ok(match i {
0 => Conviction::None,
1 => Conviction::Locked1x,
2 => Conviction::Locked2x,
3 => Conviction::Locked3x,
4 => Conviction::Locked4x,
5 => Conviction::Locked5x,
6 => Conviction::Locked6x,
_ => return Err(()),
})
}
}
impl Conviction {
/// The amount of time (in number of periods) that our conviction implies a successful voter's
/// balance should be locked for.
pub fn lock_periods(self) -> u32 {
match self {
Conviction::None => 0,
Conviction::Locked1x => 1,
Conviction::Locked2x => 2,
Conviction::Locked3x => 4,
Conviction::Locked4x => 8,
Conviction::Locked5x => 16,
Conviction::Locked6x => 32,
}
}
/// The votes of a voter of the given `balance` with our conviction.
pub fn votes<
B: From<u8> + Zero + Copy + CheckedMul + CheckedDiv + Bounded
>(self, capital: B) -> Delegations<B> {
let votes = match self {
Conviction::None => capital.checked_div(&10u8.into()).unwrap_or_else(Zero::zero),
x => capital.checked_mul(&u8::from(x).into()).unwrap_or_else(B::max_value),
};
Delegations { votes, capital }
}
}
impl Bounded for Conviction {
fn min_value() -> Self {
Conviction::None
}
fn max_value() -> Self {
Conviction::Locked6x
}
}
File diff suppressed because it is too large Load Diff
+250
View File
@@ -0,0 +1,250 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The crate's tests.
use super::*;
use std::cell::RefCell;
use codec::Encode;
use frame_support::{
impl_outer_origin, impl_outer_dispatch, assert_noop, assert_ok, parameter_types,
ord_parameter_types, traits::Contains, weights::Weight,
};
use sp_core::H256;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup, BadOrigin},
testing::Header, Perbill,
};
use pallet_balances::{BalanceLock, Error as BalancesError};
use frame_system::EnsureSignedBy;
mod cancellation;
mod delegation;
mod external_proposing;
mod fast_tracking;
mod lock_voting;
mod preimage;
mod proxying;
mod public_proposals;
mod scheduling;
mod voting;
const AYE: Vote = Vote { aye: true, conviction: Conviction::None };
const NAY: Vote = Vote { aye: false, conviction: Conviction::None };
const BIG_AYE: Vote = Vote { aye: true, conviction: Conviction::Locked1x };
const BIG_NAY: Vote = Vote { aye: false, conviction: Conviction::Locked1x };
impl_outer_origin! {
pub enum Origin for Test where system = frame_system {}
}
impl_outer_dispatch! {
pub enum Call for Test where origin: Origin {
pallet_balances::Balances,
democracy::Democracy,
}
}
// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl frame_system::Trait for Test {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Call = ();
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
}
parameter_types! {
pub const ExistentialDeposit: u64 = 1;
}
impl pallet_balances::Trait for Test {
type Balance = u64;
type Event = ();
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
}
parameter_types! {
pub const LaunchPeriod: u64 = 2;
pub const VotingPeriod: u64 = 2;
pub const FastTrackVotingPeriod: u64 = 2;
pub const MinimumDeposit: u64 = 1;
pub const EnactmentPeriod: u64 = 2;
pub const CooloffPeriod: u64 = 2;
}
ord_parameter_types! {
pub const One: u64 = 1;
pub const Two: u64 = 2;
pub const Three: u64 = 3;
pub const Four: u64 = 4;
pub const Five: u64 = 5;
pub const Six: u64 = 6;
}
pub struct OneToFive;
impl Contains<u64> for OneToFive {
fn sorted_members() -> Vec<u64> {
vec![1, 2, 3, 4, 5]
}
}
thread_local! {
static PREIMAGE_BYTE_DEPOSIT: RefCell<u64> = RefCell::new(0);
static INSTANT_ALLOWED: RefCell<bool> = RefCell::new(false);
}
pub struct PreimageByteDeposit;
impl Get<u64> for PreimageByteDeposit {
fn get() -> u64 { PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow()) }
}
pub struct InstantAllowed;
impl Get<bool> for InstantAllowed {
fn get() -> bool { INSTANT_ALLOWED.with(|v| *v.borrow()) }
}
impl super::Trait for Test {
type Proposal = Call;
type Event = ();
type Currency = pallet_balances::Module<Self>;
type EnactmentPeriod = EnactmentPeriod;
type LaunchPeriod = LaunchPeriod;
type VotingPeriod = VotingPeriod;
type FastTrackVotingPeriod = FastTrackVotingPeriod;
type MinimumDeposit = MinimumDeposit;
type ExternalOrigin = EnsureSignedBy<Two, u64>;
type ExternalMajorityOrigin = EnsureSignedBy<Three, u64>;
type ExternalDefaultOrigin = EnsureSignedBy<One, u64>;
type FastTrackOrigin = EnsureSignedBy<Five, u64>;
type CancellationOrigin = EnsureSignedBy<Four, u64>;
type VetoOrigin = EnsureSignedBy<OneToFive, u64>;
type CooloffPeriod = CooloffPeriod;
type PreimageByteDeposit = PreimageByteDeposit;
type Slash = ();
type InstantOrigin = EnsureSignedBy<Six, u64>;
type InstantAllowed = InstantAllowed;
}
fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
pallet_balances::GenesisConfig::<Test>{
balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)],
}.assimilate_storage(&mut t).unwrap();
GenesisConfig::default().assimilate_storage(&mut t).unwrap();
sp_io::TestExternalities::new(t)
}
type System = frame_system::Module<Test>;
type Balances = pallet_balances::Module<Test>;
type Democracy = Module<Test>;
#[test]
fn params_should_work() {
new_test_ext().execute_with(|| {
assert_eq!(Democracy::referendum_count(), 0);
assert_eq!(Balances::free_balance(42), 0);
assert_eq!(Balances::total_issuance(), 210);
});
}
fn set_balance_proposal(value: u64) -> Vec<u8> {
Call::Balances(pallet_balances::Call::set_balance(42, value, 0)).encode()
}
fn set_balance_proposal_hash(value: u64) -> H256 {
BlakeTwo256::hash(&set_balance_proposal(value)[..])
}
fn set_balance_proposal_hash_and_note(value: u64) -> H256 {
let p = set_balance_proposal(value);
let h = BlakeTwo256::hash(&p[..]);
match Democracy::note_preimage(Origin::signed(6), p) {
Ok(_) => (),
Err(x) if x == Error::<Test>::DuplicatePreimage.into() => (),
Err(x) => panic!(x),
}
h
}
fn propose_set_balance(who: u64, value: u64, delay: u64) -> DispatchResult {
Democracy::propose(
Origin::signed(who),
set_balance_proposal_hash(value),
delay
)
}
fn propose_set_balance_and_note(who: u64, value: u64, delay: u64) -> DispatchResult {
Democracy::propose(
Origin::signed(who),
set_balance_proposal_hash_and_note(value),
delay
)
}
fn next_block() {
System::set_block_number(System::block_number() + 1);
assert_eq!(Democracy::begin_block(System::block_number()), Ok(()));
}
fn fast_forward_to(n: u64) {
while System::block_number() < n {
next_block();
}
}
fn begin_referendum() -> ReferendumIndex {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
fast_forward_to(2);
0
}
fn aye(who: u64) -> AccountVote<u64> {
AccountVote::Standard { vote: AYE, balance: Balances::free_balance(&who) }
}
fn nay(who: u64) -> AccountVote<u64> {
AccountVote::Standard { vote: NAY, balance: Balances::free_balance(&who) }
}
fn big_aye(who: u64) -> AccountVote<u64> {
AccountVote::Standard { vote: BIG_AYE, balance: Balances::free_balance(&who) }
}
fn big_nay(who: u64) -> AccountVote<u64> {
AccountVote::Standard { vote: BIG_NAY, balance: Balances::free_balance(&who) }
}
fn tally(r: ReferendumIndex) -> Tally<u64> {
Democracy::referendum_status(r).unwrap().tally
}
@@ -0,0 +1,94 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for cancelation functionality.
use super::*;
#[test]
fn cancel_referendum_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_ok!(Democracy::cancel_referendum(Origin::ROOT, r.into()));
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 0);
});
}
#[test]
fn cancel_queued_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
// start of 2 => next referendum scheduled.
fast_forward_to(2);
assert_ok!(Democracy::vote(Origin::signed(1), 0, aye(1)));
fast_forward_to(4);
assert_eq!(Democracy::dispatch_queue(), vec![
(6, set_balance_proposal_hash_and_note(2), 0)
]);
assert_noop!(Democracy::cancel_queued(Origin::ROOT, 1), Error::<Test>::ProposalMissing);
assert_ok!(Democracy::cancel_queued(Origin::ROOT, 0));
assert_eq!(Democracy::dispatch_queue(), vec![]);
});
}
#[test]
fn emergency_cancel_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
2
);
assert!(Democracy::referendum_status(r).is_ok());
assert_noop!(Democracy::emergency_cancel(Origin::signed(3), r), BadOrigin);
assert_ok!(Democracy::emergency_cancel(Origin::signed(4), r));
assert!(Democracy::referendum_info(r).is_none());
// some time later...
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
2
);
assert!(Democracy::referendum_status(r).is_ok());
assert_noop!(
Democracy::emergency_cancel(Origin::signed(4), r),
Error::<Test>::AlreadyCanceled,
);
});
}
@@ -0,0 +1,178 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for functionality concerning delegation.
use super::*;
#[test]
fn single_proposal_should_work_with_delegation() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
fast_forward_to(2);
// Delegate first vote.
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20));
let r = 0;
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 });
// Delegate a second vote.
assert_ok!(Democracy::delegate(Origin::signed(3), 1, Conviction::None, 30));
assert_eq!(tally(r), Tally { ayes: 6, nays: 0, turnout: 60 });
// Reduce first vote.
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 10));
assert_eq!(tally(r), Tally { ayes: 5, nays: 0, turnout: 50 });
// Second vote delegates to first; we don't do tiered delegation, so it doesn't get used.
assert_ok!(Democracy::delegate(Origin::signed(3), 2, Conviction::None, 30));
assert_eq!(tally(r), Tally { ayes: 2, nays: 0, turnout: 20 });
// Main voter cancels their vote
assert_ok!(Democracy::remove_vote(Origin::signed(1), r));
assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 });
// First delegator delegates half funds with conviction; nothing changes yet.
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked1x, 10));
assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 });
// Main voter reinstates their vote
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_eq!(tally(r), Tally { ayes: 11, nays: 0, turnout: 20 });
});
}
#[test]
fn self_delegation_not_allowed() {
new_test_ext().execute_with(|| {
assert_noop!(
Democracy::delegate(Origin::signed(1), 1, Conviction::None, 10),
Error::<Test>::Nonsense,
);
});
}
#[test]
fn cyclic_delegation_should_unwind() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
fast_forward_to(2);
// Check behavior with cycle.
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20));
assert_ok!(Democracy::delegate(Origin::signed(3), 2, Conviction::None, 30));
assert_ok!(Democracy::delegate(Origin::signed(1), 3, Conviction::None, 10));
let r = 0;
assert_ok!(Democracy::undelegate(Origin::signed(3)));
assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3)));
assert_ok!(Democracy::undelegate(Origin::signed(1)));
assert_ok!(Democracy::vote(Origin::signed(1), r, nay(1)));
// Delegated vote is counted.
assert_eq!(tally(r), Tally { ayes: 3, nays: 3, turnout: 60 });
});
}
#[test]
fn single_proposal_should_work_with_vote_and_delegation() {
// If transactor already voted, delegated vote is overwritten.
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
fast_forward_to(2);
let r = 0;
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_ok!(Democracy::vote(Origin::signed(2), r, nay(2)));
assert_eq!(tally(r), Tally { ayes: 1, nays: 2, turnout: 30 });
// Delegate vote.
assert_ok!(Democracy::remove_vote(Origin::signed(2), r));
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20));
// Delegated vote replaces the explicit vote.
assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 });
});
}
#[test]
fn single_proposal_should_work_with_undelegation() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
// Delegate and undelegate vote.
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20));
assert_ok!(Democracy::undelegate(Origin::signed(2)));
fast_forward_to(2);
let r = 0;
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
// Delegated vote is not counted.
assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 });
});
}
#[test]
fn single_proposal_should_work_with_delegation_and_vote() {
// If transactor voted, delegated vote is overwritten.
new_test_ext().execute_with(|| {
let r = begin_referendum();
// Delegate, undelegate and vote.
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20));
assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 });
assert_ok!(Democracy::undelegate(Origin::signed(2)));
assert_ok!(Democracy::vote(Origin::signed(2), r, aye(2)));
// Delegated vote is not counted.
assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 });
});
}
#[test]
fn conviction_should_be_honored_in_delegation() {
// If transactor voted, delegated vote is overwritten.
new_test_ext().execute_with(|| {
let r = begin_referendum();
// Delegate, undelegate and vote.
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked6x, 20));
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
// Delegated vote is huge.
assert_eq!(tally(r), Tally { ayes: 121, nays: 0, turnout: 30 });
});
}
#[test]
fn split_vote_delegation_should_be_ignored() {
// If transactor voted, delegated vote is overwritten.
new_test_ext().execute_with(|| {
let r = begin_referendum();
assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked6x, 20));
assert_ok!(Democracy::vote(Origin::signed(1), r, AccountVote::Split { aye: 10, nay: 0 }));
// Delegated vote is huge.
assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 });
});
}
@@ -0,0 +1,289 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for functionality concerning the "external" origin.
use super::*;
#[test]
fn veto_external_works() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(2),
));
assert!(<NextExternal<Test>>::exists());
let h = set_balance_proposal_hash_and_note(2);
assert_ok!(Democracy::veto_external(Origin::signed(3), h.clone()));
// cancelled.
assert!(!<NextExternal<Test>>::exists());
// fails - same proposal can't be resubmitted.
assert_noop!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash(2),
), Error::<Test>::ProposalBlacklisted);
fast_forward_to(1);
// fails as we're still in cooloff period.
assert_noop!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash(2),
), Error::<Test>::ProposalBlacklisted);
fast_forward_to(2);
// works; as we're out of the cooloff period.
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(2),
));
assert!(<NextExternal<Test>>::exists());
// 3 can't veto the same thing twice.
assert_noop!(
Democracy::veto_external(Origin::signed(3), h.clone()),
Error::<Test>::AlreadyVetoed
);
// 4 vetoes.
assert_ok!(Democracy::veto_external(Origin::signed(4), h.clone()));
// cancelled again.
assert!(!<NextExternal<Test>>::exists());
fast_forward_to(3);
// same proposal fails as we're still in cooloff
assert_noop!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash(2),
), Error::<Test>::ProposalBlacklisted);
// different proposal works fine.
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(3),
));
});
}
#[test]
fn external_referendum_works() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_noop!(
Democracy::external_propose(
Origin::signed(1),
set_balance_proposal_hash(2),
),
BadOrigin,
);
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(2),
));
assert_noop!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash(1),
), Error::<Test>::DuplicateProposal);
fast_forward_to(2);
assert_eq!(
Democracy::referendum_status(0),
Ok(ReferendumStatus {
end: 4,
proposal_hash: set_balance_proposal_hash(2),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
});
}
#[test]
fn external_majority_referendum_works() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_noop!(
Democracy::external_propose_majority(
Origin::signed(1),
set_balance_proposal_hash(2)
),
BadOrigin,
);
assert_ok!(Democracy::external_propose_majority(
Origin::signed(3),
set_balance_proposal_hash_and_note(2)
));
fast_forward_to(2);
assert_eq!(
Democracy::referendum_status(0),
Ok(ReferendumStatus {
end: 4,
proposal_hash: set_balance_proposal_hash(2),
threshold: VoteThreshold::SimpleMajority,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
});
}
#[test]
fn external_default_referendum_works() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_noop!(
Democracy::external_propose_default(
Origin::signed(3),
set_balance_proposal_hash(2)
),
BadOrigin,
);
assert_ok!(Democracy::external_propose_default(
Origin::signed(1),
set_balance_proposal_hash_and_note(2)
));
fast_forward_to(2);
assert_eq!(
Democracy::referendum_status(0),
Ok(ReferendumStatus {
end: 4,
proposal_hash: set_balance_proposal_hash(2),
threshold: VoteThreshold::SuperMajorityAgainst,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
});
}
#[test]
fn external_and_public_interleaving_works() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(1),
));
assert_ok!(propose_set_balance_and_note(6, 2, 2));
fast_forward_to(2);
// both waiting: external goes first.
assert_eq!(
Democracy::referendum_status(0),
Ok(ReferendumStatus {
end: 4,
proposal_hash: set_balance_proposal_hash_and_note(1),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
// replenish external
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(3),
));
fast_forward_to(4);
// both waiting: public goes next.
assert_eq!(
Democracy::referendum_status(1),
Ok(ReferendumStatus {
end: 6,
proposal_hash: set_balance_proposal_hash_and_note(2),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
// don't replenish public
fast_forward_to(6);
// it's external "turn" again, though since public is empty that doesn't really matter
assert_eq!(
Democracy::referendum_status(2),
Ok(ReferendumStatus {
end: 8,
proposal_hash: set_balance_proposal_hash_and_note(3),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
// replenish external
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(5),
));
fast_forward_to(8);
// external goes again because there's no public waiting.
assert_eq!(
Democracy::referendum_status(3),
Ok(ReferendumStatus {
end: 10,
proposal_hash: set_balance_proposal_hash_and_note(5),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
// replenish both
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(7),
));
assert_ok!(propose_set_balance_and_note(6, 4, 2));
fast_forward_to(10);
// public goes now since external went last time.
assert_eq!(
Democracy::referendum_status(4),
Ok(ReferendumStatus {
end: 12,
proposal_hash: set_balance_proposal_hash_and_note(4),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
// replenish public again
assert_ok!(propose_set_balance_and_note(6, 6, 2));
// cancel external
let h = set_balance_proposal_hash_and_note(7);
assert_ok!(Democracy::veto_external(Origin::signed(3), h));
fast_forward_to(12);
// public goes again now since there's no external waiting.
assert_eq!(
Democracy::referendum_status(5),
Ok(ReferendumStatus {
end: 14,
proposal_hash: set_balance_proposal_hash_and_note(6),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 2,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
});
}
@@ -0,0 +1,88 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for fast-tracking functionality.
use super::*;
#[test]
fn fast_track_referendum_works() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let h = set_balance_proposal_hash_and_note(2);
assert_noop!(Democracy::fast_track(Origin::signed(5), h, 3, 2), Error::<Test>::ProposalMissing);
assert_ok!(Democracy::external_propose_majority(
Origin::signed(3),
set_balance_proposal_hash_and_note(2)
));
assert_noop!(Democracy::fast_track(Origin::signed(1), h, 3, 2), BadOrigin);
assert_ok!(Democracy::fast_track(Origin::signed(5), h, 2, 0));
assert_eq!(
Democracy::referendum_status(0),
Ok(ReferendumStatus {
end: 2,
proposal_hash: set_balance_proposal_hash_and_note(2),
threshold: VoteThreshold::SimpleMajority,
delay: 0,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
});
}
#[test]
fn instant_referendum_works() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let h = set_balance_proposal_hash_and_note(2);
assert_noop!(Democracy::fast_track(Origin::signed(5), h, 3, 2), Error::<Test>::ProposalMissing);
assert_ok!(Democracy::external_propose_majority(
Origin::signed(3),
set_balance_proposal_hash_and_note(2)
));
assert_noop!(Democracy::fast_track(Origin::signed(1), h, 3, 2), BadOrigin);
assert_noop!(Democracy::fast_track(Origin::signed(5), h, 1, 0), BadOrigin);
assert_noop!(Democracy::fast_track(Origin::signed(6), h, 1, 0), Error::<Test>::InstantNotAllowed);
INSTANT_ALLOWED.with(|v| *v.borrow_mut() = true);
assert_ok!(Democracy::fast_track(Origin::signed(6), h, 1, 0));
assert_eq!(
Democracy::referendum_status(0),
Ok(ReferendumStatus {
end: 1,
proposal_hash: set_balance_proposal_hash_and_note(2),
threshold: VoteThreshold::SimpleMajority,
delay: 0,
tally: Tally { ayes: 0, nays: 0, turnout: 0 },
})
);
});
}
#[test]
fn fast_track_referendum_fails_when_no_simple_majority() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let h = set_balance_proposal_hash_and_note(2);
assert_ok!(Democracy::external_propose(
Origin::signed(2),
set_balance_proposal_hash_and_note(2)
));
assert_noop!(
Democracy::fast_track(Origin::signed(5), h, 3, 2),
Error::<Test>::NotSimpleMajority
);
});
}
@@ -0,0 +1,364 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for functionality concerning locking and lock-voting.
use super::*;
use std::convert::TryFrom;
fn aye(x: u8, balance: u64) -> AccountVote<u64> {
AccountVote::Standard {
vote: Vote { aye: true, conviction: Conviction::try_from(x).unwrap() },
balance
}
}
fn nay(x: u8, balance: u64) -> AccountVote<u64> {
AccountVote::Standard {
vote: Vote { aye: false, conviction: Conviction::try_from(x).unwrap() },
balance
}
}
fn the_lock(amount: u64) -> BalanceLock<u64> {
BalanceLock {
id: DEMOCRACY_ID,
amount,
reasons: pallet_balances::Reasons::Misc,
}
}
#[test]
fn lock_voting_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r, nay(5, 10)));
assert_ok!(Democracy::vote(Origin::signed(2), r, aye(4, 20)));
assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3, 30)));
assert_ok!(Democracy::vote(Origin::signed(4), r, aye(2, 40)));
assert_ok!(Democracy::vote(Origin::signed(5), r, nay(1, 50)));
assert_eq!(tally(r), Tally { ayes: 250, nays: 100, turnout: 150 });
// All balances are currently locked.
for i in 1..=5 {
assert_eq!(Balances::locks(i), vec![the_lock(i * 10)]);
}
fast_forward_to(2);
// Referendum passed; 1 and 5 didn't get their way and can now reap and unlock.
assert_ok!(Democracy::remove_vote(Origin::signed(1), r));
assert_ok!(Democracy::unlock(Origin::signed(1), 1));
// Anyone can reap and unlock anyone else's in this context.
assert_ok!(Democracy::remove_other_vote(Origin::signed(2), 5, r));
assert_ok!(Democracy::unlock(Origin::signed(2), 5));
// 2, 3, 4 got their way with the vote, so they cannot be reaped by others.
assert_noop!(Democracy::remove_other_vote(Origin::signed(1), 2, r), Error::<Test>::NoPermission);
// However, they can be unvoted by the owner, though it will make no difference to the lock.
assert_ok!(Democracy::remove_vote(Origin::signed(2), r));
assert_ok!(Democracy::unlock(Origin::signed(2), 2));
assert_eq!(Balances::locks(1), vec![]);
assert_eq!(Balances::locks(2), vec![the_lock(20)]);
assert_eq!(Balances::locks(3), vec![the_lock(30)]);
assert_eq!(Balances::locks(4), vec![the_lock(40)]);
assert_eq!(Balances::locks(5), vec![]);
assert_eq!(Balances::free_balance(42), 2);
fast_forward_to(5);
// No change yet...
assert_noop!(Democracy::remove_other_vote(Origin::signed(1), 4, r), Error::<Test>::NoPermission);
assert_ok!(Democracy::unlock(Origin::signed(1), 4));
assert_eq!(Balances::locks(4), vec![the_lock(40)]);
fast_forward_to(6);
// 4 should now be able to reap and unlock
assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 4, r));
assert_ok!(Democracy::unlock(Origin::signed(1), 4));
assert_eq!(Balances::locks(4), vec![]);
fast_forward_to(9);
assert_noop!(Democracy::remove_other_vote(Origin::signed(1), 3, r), Error::<Test>::NoPermission);
assert_ok!(Democracy::unlock(Origin::signed(1), 3));
assert_eq!(Balances::locks(3), vec![the_lock(30)]);
fast_forward_to(10);
assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 3, r));
assert_ok!(Democracy::unlock(Origin::signed(1), 3));
assert_eq!(Balances::locks(3), vec![]);
// 2 doesn't need to reap_vote here because it was already done before.
fast_forward_to(17);
assert_ok!(Democracy::unlock(Origin::signed(1), 2));
assert_eq!(Balances::locks(2), vec![the_lock(20)]);
fast_forward_to(18);
assert_ok!(Democracy::unlock(Origin::signed(1), 2));
assert_eq!(Balances::locks(2), vec![]);
});
}
#[test]
fn no_locks_without_conviction_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0,
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(0, 10)));
fast_forward_to(2);
assert_eq!(Balances::free_balance(42), 2);
assert_ok!(Democracy::remove_other_vote(Origin::signed(2), 1, r));
assert_ok!(Democracy::unlock(Origin::signed(2), 1));
assert_eq!(Balances::locks(1), vec![]);
});
}
#[test]
fn lock_voting_should_work_with_delegation() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r, nay(5, 10)));
assert_ok!(Democracy::vote(Origin::signed(2), r, aye(4, 20)));
assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3, 30)));
assert_ok!(Democracy::delegate(Origin::signed(4), 2, Conviction::Locked2x, 40));
assert_ok!(Democracy::vote(Origin::signed(5), r, nay(1, 50)));
assert_eq!(tally(r), Tally { ayes: 250, nays: 100, turnout: 150 });
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 2);
});
}
fn setup_three_referenda() -> (u32, u32, u32) {
System::set_block_number(0);
let r1 = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SimpleMajority,
0
);
assert_ok!(Democracy::vote(Origin::signed(5), r1, aye(4, 10)));
let r2 = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SimpleMajority,
0
);
assert_ok!(Democracy::vote(Origin::signed(5), r2, aye(3, 20)));
let r3 = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SimpleMajority,
0
);
assert_ok!(Democracy::vote(Origin::signed(5), r3, aye(2, 50)));
fast_forward_to(2);
(r1, r2, r3)
}
#[test]
fn prior_lockvotes_should_be_enforced() {
new_test_ext().execute_with(|| {
let r = setup_three_referenda();
// r.0 locked 10 until #18.
// r.1 locked 20 until #10.
// r.2 locked 50 until #6.
fast_forward_to(5);
assert_noop!(Democracy::remove_other_vote(Origin::signed(1), 5, r.2), Error::<Test>::NoPermission);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(50)]);
fast_forward_to(6);
assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.2));
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(20)]);
fast_forward_to(9);
assert_noop!(Democracy::remove_other_vote(Origin::signed(1), 5, r.1), Error::<Test>::NoPermission);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(20)]);
fast_forward_to(10);
assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.1));
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(10)]);
fast_forward_to(17);
assert_noop!(Democracy::remove_other_vote(Origin::signed(1), 5, r.0), Error::<Test>::NoPermission);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(10)]);
fast_forward_to(18);
assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.0));
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![]);
});
}
#[test]
fn single_consolidation_of_lockvotes_should_work_as_before() {
new_test_ext().execute_with(|| {
let r = setup_three_referenda();
// r.0 locked 10 until #18.
// r.1 locked 20 until #10.
// r.2 locked 50 until #6.
fast_forward_to(5);
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2));
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(50)]);
fast_forward_to(6);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(20)]);
fast_forward_to(9);
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1));
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(20)]);
fast_forward_to(10);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(10)]);
fast_forward_to(17);
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0));
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![the_lock(10)]);
fast_forward_to(18);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![]);
});
}
#[test]
fn multi_consolidation_of_lockvotes_should_be_conservative() {
new_test_ext().execute_with(|| {
let r = setup_three_referenda();
// r.0 locked 10 until #18.
// r.1 locked 20 until #10.
// r.2 locked 50 until #6.
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2));
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1));
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0));
fast_forward_to(6);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert!(Balances::locks(5)[0].amount >= 20);
fast_forward_to(10);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert!(Balances::locks(5)[0].amount >= 10);
fast_forward_to(18);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![]);
});
}
#[test]
fn locks_should_persist_from_voting_to_delegation() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SimpleMajority,
0
);
assert_ok!(Democracy::vote(Origin::signed(5), r, aye(4, 10)));
fast_forward_to(2);
assert_ok!(Democracy::remove_vote(Origin::signed(5), r));
// locked 10 until #18.
assert_ok!(Democracy::delegate(Origin::signed(5), 1, Conviction::Locked3x, 20));
// locked 20.
assert!(Balances::locks(5)[0].amount == 20);
assert_ok!(Democracy::undelegate(Origin::signed(5)));
// locked 20 until #10
fast_forward_to(9);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert!(Balances::locks(5)[0].amount == 20);
fast_forward_to(10);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert!(Balances::locks(5)[0].amount >= 10);
fast_forward_to(17);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert!(Balances::locks(5)[0].amount >= 10);
fast_forward_to(18);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![]);
});
}
#[test]
fn locks_should_persist_from_delegation_to_voting() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(Democracy::delegate(Origin::signed(5), 1, Conviction::Locked5x, 5));
assert_ok!(Democracy::undelegate(Origin::signed(5)));
// locked 5 until #32
let r = setup_three_referenda();
// r.0 locked 10 until #18.
// r.1 locked 20 until #10.
// r.2 locked 50 until #6.
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2));
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1));
assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0));
fast_forward_to(6);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert!(Balances::locks(5)[0].amount >= 20);
fast_forward_to(10);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert!(Balances::locks(5)[0].amount >= 10);
fast_forward_to(18);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert!(Balances::locks(5)[0].amount >= 5);
fast_forward_to(32);
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![]);
});
}
@@ -0,0 +1,164 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The preimage tests.
use super::*;
#[test]
fn missing_preimage_should_fail() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 0);
});
}
#[test]
fn preimage_deposit_should_be_required_and_returned() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
// fee of 100 is too much.
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 100);
assert_noop!(
Democracy::note_preimage(Origin::signed(6), vec![0; 500]),
BalancesError::<Test, _>::InsufficientBalance,
);
// fee of 1 is reasonable.
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_eq!(Balances::reserved_balance(6), 12);
next_block();
next_block();
assert_eq!(Balances::reserved_balance(6), 0);
assert_eq!(Balances::free_balance(6), 60);
assert_eq!(Balances::free_balance(42), 2);
});
}
#[test]
fn preimage_deposit_should_be_reapable_earlier_by_owner() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
assert_ok!(Democracy::note_preimage(Origin::signed(6), set_balance_proposal(2)));
assert_eq!(Balances::reserved_balance(6), 12);
next_block();
assert_noop!(
Democracy::reap_preimage(Origin::signed(6), set_balance_proposal_hash(2)),
Error::<Test>::TooEarly
);
next_block();
assert_ok!(Democracy::reap_preimage(Origin::signed(6), set_balance_proposal_hash(2)));
assert_eq!(Balances::free_balance(6), 60);
assert_eq!(Balances::reserved_balance(6), 0);
});
}
#[test]
fn preimage_deposit_should_be_reapable() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_noop!(
Democracy::reap_preimage(Origin::signed(5), set_balance_proposal_hash(2)),
Error::<Test>::PreimageMissing
);
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
assert_ok!(Democracy::note_preimage(Origin::signed(6), set_balance_proposal(2)));
assert_eq!(Balances::reserved_balance(6), 12);
next_block();
next_block();
next_block();
assert_noop!(
Democracy::reap_preimage(Origin::signed(5), set_balance_proposal_hash(2)),
Error::<Test>::TooEarly
);
next_block();
assert_ok!(Democracy::reap_preimage(Origin::signed(5), set_balance_proposal_hash(2)));
assert_eq!(Balances::reserved_balance(6), 0);
assert_eq!(Balances::free_balance(6), 48);
assert_eq!(Balances::free_balance(5), 62);
});
}
#[test]
fn noting_imminent_preimage_for_free_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash(2),
VoteThreshold::SuperMajorityApprove,
1
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_noop!(
Democracy::note_imminent_preimage(Origin::signed(7), set_balance_proposal(2)),
Error::<Test>::NotImminent
);
next_block();
// Now we're in the dispatch queue it's all good.
assert_ok!(Democracy::note_imminent_preimage(Origin::signed(7), set_balance_proposal(2)));
next_block();
assert_eq!(Balances::free_balance(42), 2);
});
}
#[test]
fn reaping_imminent_preimage_should_fail() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let h = set_balance_proposal_hash_and_note(2);
let r = Democracy::inject_referendum(3, h, VoteThreshold::SuperMajorityApprove, 1);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
next_block();
next_block();
// now imminent.
assert_noop!(Democracy::reap_preimage(Origin::signed(6), h), Error::<Test>::Imminent);
});
}
@@ -0,0 +1,104 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for functionality concerning proxying.
use super::*;
#[test]
fn proxy_should_work() {
new_test_ext().execute_with(|| {
assert_eq!(Democracy::proxy(10), None);
assert!(System::allow_death(&10));
assert_noop!(Democracy::activate_proxy(Origin::signed(1), 10), Error::<Test>::NotOpen);
assert_ok!(Democracy::open_proxy(Origin::signed(10), 1));
assert!(!System::allow_death(&10));
assert_eq!(Democracy::proxy(10), Some(ProxyState::Open(1)));
assert_noop!(Democracy::activate_proxy(Origin::signed(2), 10), Error::<Test>::WrongOpen);
assert_ok!(Democracy::activate_proxy(Origin::signed(1), 10));
assert_eq!(Democracy::proxy(10), Some(ProxyState::Active(1)));
// Can't set when already set.
assert_noop!(Democracy::activate_proxy(Origin::signed(2), 10), Error::<Test>::AlreadyProxy);
// But this works because 11 isn't proxying.
assert_ok!(Democracy::open_proxy(Origin::signed(11), 2));
assert_ok!(Democracy::activate_proxy(Origin::signed(2), 11));
assert_eq!(Democracy::proxy(10), Some(ProxyState::Active(1)));
assert_eq!(Democracy::proxy(11), Some(ProxyState::Active(2)));
// 2 cannot fire 1's proxy:
assert_noop!(Democracy::deactivate_proxy(Origin::signed(2), 10), Error::<Test>::WrongProxy);
// 1 deactivates their proxy:
assert_ok!(Democracy::deactivate_proxy(Origin::signed(1), 10));
assert_eq!(Democracy::proxy(10), Some(ProxyState::Open(1)));
// but the proxy account cannot be killed until the proxy is closed.
assert!(!System::allow_death(&10));
// and then 10 closes it completely:
assert_ok!(Democracy::close_proxy(Origin::signed(10)));
assert_eq!(Democracy::proxy(10), None);
assert!(System::allow_death(&10));
// 11 just closes without 2's "permission".
assert_ok!(Democracy::close_proxy(Origin::signed(11)));
assert_eq!(Democracy::proxy(11), None);
assert!(System::allow_death(&11));
});
}
#[test]
fn voting_and_removing_votes_should_work_with_proxy() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
fast_forward_to(2);
let r = 0;
assert_ok!(Democracy::open_proxy(Origin::signed(10), 1));
assert_ok!(Democracy::activate_proxy(Origin::signed(1), 10));
assert_ok!(Democracy::proxy_vote(Origin::signed(10), r, aye(1)));
assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 });
assert_ok!(Democracy::proxy_remove_vote(Origin::signed(10), r));
assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 });
});
}
#[test]
fn delegation_and_undelegation_should_work_with_proxy() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
fast_forward_to(2);
let r = 0;
assert_ok!(Democracy::open_proxy(Origin::signed(10), 1));
assert_ok!(Democracy::activate_proxy(Origin::signed(1), 10));
assert_ok!(Democracy::vote(Origin::signed(2), r, aye(2)));
assert_ok!(Democracy::proxy_delegate(Origin::signed(10), 2, Conviction::None, 10));
assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 });
assert_ok!(Democracy::proxy_undelegate(Origin::signed(10)));
assert_eq!(tally(r), Tally { ayes: 2, nays: 0, turnout: 20 });
});
}
@@ -0,0 +1,104 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for the public proposal queue.
use super::*;
#[test]
fn backing_for_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(propose_set_balance_and_note(1, 2, 2));
assert_ok!(propose_set_balance_and_note(1, 4, 4));
assert_ok!(propose_set_balance_and_note(1, 3, 3));
assert_eq!(Democracy::backing_for(0), Some(2));
assert_eq!(Democracy::backing_for(1), Some(4));
assert_eq!(Democracy::backing_for(2), Some(3));
});
}
#[test]
fn deposit_for_proposals_should_be_taken() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(propose_set_balance_and_note(1, 2, 5));
assert_ok!(Democracy::second(Origin::signed(2), 0));
assert_ok!(Democracy::second(Origin::signed(5), 0));
assert_ok!(Democracy::second(Origin::signed(5), 0));
assert_ok!(Democracy::second(Origin::signed(5), 0));
assert_eq!(Balances::free_balance(1), 5);
assert_eq!(Balances::free_balance(2), 15);
assert_eq!(Balances::free_balance(5), 35);
});
}
#[test]
fn deposit_for_proposals_should_be_returned() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(propose_set_balance_and_note(1, 2, 5));
assert_ok!(Democracy::second(Origin::signed(2), 0));
assert_ok!(Democracy::second(Origin::signed(5), 0));
assert_ok!(Democracy::second(Origin::signed(5), 0));
assert_ok!(Democracy::second(Origin::signed(5), 0));
fast_forward_to(3);
assert_eq!(Balances::free_balance(1), 10);
assert_eq!(Balances::free_balance(2), 20);
assert_eq!(Balances::free_balance(5), 50);
});
}
#[test]
fn proposal_with_deposit_below_minimum_should_not_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_noop!(propose_set_balance(1, 2, 0), Error::<Test>::ValueLow);
});
}
#[test]
fn poor_proposer_should_not_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_noop!(propose_set_balance(1, 2, 11), BalancesError::<Test, _>::InsufficientBalance);
});
}
#[test]
fn poor_seconder_should_not_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(propose_set_balance_and_note(2, 2, 11));
assert_noop!(Democracy::second(Origin::signed(1), 0), BalancesError::<Test, _>::InsufficientBalance);
});
}
#[test]
fn runners_up_should_come_after() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 2));
assert_ok!(propose_set_balance_and_note(1, 4, 4));
assert_ok!(propose_set_balance_and_note(1, 3, 3));
fast_forward_to(2);
assert_ok!(Democracy::vote(Origin::signed(1), 0, aye(1)));
fast_forward_to(4);
assert_ok!(Democracy::vote(Origin::signed(1), 1, aye(1)));
fast_forward_to(6);
assert_ok!(Democracy::vote(Origin::signed(1), 2, aye(1)));
});
}
@@ -0,0 +1,115 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for functionality concerning normal starting, ending and enacting of referenda.
use super::*;
#[test]
fn simple_passing_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 });
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 2);
});
}
#[test]
fn simple_failing_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r, nay(1)));
assert_eq!(tally(r), Tally { ayes: 0, nays: 1, turnout: 10 });
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 0);
});
}
#[test]
fn ooo_inject_referendums_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r1 = Democracy::inject_referendum(
3,
set_balance_proposal_hash_and_note(3),
VoteThreshold::SuperMajorityApprove,
0
);
let r2 = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r2, aye(1)));
assert_eq!(tally(r2), Tally { ayes: 1, nays: 0, turnout: 10 });
next_block();
assert_eq!(Balances::free_balance(42), 2);
assert_ok!(Democracy::vote(Origin::signed(1), r1, aye(1)));
assert_eq!(tally(r1), Tally { ayes: 1, nays: 0, turnout: 10 });
next_block();
assert_eq!(Balances::free_balance(42), 3);
});
}
#[test]
fn delayed_enactment_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
1
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_ok!(Democracy::vote(Origin::signed(2), r, aye(2)));
assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3)));
assert_ok!(Democracy::vote(Origin::signed(4), r, aye(4)));
assert_ok!(Democracy::vote(Origin::signed(5), r, aye(5)));
assert_ok!(Democracy::vote(Origin::signed(6), r, aye(6)));
assert_eq!(tally(r), Tally { ayes: 21, nays: 0, turnout: 210 });
next_block();
assert_eq!(Balances::free_balance(42), 0);
next_block();
assert_eq!(Balances::free_balance(42), 2);
});
}
@@ -0,0 +1,170 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The tests for normal voting functionality.
use super::*;
#[test]
fn overvoting_should_fail() {
new_test_ext().execute_with(|| {
let r = begin_referendum();
assert_noop!(Democracy::vote(Origin::signed(1), r, aye(2)), Error::<Test>::InsufficientFunds);
});
}
#[test]
fn split_voting_should_work() {
new_test_ext().execute_with(|| {
let r = begin_referendum();
let v = AccountVote::Split { aye: 40, nay: 20 };
assert_noop!(Democracy::vote(Origin::signed(5), r, v), Error::<Test>::InsufficientFunds);
let v = AccountVote::Split { aye: 30, nay: 20 };
assert_ok!(Democracy::vote(Origin::signed(5), r, v));
assert_eq!(tally(r), Tally { ayes: 3, nays: 2, turnout: 50 });
});
}
#[test]
fn split_vote_cancellation_should_work() {
new_test_ext().execute_with(|| {
let r = begin_referendum();
let v = AccountVote::Split { aye: 30, nay: 20 };
assert_ok!(Democracy::vote(Origin::signed(5), r, v));
assert_ok!(Democracy::remove_vote(Origin::signed(5), r));
assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 });
assert_ok!(Democracy::unlock(Origin::signed(5), 5));
assert_eq!(Balances::locks(5), vec![]);
});
}
#[test]
fn single_proposal_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance_and_note(1, 2, 1));
let r = 0;
assert!(Democracy::referendum_info(r).is_none());
// start of 2 => next referendum scheduled.
fast_forward_to(2);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_eq!(Democracy::referendum_count(), 1);
assert_eq!(
Democracy::referendum_status(0),
Ok(ReferendumStatus {
end: 4,
proposal_hash: set_balance_proposal_hash_and_note(2),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 2,
tally: Tally { ayes: 1, nays: 0, turnout: 10 },
})
);
fast_forward_to(3);
// referendum still running
assert!(Democracy::referendum_status(0).is_ok());
// referendum runs during 2 and 3, ends @ start of 4.
fast_forward_to(4);
assert!(Democracy::referendum_status(0).is_err());
assert_eq!(Democracy::dispatch_queue(), vec![
(6, set_balance_proposal_hash_and_note(2), 0)
]);
// referendum passes and wait another two blocks for enactment.
fast_forward_to(6);
assert_eq!(Balances::free_balance(42), 2);
});
}
#[test]
fn controversial_voting_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(1), r, big_aye(1)));
assert_ok!(Democracy::vote(Origin::signed(2), r, big_nay(2)));
assert_ok!(Democracy::vote(Origin::signed(3), r, big_nay(3)));
assert_ok!(Democracy::vote(Origin::signed(4), r, big_aye(4)));
assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5)));
assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6)));
assert_eq!(tally(r), Tally { ayes: 110, nays: 100, turnout: 210 });
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 2);
});
}
#[test]
fn controversial_low_turnout_voting_should_work() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5)));
assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6)));
assert_eq!(tally(r), Tally { ayes: 60, nays: 50, turnout: 110 });
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 0);
});
}
#[test]
fn passing_low_turnout_voting_should_work() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(42), 0);
assert_eq!(Balances::total_issuance(), 210);
System::set_block_number(1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0
);
assert_ok!(Democracy::vote(Origin::signed(4), r, big_aye(4)));
assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5)));
assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6)));
assert_eq!(tally(r), Tally { ayes: 100, nays: 50, turnout: 150 });
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 2);
});
}
+217
View File
@@ -0,0 +1,217 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Miscellaneous additional datatypes.
use codec::{Encode, Decode};
use sp_runtime::RuntimeDebug;
use sp_runtime::traits::{Zero, Bounded, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, Saturating};
use crate::{Vote, VoteThreshold, AccountVote, Conviction};
/// Info regarding an ongoing referendum.
#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, RuntimeDebug)]
pub struct Tally<Balance> {
/// The number of aye votes, expressed in terms of post-conviction lock-vote.
pub (crate) ayes: Balance,
/// The number of nay votes, expressed in terms of post-conviction lock-vote.
pub (crate) nays: Balance,
/// The amount of funds currently expressing its opinion. Pre-conviction.
pub (crate) turnout: Balance,
}
/// Amount of votes and capital placed in delegation for an account.
#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, RuntimeDebug)]
pub struct Delegations<Balance> {
/// The number of votes (this is post-conviction).
pub (crate) votes: Balance,
/// The amount of raw capital, used for the turnout.
pub (crate) capital: Balance,
}
impl<Balance: Saturating> Saturating for Delegations<Balance> {
fn saturating_add(self, o: Self) -> Self {
Self {
votes: self.votes.saturating_add(o.votes),
capital: self.capital.saturating_add(o.capital),
}
}
fn saturating_sub(self, o: Self) -> Self {
Self {
votes: self.votes.saturating_sub(o.votes),
capital: self.capital.saturating_sub(o.capital),
}
}
fn saturating_mul(self, o: Self) -> Self {
Self {
votes: self.votes.saturating_mul(o.votes),
capital: self.capital.saturating_mul(o.capital),
}
}
}
impl<
Balance: From<u8> + Zero + Copy + CheckedAdd + CheckedSub + CheckedMul + CheckedDiv + Bounded +
Saturating
> Tally<Balance> {
/// Create a new tally.
pub fn new(
vote: Vote,
balance: Balance,
) -> Self {
let Delegations { votes, capital } = vote.conviction.votes(balance);
Self {
ayes: if vote.aye { votes } else { Zero::zero() },
nays: if vote.aye { Zero::zero() } else { votes },
turnout: capital,
}
}
/// Add an account's vote into the tally.
pub fn add(
&mut self,
vote: AccountVote<Balance>,
) -> Option<()> {
match vote {
AccountVote::Standard { vote, balance } => {
let Delegations { votes, capital } = vote.conviction.votes(balance);
self.turnout = self.turnout.checked_add(&capital)?;
match vote.aye {
true => self.ayes = self.ayes.checked_add(&votes)?,
false => self.nays = self.nays.checked_add(&votes)?,
}
}
AccountVote::Split { aye, nay } => {
let aye = Conviction::None.votes(aye);
let nay = Conviction::None.votes(nay);
self.turnout = self.turnout.checked_add(&aye.capital)?.checked_add(&nay.capital)?;
self.ayes = self.ayes.checked_add(&aye.votes)?;
self.nays = self.nays.checked_add(&nay.votes)?;
}
}
Some(())
}
/// Remove an account's vote from the tally.
pub fn remove(
&mut self,
vote: AccountVote<Balance>,
) -> Option<()> {
match vote {
AccountVote::Standard { vote, balance } => {
let Delegations { votes, capital } = vote.conviction.votes(balance);
self.turnout = self.turnout.checked_sub(&capital)?;
match vote.aye {
true => self.ayes = self.ayes.checked_sub(&votes)?,
false => self.nays = self.nays.checked_sub(&votes)?,
}
}
AccountVote::Split { aye, nay } => {
let aye = Conviction::None.votes(aye);
let nay = Conviction::None.votes(nay);
self.turnout = self.turnout.checked_sub(&aye.capital)?.checked_sub(&nay.capital)?;
self.ayes = self.ayes.checked_sub(&aye.votes)?;
self.nays = self.nays.checked_sub(&nay.votes)?;
}
}
Some(())
}
/// Increment some amount of votes.
pub fn increase(&mut self, approve: bool, delegations: Delegations<Balance>) -> Option<()> {
self.turnout = self.turnout.saturating_add(delegations.capital);
match approve {
true => self.ayes = self.ayes.saturating_add(delegations.votes),
false => self.nays = self.nays.saturating_add(delegations.votes),
}
Some(())
}
/// Decrement some amount of votes.
pub fn reduce(&mut self, approve: bool, delegations: Delegations<Balance>) -> Option<()> {
self.turnout = self.turnout.saturating_sub(delegations.capital);
match approve {
true => self.ayes = self.ayes.saturating_sub(delegations.votes),
false => self.nays = self.nays.saturating_sub(delegations.votes),
}
Some(())
}
}
/// Info regarding an ongoing referendum.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
pub struct ReferendumStatus<BlockNumber, Hash, Balance> {
/// When voting on this referendum will end.
pub (crate) end: BlockNumber,
/// The hash of the proposal being voted on.
pub (crate) proposal_hash: Hash,
/// The thresholding mechanism to determine whether it passed.
pub (crate) threshold: VoteThreshold,
/// The delay (in blocks) to wait after a successful referendum before deploying.
pub (crate) delay: BlockNumber,
/// The current tally of votes in this referendum.
pub (crate) tally: Tally<Balance>,
}
/// Info regarding a referendum, present or past.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
pub enum ReferendumInfo<BlockNumber, Hash, Balance> {
/// Referendum is happening, the arg is the block number at which it will end.
Ongoing(ReferendumStatus<BlockNumber, Hash, Balance>),
/// Referendum finished at `end`, and has been `approved` or rejected.
Finished{approved: bool, end: BlockNumber},
}
impl<BlockNumber, Hash, Balance: Default> ReferendumInfo<BlockNumber, Hash, Balance> {
/// Create a new instance.
pub fn new(
end: BlockNumber,
proposal_hash: Hash,
threshold: VoteThreshold,
delay: BlockNumber,
) -> Self {
let s = ReferendumStatus{ end, proposal_hash, threshold, delay, tally: Tally::default() };
ReferendumInfo::Ongoing(s)
}
}
/// State of a proxy voting account.
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)]
pub enum ProxyState<AccountId> {
/// Account is open to becoming a proxy but is not yet assigned.
Open(AccountId),
/// Account is actively being a proxy.
Active(AccountId),
}
impl<AccountId> ProxyState<AccountId> {
pub (crate) fn as_active(self) -> Option<AccountId> {
match self {
ProxyState::Active(a) => Some(a),
ProxyState::Open(_) => None,
}
}
}
/// Whether an `unvote` operation is able to make actions that are not strictly always in the
/// interest of an account.
pub enum UnvoteScope {
/// Permitted to do everything.
Any,
/// Permitted to do only the changes that do not need the owner's permission.
OnlyExpired,
}
+181
View File
@@ -0,0 +1,181 @@
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! The vote datatype.
use sp_std::{prelude::*, result::Result, convert::TryFrom};
use codec::{Encode, EncodeLike, Decode, Output, Input};
use sp_runtime::{RuntimeDebug, traits::{Saturating, Zero}};
use crate::{Conviction, ReferendumIndex, Delegations};
/// A number of lock periods, plus a vote, one way or the other.
#[derive(Copy, Clone, Eq, PartialEq, Default, RuntimeDebug)]
pub struct Vote {
pub aye: bool,
pub conviction: Conviction,
}
impl Encode for Vote {
fn encode_to<T: Output>(&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"))?,
})
}
}
/// A vote for a referendum of a particular account.
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug)]
pub enum AccountVote<Balance> {
/// A standard vote, one-way (approve or reject) with a given amount of conviction.
Standard { vote: Vote, balance: Balance },
/// A split vote with balances given for both ways, and with no conviction, useful for
/// parachains when voting.
Split { aye: Balance, nay: Balance },
}
impl<Balance: Saturating> AccountVote<Balance> {
/// Returns `Some` of the lock periods that the account is locked for, assuming that the
/// referendum passed iff `approved` is `true`.
pub fn locked_if(self, approved: bool) -> Option<(u32, Balance)> {
// winning side: can only be removed after the lock period ends.
match self {
AccountVote::Standard { vote, balance } if vote.aye == approved =>
Some((vote.conviction.lock_periods(), balance)),
_ => None,
}
}
/// The total balance involved in this vote.
pub fn balance(self) -> Balance {
match self {
AccountVote::Standard { balance, .. } => balance,
AccountVote::Split { aye, nay } => aye.saturating_add(nay),
}
}
/// Returns `Some` with whether the vote is an aye vote if it is standard, otherwise `None` if
/// it is split.
pub fn as_standard(self) -> Option<bool> {
match self {
AccountVote::Standard { vote, .. } => Some(vote.aye),
_ => None,
}
}
}
/// A "prior" lock, i.e. a lock for some now-forgotten reason.
#[derive(Encode, Decode, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug)]
pub struct PriorLock<BlockNumber, Balance>(BlockNumber, Balance);
impl<BlockNumber: Ord + Copy + Zero, Balance: Ord + Copy + Zero> PriorLock<BlockNumber, Balance> {
/// Accumulates an additional lock.
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();
}
}
}
/// An indicator for what an account is doing; it can either be delegating or voting.
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)]
pub enum Voting<Balance, AccountId, BlockNumber> {
/// The account is voting directly. `delegations` is the total amount of post-conviction voting
/// weight that it controls from those that have delegated to it.
Direct {
/// The current votes of the account.
votes: Vec<(ReferendumIndex, AccountVote<Balance>)>,
/// The total amount of delegations that this account has received.
delegations: Delegations<Balance>,
/// Any pre-existing locks from past voting/delegating activity.
prior: PriorLock<BlockNumber, Balance>,
},
/// The account is delegating `balance` of its balance to a `target` account with `conviction`.
Delegating {
balance: Balance,
target: AccountId,
conviction: Conviction,
/// The total amount of delegations that this account has received.
delegations: Delegations<Balance>,
/// Any pre-existing locks from past voting/delegating activity.
prior: PriorLock<BlockNumber, Balance>,
},
}
impl<Balance: Default, AccountId, BlockNumber: Zero> Default for Voting<Balance, AccountId, BlockNumber> {
fn default() -> Self {
Voting::Direct {
votes: Vec::new(),
delegations: Default::default(),
prior: PriorLock(Zero::zero(), Default::default()),
}
}
}
impl<
Balance: Saturating + Ord + Zero + Copy,
BlockNumber: Ord + Copy + Zero,
AccountId,
> Voting<Balance, AccountId, BlockNumber> {
pub fn rejig(&mut self, now: BlockNumber) {
match self {
Voting::Direct { prior, .. } => prior,
Voting::Delegating { prior, .. } => prior,
}.rejig(now);
}
/// The amount of this account's balance that much currently be locked due to voting.
pub fn locked_balance(&self) -> Balance {
match self {
Voting::Direct { votes, prior, .. } => votes.iter()
.map(|i| i.1.balance())
.fold(prior.locked(), |a, i| a.max(i)),
Voting::Delegating { balance, .. } => *balance,
}
}
pub fn set_common(&mut self,
delegations: Delegations<Balance>,
prior: PriorLock<BlockNumber, Balance>
) {
let (d, p) = match self {
Voting::Direct { ref mut delegations, ref mut prior, .. } => (delegations, prior),
Voting::Delegating { ref mut delegations, ref mut prior, .. } => (delegations, prior),
};
*d = delegations;
*p = prior;
}
}
+16 -18
View File
@@ -21,6 +21,7 @@ use serde::{Serialize, Deserialize};
use codec::{Encode, Decode};
use sp_runtime::traits::{Zero, IntegerSquareRoot};
use sp_std::ops::{Add, Mul, Div, Rem};
use crate::Tally;
/// A means of determining if a vote is past pass threshold.
#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug)]
@@ -35,10 +36,9 @@ pub enum VoteThreshold {
}
pub trait Approved<Balance> {
/// Given `approve` votes for and `against` votes against from a total electorate size of
/// `electorate` (`electorate - (approve + against)` are abstainers), then returns true if the
/// overall outcome is in favor of approval.
fn approved(&self, approve: Balance, against: Balance, voters: Balance, electorate: Balance) -> bool;
/// Given a `tally` of votes and a total size of `electorate`, this returns `true` if the
/// overall outcome is in favor of approval according to `self`'s threshold method.
fn approved(&self, tally: Tally<Balance>, electorate: Balance) -> bool;
}
/// Return `true` iff `n1 / d1 < n2 / d2`. `d1` and `d2` may not be zero.
@@ -69,23 +69,21 @@ fn compare_rationals<T: Zero + Mul<T, Output = T> + Div<T, Output = T> + Rem<T,
}
}
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 {
/// Given `approve` votes for and `against` votes against from a total electorate size of
/// `electorate` of whom `voters` voted (`electorate - voters` are abstainers) then returns true if the
/// overall outcome is in favor of approval.
///
/// We assume each *voter* may cast more than one *vote*, hence `voters` is not necessarily equal to
/// `approve + against`.
fn approved(&self, approve: Balance, against: Balance, voters: Balance, electorate: Balance) -> bool {
let sqrt_voters = voters.integer_sqrt();
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(against, sqrt_voters, approve, sqrt_electorate),
compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate),
VoteThreshold::SuperMajorityAgainst =>
compare_rationals(against, sqrt_electorate, approve, sqrt_voters),
VoteThreshold::SimpleMajority => approve > against,
compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters),
VoteThreshold::SimpleMajority => tally.ayes > tally.nays,
}
}
}
@@ -96,7 +94,7 @@ mod tests {
#[test]
fn should_work() {
assert_eq!(VoteThreshold::SuperMajorityApprove.approved(60, 50, 110, 210), false);
assert_eq!(VoteThreshold::SuperMajorityApprove.approved(100, 50, 150, 210), true);
assert!(!VoteThreshold::SuperMajorityApprove.approved(Tally{ayes: 60, nays: 50, turnout: 110}, 210));
assert!(VoteThreshold::SuperMajorityApprove.approved(Tally{ayes: 100, nays: 50, turnout: 150}, 210));
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ pub use self::hash::{
};
pub use self::storage::{
StorageValue, StorageMap, StorageDoubleMap, StoragePrefixedMap, IterableStorageMap,
IterableStorageDoubleMap,
IterableStorageDoubleMap, migration
};
pub use self::dispatch::{Parameter, Callable, IsSubType};
pub use sp_runtime::{self, ConsensusEngineId, print, traits::Printable};
@@ -19,6 +19,7 @@
use sp_std::prelude::*;
use codec::{Encode, Decode};
use crate::{StorageHasher, Twox128};
use crate::hash::ReversibleStorageHasher;
/// Utility to iterate through raw items in storage.
pub struct StorageIterator<T> {
@@ -78,6 +79,72 @@ impl<T: Decode + Sized> Iterator for StorageIterator<T> {
}
}
/// Utility to iterate through raw items in storage.
pub struct StorageKeyIterator<K, T, H: ReversibleStorageHasher> {
prefix: Vec<u8>,
previous_key: Vec<u8>,
drain: bool,
_phantom: ::sp_std::marker::PhantomData<(K, T, H)>,
}
impl<K, T, H: ReversibleStorageHasher> StorageKeyIterator<K, T, H> {
/// Construct iterator to iterate over map items in `module` for the map called `item`.
pub fn new(module: &[u8], item: &[u8]) -> Self {
Self::with_suffix(module, item, &[][..])
}
/// Construct iterator to iterate over map items in `module` for the map called `item`.
pub fn with_suffix(module: &[u8], item: &[u8], suffix: &[u8]) -> Self {
let mut prefix = Vec::new();
prefix.extend_from_slice(&Twox128::hash(module));
prefix.extend_from_slice(&Twox128::hash(item));
prefix.extend_from_slice(suffix);
let previous_key = prefix.clone();
Self { prefix, previous_key, drain: false, _phantom: Default::default() }
}
/// Mutate this iterator into a draining iterator; items iterated are removed from storage.
pub fn drain(mut self) -> Self {
self.drain = true;
self
}
}
impl<K: Decode + Sized, T: Decode + Sized, H: ReversibleStorageHasher> Iterator
for StorageKeyIterator<K, T, H>
{
type Item = (K, T);
fn next(&mut self) -> Option<(K, T)> {
loop {
let maybe_next = sp_io::storage::next_key(&self.previous_key)
.filter(|n| n.starts_with(&self.prefix));
break match maybe_next {
Some(next) => {
self.previous_key = next.clone();
let mut key_material = H::reverse(&next[self.prefix.len()..]);
match K::decode(&mut key_material) {
Ok(key) => {
let maybe_value = frame_support::storage::unhashed::get::<T>(&next);
match maybe_value {
Some(value) => {
if self.drain {
frame_support::storage::unhashed::kill(&next);
}
Some((key, value))
}
None => continue,
}
}
Err(_) => continue,
}
}
None => None,
}
}
}
}
/// Get a particular value in storage by the `module`, the map's `item` name and the key `hash`.
pub fn have_storage_value(module: &[u8], item: &[u8], hash: &[u8]) -> bool {
get_storage_value::<()>(module, item, hash).is_some()
@@ -109,3 +176,12 @@ pub fn put_storage_value<T: Encode>(module: &[u8], item: &[u8], hash: &[u8], val
key[32..].copy_from_slice(hash);
frame_support::storage::unhashed::put(&key, &value);
}
/// Get a particular value in storage by the `module`, the map's `item` name and the key `hash`.
pub fn remove_storage_prefix(module: &[u8], item: &[u8], hash: &[u8]) {
let mut key = vec![0u8; 32 + hash.len()];
key[0..16].copy_from_slice(&Twox128::hash(module));
key[16..32].copy_from_slice(&Twox128::hash(item));
key[32..].copy_from_slice(hash);
frame_support::storage::unhashed::kill_prefix(&key)
}