Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate pallet-referenda to use umbrella crate #7236

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions Cargo.lock

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

24 changes: 3 additions & 21 deletions substrate/frame/referenda/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,56 +20,38 @@ assert_matches = { optional = true, workspace = true }
codec = { features = [
"derive",
], workspace = true }
frame-benchmarking = { optional = true, workspace = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
frame = { workspace = true, features = ["runtime"]}
log = { workspace = true }
scale-info = { features = ["derive"], workspace = true }
serde = { features = ["derive"], optional = true, workspace = true, default-features = true }
sp-arithmetic = { workspace = true }
sp-io = { workspace = true }
sp-runtime = { workspace = true }

[dev-dependencies]
assert_matches = { workspace = true }
pallet-balances = { workspace = true, default-features = true }
pallet-preimage = { workspace = true, default-features = true }
pallet-scheduler = { workspace = true, default-features = true }
gui1117 marked this conversation as resolved.
Show resolved Hide resolved
sp-core = { workspace = true, default-features = true }

[features]
default = ["std"]
std = [
"codec/std",
"frame-benchmarking?/std",
"frame-support/std",
"frame-system/std",
"frame/std",
"log/std",
"pallet-balances/std",
"pallet-preimage/std",
"pallet-scheduler/std",
"scale-info/std",
"serde",
"sp-arithmetic/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
]
runtime-benchmarks = [
"assert_matches",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-preimage/runtime-benchmarks",
"pallet-scheduler/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-balances/try-runtime",
"pallet-preimage/try-runtime",
"pallet-scheduler/try-runtime",
"sp-runtime/try-runtime",
"frame/try-runtime",
]
12 changes: 2 additions & 10 deletions substrate/frame/referenda/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,12 @@ use super::*;
use crate::Pallet as Referenda;
use alloc::{vec, vec::Vec};
use assert_matches::assert_matches;
use frame_benchmarking::v1::{
account, benchmarks_instance_pallet, whitelist_account, BenchmarkError,
};
use frame_support::{
assert_ok,
traits::{Currency, EnsureOrigin, EnsureOriginWithArg, UnfilteredDispatchable},
};
use frame_system::RawOrigin;
use sp_runtime::traits::Bounded as ArithBounded;
use frame::benchmarking::prelude::{Pallet as System, RawOrigin, *};

const SEED: u32 = 0;

fn assert_last_event<T: Config<I>, I: 'static>(generic_event: <T as Config<I>>::RuntimeEvent) {
frame_system::Pallet::<T>::assert_last_event(generic_event.into());
System::<T>::assert_last_event(generic_event.into());
}

