Skip to content

Commit

Permalink
Pallets referenda and conviction voting used instead of democracy
Browse files Browse the repository at this point in the history
  • Loading branch information
Zebedeusz committed Jan 8, 2025
1 parent 03a7780 commit d45a846
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 79 deletions.
4 changes: 3 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ pallet-bags-list = { workspace = true, default-features = true }
pallet-balances = { workspace = true, default-features = true }
pallet-timestamp = { workspace = true, default-features = true }
pallet-session = { workspace = true, default-features = true }
pallet-democracy = { workspace = true, default-features = true }
pallet-referenda = { workspace = true, default-features = true }
pallet-vesting = { workspace = true, default-features = true }
pallet-scheduler = { workspace = true, default-features = true }
pallet-preimage = { workspace = true, default-features = true }
pallet-conviction-voting = { workspace = true, default-features = true }
sp-arithmetic = { workspace = true }

[features]
try-runtime = [
Expand All @@ -60,8 +62,9 @@ try-runtime = [
"pallet-staking/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-scheduler/try-runtime",
"pallet-democracy/try-runtime",
"pallet-referenda/try-runtime",
"pallet-vesting/try-runtime",
"pallet-preimage/try-runtime",
"pallet-conviction-voting/try-runtime",
"sp-runtime/try-runtime",
]
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@ mod mock;

pub(crate) const LOG_TARGET: &str = "tests::e2e-epm";

use frame_support::{assert_err, assert_noop, assert_ok};
use frame_support::{assert_err, assert_noop, assert_ok, traits::schedule::DispatchTime};
use frame_system::RawOrigin;
use mock::*;
use pallet_balances::BalanceLock;
use pallet_democracy::{AccountVote, BoundedCallOf, Conviction, Vote, VoteThreshold};
use pallet_conviction_voting::{AccountVote, Conviction, Vote};
use pallet_referenda::{BoundedCallOf, ReferendumCount};
use pallet_timestamp::Now;
use pallet_vesting::VestingInfo;
use sp_core::{ConstU32, Get};
use sp_runtime::{Perbill, WeakBoundedVec};
use sp_core::Get;
use sp_runtime::Perbill;

use crate::mock::RuntimeOrigin;

Expand Down Expand Up @@ -442,22 +443,26 @@ fn automatic_unbonding_pools() {
});
}