fn funded_account<T: Config<I>, I: 'static>(name: &'static str, index: u32) -> T::AccountId {
Expand Down
15 changes: 6 additions & 9 deletions substrate/frame/referenda/src/branch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

use super::Config;
use crate::weights::WeightInfo;
use frame_support::weights::Weight;

/// Branches within the `begin_deciding` function.
pub enum BeginDecidingBranch {
Expand Down Expand Up @@ -60,7 +59,7 @@ impl From<BeginDecidingBranch> for ServiceBranch {

impl ServiceBranch {
/// Return the weight of the `nudge` function when it takes the branch denoted by `self`.
pub fn weight_of_nudge<T: Config<I>, I: 'static>(self) -> frame_support::weights::Weight {
pub fn weight_of_nudge<T: Config<I>, I: 'static>(self) -> Weight {
use ServiceBranch::*;
match self {
NoDeposit => T::WeightInfo::nudge_referendum_no_deposit(),
Expand All @@ -82,7 +81,7 @@ impl ServiceBranch {
}

/// Return the maximum possible weight of the `nudge` function.
pub fn max_weight_of_nudge<T: Config<I>, I: 'static>() -> frame_support::weights::Weight {
pub fn max_weight_of_nudge<T: Config<I>, I: 'static>() -> Weight {
Weight::zero()
.max(T::WeightInfo::nudge_referendum_no_deposit())
.max(T::WeightInfo::nudge_referendum_preparing())
Expand All @@ -103,9 +102,7 @@ impl ServiceBranch {

/// Return the weight of the `place_decision_deposit` function when it takes the branch denoted
/// by `self`.
pub fn weight_of_deposit<T: Config<I>, I: 'static>(
self,
) -> Option<frame_support::weights::Weight> {
pub fn weight_of_deposit<T: Config<I>, I: 'static>(self) -> Option<Weight> {
use ServiceBranch::*;
let ref_time_weight = match self {
Preparing => T::WeightInfo::place_decision_deposit_preparing(),
Expand All @@ -130,7 +127,7 @@ impl ServiceBranch {
}

/// Return the maximum possible weight of the `place_decision_deposit` function.
pub fn max_weight_of_deposit<T: Config<I>, I: 'static>() -> frame_support::weights::Weight {
pub fn max_weight_of_deposit<T: Config<I>, I: 'static>() -> Weight {
Weight::zero()
.max(T::WeightInfo::place_decision_deposit_preparing())
.max(T::WeightInfo::place_decision_deposit_queued())
Expand Down Expand Up @@ -161,7 +158,7 @@ impl From<BeginDecidingBranch> for OneFewerDecidingBranch {
impl OneFewerDecidingBranch {
/// Return the weight of the `one_fewer_deciding` function when it takes the branch denoted
/// by `self`.
pub fn weight<T: Config<I>, I: 'static>(self) -> frame_support::weights::Weight {
pub fn weight<T: Config<I>, I: 'static>(self) -> Weight {
use OneFewerDecidingBranch::*;
match self {
QueueEmpty => T::WeightInfo::one_fewer_deciding_queue_empty(),
Expand All @@ -171,7 +168,7 @@ impl OneFewerDecidingBranch {
}

/// Return the maximum possible weight of the `one_fewer_deciding` function.
pub fn max_weight<T: Config<I>, I: 'static>() -> frame_support::weights::Weight {
pub fn max_weight<T: Config<I>, I: 'static>() -> Weight {
Weight::zero()
.max(T::WeightInfo::one_fewer_deciding_queue_empty())
.max(T::WeightInfo::one_fewer_deciding_passing())
Expand Down
45 changes: 13 additions & 32 deletions substrate/frame/referenda/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,25 +69,10 @@ extern crate alloc;
use alloc::boxed::Box;
use codec::{Codec, Encode};
use core::fmt::Debug;
use frame_support::{
dispatch::DispatchResult,
ensure,
traits::{
schedule::{
v3::{Anon as ScheduleAnon, Named as ScheduleNamed},
DispatchTime,
},
Currency, LockIdentifier, OnUnbalanced, OriginTrait, PollStatus, Polling, QueryPreimage,
ReservableCurrency, StorePreimage, VoteTally,
},
BoundedVec,
};
use frame_system::pallet_prelude::BlockNumberFor;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

use scale_info::TypeInfo;
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Bounded, Dispatchable, One, Saturating, Zero},
DispatchError, Perbill,
};

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

use frame::runtime::prelude::*;

mod branch;
pub mod migration;
Expand Down Expand Up @@ -115,8 +100,6 @@ mod tests;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;

pub use frame_support::traits::Get;

#[macro_export]
macro_rules! impl_tracksinfo_get {
($tracksinfo:ty, $balance:ty, $blocknumber:ty) => {
Expand All @@ -140,11 +123,10 @@ macro_rules! impl_tracksinfo_get {

const ASSEMBLY_ID: LockIdentifier = *b"assembly";

#[frame_support::pallet]
#[frame::pallet]
pub mod pallet {
use super::*;
use frame_support::{pallet_prelude::*, traits::EnsureOriginWithArg};
use frame_system::pallet_prelude::*;
use frame::traits::EnsureOriginWithArg;

/// The in-code storage version.
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
Expand Down Expand Up @@ -801,12 +783,11 @@ impl<T: Config<I>, I: 'static> Polling<T::Tally> for Pallet<T, I> {
r
});
let now = frame_system::Pallet::<T>::block_number();
let dummy_account_id =
codec::Decode::decode(&mut sp_runtime::traits::TrailingZeroInput::new(&b"dummy"[..]))
.expect("infinite length input; no invalid inputs for type; qed");
let dummy_account_id = codec::Decode::decode(&mut TrailingZeroInput::new(&b"dummy"[..]))
.expect("infinite length input; no invalid inputs for type; qed");
let mut status = ReferendumStatusOf::<T, I> {
track: class,
origin: frame_support::dispatch::RawOrigin::Root.into(),
origin: RawOrigin::Root.into(),
proposal: T::Preimages::bound(CallOf::<T, I>::from(Call::nudge_referendum { index }))
.map_err(|_| ())?,
enactment: DispatchTime::After(Zero::zero()),
Expand All @@ -818,7 +799,7 @@ impl<T: Config<I>, I: 'static> Polling<T::Tally> for Pallet<T, I> {
in_queue: false,
alarm: None,
};
Self::ensure_alarm_at(&mut status, index, sp_runtime::traits::Bounded::max_value());
Self::ensure_alarm_at(&mut status, index, Bounded::max_value());
ReferendumInfoFor::<T, I>::insert(index, ReferendumInfo::Ongoing(status));
Ok(index)
}
Expand Down Expand Up @@ -1335,7 +1316,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// [`ReferendumInfoFor`].
/// * Referendum indices in [`MetadataOf`] must also be stored in [`ReferendumInfoFor`].
#[cfg(any(feature = "try-runtime", test))]
fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
fn do_try_state() -> Result<(), TryRuntimeError> {
ensure!(
ReferendumCount::<T, I>::get() as usize ==
ReferendumInfoFor::<T, I>::iter_keys().count(),
Expand Down Expand Up @@ -1365,7 +1346,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// * If alarm is set the nudge call has to be at most [`UndecidingTimeout`] blocks away
/// from the submission block.
#[cfg(any(feature = "try-runtime", test))]
fn try_state_referenda_info() -> Result<(), sp_runtime::TryRuntimeError> {
fn try_state_referenda_info() -> Result<(), TryRuntimeError> {
ReferendumInfoFor::<T, I>::iter().try_for_each(|(_, referendum)| {
match referendum {
ReferendumInfo::Ongoing(status) => {
Expand Down Expand Up @@ -1393,10 +1374,10 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// * The referendum indices stored in [`TrackQueue`] must exist as keys in the
/// [`ReferendumInfoFor`] storage map.
#[cfg(any(feature = "try-runtime", test))]
fn try_state_tracks() -> Result<(), sp_runtime::TryRuntimeError> {
fn try_state_tracks() -> Result<(), TryRuntimeError> {
T::Tracks::tracks().iter().try_for_each(|track| {
TrackQueue::<T, I>::get(track.0).iter().try_for_each(
|(referendum_index, _)| -> Result<(), sp_runtime::TryRuntimeError> {
|(referendum_index, _)| -> Result<(), TryRuntimeError> {
ensure!(
ReferendumInfoFor::<T, I>::contains_key(referendum_index),
"`ReferendumIndex` inside the `TrackQueue` should be a key in `ReferendumInfoFor`"
Expand Down
12 changes: 5 additions & 7 deletions substrate/frame/referenda/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,9 @@

use super::*;
use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade};
use frame::testing_prelude::*;
use log;

#[cfg(feature = "try-runtime")]
use sp_runtime::TryRuntimeError;

/// Initial version of storage types.
pub mod v0 {
Expand All @@ -37,7 +35,7 @@ pub mod v0 {
pub type ReferendumInfoOf<T, I> = ReferendumInfo<
TrackIdOf<T, I>,
PalletsOriginOf<T>,
frame_system::pallet_prelude::BlockNumberFor<T>,
BlockNumberFor<T>,
BoundedCallOf<T, I>,
BalanceOf<T, I>,
TallyOf<T, I>,
Expand Down Expand Up @@ -96,9 +94,9 @@ pub mod v1 {
/// Transforms a submission deposit of ReferendumInfo(Approved|Rejected|Cancelled|TimedOut) to
/// optional value, making it refundable.
pub struct MigrateV0ToV1<T, I = ()>(PhantomData<(T, I)>);
impl<T: Config<I>, I: 'static> OnRuntimeUpgrade for MigrateV0ToV1<T, I> {
impl<T: Config<I>, I: 'static> frame::traits::OnRuntimeUpgrade for MigrateV0ToV1<T, I> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it not in the prelude?

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
fn pre_upgrade() -> Result<Vec<u8>, frame::try_runtime::TryRuntimeError> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it not in the prelude?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No it is not

let referendum_count = v0::ReferendumInfoFor::<T, I>::iter().count();
log::info!(
target: TARGET,
Expand Down Expand Up @@ -148,7 +146,7 @@ pub mod v1 {
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(state: Vec<u8>) -> Result<(), TryRuntimeError> {
fn post_upgrade(state: Vec<u8>) -> Result<(), frame::try_runtime::TryRuntimeError> {
let on_chain_version = Pallet::<T, I>::on_chain_storage_version();
ensure!(on_chain_version == 1, "must upgrade from version 0 to 1.");
let pre_referendum_count: u32 = Decode::decode(&mut &state[..])
Expand Down
27 changes: 8 additions & 19 deletions substrate/frame/referenda/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,11 @@
use super::*;
use crate as pallet_referenda;
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
assert_ok, derive_impl, ord_parameter_types, parameter_types,
traits::{
ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnInitialize, OriginTrait, Polling,
},
weights::Weight,
};
use frame_system::{EnsureRoot, EnsureSignedBy};
use sp_runtime::{
traits::{BlakeTwo256, Hash},
BuildStorage, DispatchResult, Perbill,
};

type Block = frame_system::mocking::MockBlock<Test>;

frame_support::construct_runtime!(
use frame::testing_prelude::*;

type Block = MockBlock<Test>;

construct_runtime!(
pub enum Test
{
System: frame_system,
Expand Down Expand Up @@ -216,13 +205,13 @@ impl Default for ExtBuilder {
}

impl ExtBuilder {
pub fn build(self) -> sp_io::TestExternalities {
pub fn build(self) -> TestState {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
let balances = vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100)];
pallet_balances::GenesisConfig::<Test> { balances }
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
let mut ext = TestState::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
Expand Down Expand Up @@ -428,7 +417,7 @@ impl RefState {
pub fn create(self) -> ReferendumIndex {
assert_ok!(Referenda::submit(
RuntimeOrigin::signed(1),
Box::new(frame_support::dispatch::RawOrigin::Root.into()),
Box::new(RawOrigin::Root.into()),
set_balance_proposal_bounded(1),
DispatchTime::At(10),
));
Expand Down
3 changes: 1 addition & 2 deletions substrate/frame/referenda/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@ use super::*;
use crate::mock::{RefState::*, *};
use assert_matches::assert_matches;
use codec::Decode;
use frame_support::{assert_noop, assert_ok, dispatch::RawOrigin, traits::Contains};
use frame::{testing_prelude::*, traits::Contains};
use pallet_balances::Error as BalancesError;
use sp_runtime::DispatchError::BadOrigin;

#[test]
fn params_should_work() {
Expand Down
Loading
Loading