fn set_balance_proposal(value: u64) -> BoundedCallOf<Runtime> {
let inner = pallet_balances::Call::force_set_balance { who: 42, new_free: value };
let outer = RuntimeCall::Balances(inner);
Preimage::bound(outer).unwrap()
fn set_balance_proposal_bounded(value: u64) -> BoundedCallOf<Runtime, ()> {
let c = RuntimeCall::Balances(pallet_balances::Call::force_set_balance {
who: 42,
new_free: value,
});
<Preimage as StorePreimage>::bound(c).unwrap()
}

#[test]
fn funds_used_for_voting_can_be_staked() {
execute_with(ExtBuilder::default().build(), || {
// GIVEN
// A referendum exists that is in progress
let referendum = Democracy::internal_start_referendum(
set_balance_proposal(2),
VoteThreshold::SuperMajorityApprove,
0,
);
assert_ok!(Referenda::submit(
RuntimeOrigin::signed(1),
Box::new(RawOrigin::Root.into()),
set_balance_proposal_bounded(100),
DispatchTime::At(0),
));
assert_eq!(ReferendumCount::<Runtime>::get(), 1);

// User 1 votes in the referendum with all his funds
assert!(Balances::free_balance(1) != 0);
Expand All @@ -466,7 +471,7 @@ fn funds_used_for_voting_can_be_staked() {
vote: Vote { aye: true, conviction: Conviction::Locked1x },
balance: balance_in_vote,
};
assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), referendum, vote));
assert_ok!(mock::ConvictionVoting::vote(RuntimeOrigin::signed(1), 0, vote));

// WHEN
// User 1 wants to stake all his funds, so those that were used in voting
Expand All @@ -479,10 +484,7 @@ fn funds_used_for_voting_can_be_staked() {
// THEN
// User's funds are successfuly staked
assert_ok!(result);
assert_eq!(
Balances::reserved_balance(1),
balance_in_vote - mock::ExistentialDeposit::get()
);
assert_eq!(Balances::reserved_balance(1), balance_in_vote);
assert_eq!(Balances::free_balance(1), mock::ExistentialDeposit::get());
assert_eq!(
pallet_balances::Locks::<Runtime>::get(&1).to_vec().get(0).unwrap().amount,
Expand All @@ -496,11 +498,13 @@ fn funds_staked_can_be_used_for_voting() {
execute_with(ExtBuilder::default().build(), || {
// GIVEN
// A referendum exists that is in progress
let referendum = Democracy::internal_start_referendum(
set_balance_proposal(2),
VoteThreshold::SuperMajorityApprove,
0,
);
assert_ok!(Referenda::submit(
RuntimeOrigin::signed(1),
Box::new(RawOrigin::Root.into()),
set_balance_proposal_bounded(100),
DispatchTime::At(0),
));
assert_eq!(ReferendumCount::<Runtime>::get(), 1);

// User 1 stakes all his funds
let total_balance = Balances::free_balance(1);
Expand All @@ -513,15 +517,16 @@ fn funds_staked_can_be_used_for_voting() {
// WHEN
// User 1 wants to vote with a portion of his funds (so with tokens that are currently
// staked)
assert!(Balances::free_balance(1) != 0);
let vote = AccountVote::Standard {
vote: Vote { aye: true, conviction: Conviction::Locked1x },
balance: total_balance,
};
assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), referendum, vote));
assert_ok!(mock::ConvictionVoting::vote(RuntimeOrigin::signed(1), 0, vote));

// THEN
// User's funds are successfuly used to vote in referendum
assert_eq!(Balances::reserved_balance(1), total_balance - mock::ExistentialDeposit::get());
assert_eq!(Balances::reserved_balance(1), total_balance);
assert_eq!(Balances::free_balance(1), mock::ExistentialDeposit::get());
assert_eq!(
pallet_balances::Locks::<Runtime>::get(&1).to_vec().get(0).unwrap().amount,
Expand All @@ -534,13 +539,13 @@ fn funds_staked_can_be_used_for_voting() {
fn funds_being_vested_can_be_staked() {
execute_with(ExtBuilder::default().build(), || {
// GIVEN
// All the funds of user A are being vested
// All the funds of user 2 are being vested
let balance_being_vested = Balances::free_balance(&2);
let user2_vesting_schedule = VestingInfo::new(balance_being_vested, 2, 0);
assert_eq!(Vesting::vesting(2).unwrap().to_vec(), vec![user2_vesting_schedule]);

// WHEN
// User A wants to stake some of his funds, so those that are being vested
// User 2 wants to stake some of his funds, so those that are being vested
let result = Staking::bond(
RuntimeOrigin::signed(2),
balance_being_vested,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,27 @@

#![allow(dead_code)]

use crate::{log, log_current_time};
use codec::Decode;
use frame_election_provider_support::{
bounds::ElectionBoundsBuilder, onchain, ElectionDataProvider, ExtendedBalance,
SequentialPhragmen, Weight,
};
use frame_support::{
assert_ok, parameter_types, traits,
traits::{Hooks, UnfilteredDispatchable, VariantCountOf, WithdrawReasons},
assert_ok, derive_impl, parameter_types, traits,
traits::{EqualPrivilegeOnly, Hooks, UnfilteredDispatchable, VariantCountOf, WithdrawReasons},
weights::constants,
PalletId,
};
use frame_system::{EnsureRoot, EnsureSigned};
use sp_core::{ConstBool, ConstU32, ConstU64, Get};
use pallet_election_provider_multi_phase::{
unsigned::MinerConfig, Call, CurrentPhase, ElectionCompute, GeometricDepositBase,
QueuedSolution, SolutionAccuracyOf,
};
use pallet_referenda::Curve;
use pallet_staking::{ActiveEra, CurrentEra, ErasStartSessionIndex, StakerStatus};
use parking_lot::RwLock;
use sp_core::{ConstU32, Get};
use sp_npos_elections::{ElectionScore, VoteWeight};
use sp_runtime::{
offchain::{
Expand All @@ -39,25 +52,7 @@ use sp_staking::{
offence::{OffenceDetails, OnOffenceHandler},
Agent, DelegationInterface, EraIndex, SessionIndex, StakingInterface,
};
use std::collections::BTreeMap;

use codec::Decode;
use frame_election_provider_support::{
bounds::ElectionBoundsBuilder, onchain, ElectionDataProvider, ExtendedBalance,
SequentialPhragmen, Weight,
};
use pallet_election_provider_multi_phase::{
unsigned::MinerConfig, Call, CurrentPhase, ElectionCompute, GeometricDepositBase,
QueuedSolution, SolutionAccuracyOf,
};
use pallet_staking::{ActiveEra, CurrentEra, ErasStartSessionIndex, StakerStatus};
use parking_lot::RwLock;
use std::sync::Arc;

use crate::{log, log_current_time};
use frame_support::{derive_impl, traits::EqualPrivilegeOnly};

use sp_runtime::traits::Identity;
use std::{collections::BTreeMap, sync::Arc};

pub const INIT_TIMESTAMP: BlockNumber = 30_000;
pub const BLOCK_TIME: BlockNumber = 1000;
Expand All @@ -79,8 +74,9 @@ frame_support::construct_runtime!(
Timestamp: pallet_timestamp,
Preimage: pallet_preimage,
Scheduler: pallet_scheduler,
Democracy: pallet_democracy,
Vesting: pallet_vesting,
Referenda: pallet_referenda,
ConvictionVoting: pallet_conviction_voting,
}
);

Expand Down Expand Up @@ -117,38 +113,75 @@ impl pallet_scheduler::Config for Runtime {
type Preimages = Preimage;
}

impl pallet_democracy::Config for Runtime {
type WeightInfo = ();
parameter_types! {
pub const AlarmInterval: BlockNumber = 1;
pub const SubmissionDeposit: Balance = 1;
pub const UndecidingTimeout: BlockNumber = 10;
}

const fn percent(x: i32) -> sp_arithmetic::FixedI64 {
sp_arithmetic::FixedI64::from_rational(x as u128, 100)
}

const TRACKS_DATA: [(u16, pallet_referenda::TrackInfo<Balance, BlockNumber>); 1] = [(
0,
pallet_referenda::TrackInfo {
name: "root",
max_deciding: 1,
decision_deposit: 100,
prepare_period: 8,
decision_period: 2,
confirm_period: 12,
min_enactment_period: 5,
min_approval: Curve::make_linear(20, 20, percent(0), percent(10)),
min_support: Curve::make_linear(20, 20, percent(0), percent(10)),
},
)];

pub struct TracksInfo;
impl pallet_referenda::TracksInfo<Balance, BlockNumber> for TracksInfo {
type Id = u16;
type RuntimeOrigin = <RuntimeOrigin as frame_support::traits::OriginTrait>::PalletsOrigin;
fn tracks() -> &'static [(Self::Id, pallet_referenda::TrackInfo<Balance, BlockNumber>)] {
&TRACKS_DATA[..]
}
fn track_for(_: &Self::RuntimeOrigin) -> Result<Self::Id, ()> {
Ok(0)
}
}
pallet_referenda::impl_tracksinfo_get!(TracksInfo, Balance, BlockNumber);

impl pallet_referenda::Config for Runtime {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
type Scheduler = Scheduler;
type Currency = Balances;
type EnactmentPeriod = ConstU32<2>;
type LaunchPeriod = ConstU32<2>;
type VotingPeriod = ConstU32<2>;
type VoteLockingPeriod = ConstU32<3>;
type FastTrackVotingPeriod = ConstU32<2>;
type MinimumDeposit = ConstU64<1>;
type MaxDeposits = ConstU32<1000>;
type MaxBlacklisted = ConstU32<5>;
type SubmitOrigin = EnsureSigned<Self::AccountId>;
type ExternalOrigin = EnsureSigned<Self::AccountId>;
type ExternalMajorityOrigin = EnsureSigned<Self::AccountId>;
type ExternalDefaultOrigin = EnsureSigned<Self::AccountId>;
type FastTrackOrigin = EnsureSigned<Self::AccountId>;
type CancellationOrigin = EnsureSigned<Self::AccountId>;
type BlacklistOrigin = EnsureRoot<Self::AccountId>;
type CancelProposalOrigin = EnsureRoot<Self::AccountId>;
type VetoOrigin = EnsureSigned<Self::AccountId>;
type CooloffPeriod = ConstU32<2>;
type CancelOrigin = EnsureSigned<Self::AccountId>;
type KillOrigin = EnsureSigned<Self::AccountId>;
type Slash = ();
type InstantOrigin = EnsureSigned<Self::AccountId>;
type InstantAllowed = ConstBool<true>;
type MaxVotes = ConstU32<100>;
type PalletsOrigin = OriginCaller;
type MaxProposals = ConstU32<100>;
type Votes = pallet_conviction_voting::VotesOf<Runtime>;
type Tally = pallet_conviction_voting::TallyOf<Runtime>;
type SubmissionDeposit = SubmissionDeposit;
type MaxQueued = ConstU32<100>;
type UndecidingTimeout = UndecidingTimeout;
type AlarmInterval = AlarmInterval;
type Tracks = TracksInfo;
type Preimages = Preimage;
}

impl pallet_conviction_voting::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
type Currency = Balances;
type Polls = Referenda;
type MaxTurnout =
frame_support::traits::tokens::currency::ActiveIssuanceOf<Balances, Self::AccountId>;
type MaxVotes = ConstU32<100>;
type VoteLockingPeriod = ConstU32<3>;
}

parameter_types! {
pub const MinVestedTransfer: u64 = 1;
pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
Expand Down Expand Up @@ -700,7 +733,8 @@ impl ExtBuilder {
<Staking as Hooks<u32>>::on_initialize(1);
Timestamp::set_timestamp(INIT_TIMESTAMP);
Vesting::on_initialize(1);
Democracy::on_initialize(1);
Referenda::on_initialize(1);
ConvictionVoting::on_initialize(1);
});

ext
Expand Down

0 comments on commit d45a846

Please sign in to comment.