From d579b673672454d0dc7b5049e5cbbe6077da520b Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 25 Mar 2024 16:16:58 +0700 Subject: [PATCH 01/25] Remove deprecated treasury pallet calls --- prdoc/pr_3800.prdoc | 12 + substrate/frame/treasury/README.md | 14 +- substrate/frame/treasury/src/lib.rs | 126 ----------- substrate/frame/treasury/src/tests.rs | 308 ++------------------------ 4 files changed, 36 insertions(+), 424 deletions(-) create mode 100644 prdoc/pr_3800.prdoc diff --git a/prdoc/pr_3800.prdoc b/prdoc/pr_3800.prdoc new file mode 100644 index 0000000000000..3396e8c21612d --- /dev/null +++ b/prdoc/pr_3800.prdoc @@ -0,0 +1,12 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Remove deprecated calls from treasury pallet + +doc: + - audience: Runtime Dev + description: | + This PR remove deprecated calls, relevant tests from `pallet-treasury` + +crates: + - name: pallet-treasury diff --git a/substrate/frame/treasury/README.md b/substrate/frame/treasury/README.md index 4945d79d14296..2bd58a9817aab 100644 --- a/substrate/frame/treasury/README.md +++ b/substrate/frame/treasury/README.md @@ -26,6 +26,14 @@ and use the funds to pay developers. ### Dispatchable Functions General spending/proposal protocol: -- `propose_spend` - Make a spending proposal and stake the required deposit. -- `reject_proposal` - Reject a proposal, slashing the deposit. -- `approve_proposal` - Accept the proposal, returning the deposit. +- `spend_local` - Propose and approve a spend of treasury funds, enables the + creation of spends using the native currency of the chain, utilizing the funds + stored in the pot +- `spend` - Propose and approve a spend of treasury funds, allows spending any + asset kind managed by the treasury +- `remove_approval` - Force a previously approved proposal to be removed from + the approval queue +- `payout` - Claim a spend +- `check_status` - Check the status of the spend and remove it from the storage + if processed +- `void_spend` - Void previously approved spend diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 5e429d3914bd0..f7873fe51004f 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -203,9 +203,6 @@ pub mod pallet { /// The staking balance. type Currency: Currency + ReservableCurrency; - /// Origin from which approvals must come. - type ApproveOrigin: EnsureOrigin; - /// Origin from which rejections must come. type RejectOrigin: EnsureOrigin; @@ -361,14 +358,10 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { - /// New proposal. - Proposed { proposal_index: ProposalIndex }, /// We have ended a spend period and will now allocate funds. Spending { budget_remaining: BalanceOf }, /// Some funds have been allocated. Awarded { proposal_index: ProposalIndex, award: BalanceOf, account: T::AccountId }, - /// A proposal was rejected; funds were slashed. - Rejected { proposal_index: ProposalIndex, slashed: BalanceOf }, /// Some of our funds have been burnt. Burnt { burnt_funds: BalanceOf }, /// Spending has finished; this is the amount that rolls over until next spend. @@ -406,8 +399,6 @@ pub mod pallet { /// Error for the treasury pallet. #[pallet::error] pub enum Error { - /// Proposer's balance is too low. - InsufficientProposersBalance, /// No proposal, bounty or spend at that index. InvalidIndex, /// Too many approvals in the queue. @@ -474,123 +465,6 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { - /// Put forward a suggestion for spending. - /// - /// ## Dispatch Origin - /// - /// Must be signed. - /// - /// ## Details - /// A deposit proportional to the value is reserved and slashed if the proposal is rejected. - /// It is returned once the proposal is awarded. - /// - /// ### Complexity - /// - O(1) - /// - /// ## Events - /// - /// Emits [`Event::Proposed`] if successful. - #[pallet::call_index(0)] - #[pallet::weight(T::WeightInfo::propose_spend())] - #[allow(deprecated)] - #[deprecated( - note = "`propose_spend` will be removed in February 2024. Use `spend` instead." - )] - pub fn propose_spend( - origin: OriginFor, - #[pallet::compact] value: BalanceOf, - beneficiary: AccountIdLookupOf, - ) -> DispatchResult { - let proposer = ensure_signed(origin)?; - let beneficiary = T::Lookup::lookup(beneficiary)?; - - let bond = Self::calculate_bond(value); - T::Currency::reserve(&proposer, bond) - .map_err(|_| Error::::InsufficientProposersBalance)?; - - let c = Self::proposal_count(); - >::put(c + 1); - >::insert(c, Proposal { proposer, value, beneficiary, bond }); - - Self::deposit_event(Event::Proposed { proposal_index: c }); - Ok(()) - } - - /// Reject a proposed spend. - /// - /// ## Dispatch Origin - /// - /// Must be [`Config::RejectOrigin`]. - /// - /// ## Details - /// The original deposit will be slashed. - /// - /// ### Complexity - /// - O(1) - /// - /// ## Events - /// - /// Emits [`Event::Rejected`] if successful. - #[pallet::call_index(1)] - #[pallet::weight((T::WeightInfo::reject_proposal(), DispatchClass::Operational))] - #[allow(deprecated)] - #[deprecated( - note = "`reject_proposal` will be removed in February 2024. Use `spend` instead." - )] - pub fn reject_proposal( - origin: OriginFor, - #[pallet::compact] proposal_id: ProposalIndex, - ) -> DispatchResult { - T::RejectOrigin::ensure_origin(origin)?; - - let proposal = - >::take(&proposal_id).ok_or(Error::::InvalidIndex)?; - let value = proposal.bond; - let imbalance = T::Currency::slash_reserved(&proposal.proposer, value).0; - T::OnSlash::on_unbalanced(imbalance); - - Self::deposit_event(Event::::Rejected { - proposal_index: proposal_id, - slashed: value, - }); - Ok(()) - } - - /// Approve a proposal. - /// - /// ## Dispatch Origin - /// - /// Must be [`Config::ApproveOrigin`]. - /// - /// ## Details - /// - /// At a later time, the proposal will be allocated to the beneficiary and the original - /// deposit will be returned. - /// - /// ### Complexity - /// - O(1). - /// - /// ## Events - /// - /// No events are emitted from this dispatch. - #[pallet::call_index(2)] - #[pallet::weight((T::WeightInfo::approve_proposal(T::MaxApprovals::get()), DispatchClass::Operational))] - #[allow(deprecated)] - #[deprecated( - note = "`approve_proposal` will be removed in February 2024. Use `spend` instead." - )] - pub fn approve_proposal( - origin: OriginFor, - #[pallet::compact] proposal_id: ProposalIndex, - ) -> DispatchResult { - T::ApproveOrigin::ensure_origin(origin)?; - - ensure!(>::contains_key(proposal_id), Error::::InvalidIndex); - Approvals::::try_append(proposal_id) - .map_err(|_| Error::::TooManyApprovals)?; - Ok(()) - } - /// Propose and approve a spend of treasury funds. /// /// ## Dispatch Origin diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 67d81cb5c3022..11e9f76c5b8a5 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -152,6 +152,7 @@ impl frame_support::traits::EnsureOrigin for TestSpendOrigin { frame_system::RawOrigin::Signed(11) => Ok(10), frame_system::RawOrigin::Signed(12) => Ok(20), frame_system::RawOrigin::Signed(13) => Ok(50), + frame_system::RawOrigin::Signed(14) => Ok(500), r => Err(RuntimeOrigin::from(r)), }) } @@ -174,7 +175,6 @@ impl> ConversionFromAssetBalance for MulBy { impl Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); @@ -295,56 +295,12 @@ fn minting_works() { }); } -#[test] -fn spend_proposal_takes_min_deposit() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_eq!(Balances::free_balance(0), 99); - assert_eq!(Balances::reserved_balance(0), 1); - }); -} - -#[test] -fn spend_proposal_takes_proportional_deposit() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_eq!(Balances::free_balance(0), 95); - assert_eq!(Balances::reserved_balance(0), 5); - }); -} - -#[test] -fn spend_proposal_fails_when_proposer_poor() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(2), 100, 3) - }, - Error::::InsufficientProposersBalance, - ); - }); -} - #[test] fn accepted_spend_proposal_ignored_outside_spend_period() { ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); >::on_initialize(1); assert_eq!(Balances::free_balance(3), 0); @@ -365,112 +321,13 @@ fn unused_pot_should_diminish() { }); } -#[test] -fn rejected_spend_proposal_ignored_on_spend_period() { - ExtBuilder::default().build().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - - >::on_initialize(2); - assert_eq!(Balances::free_balance(3), 0); - assert_eq!(Treasury::pot(), 50); - }); -} - -#[test] -fn reject_already_rejected_spend_proposal_fails() { - ExtBuilder::default().build().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - assert_noop!( - { - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }, - Error::::InvalidIndex - ); - }); -} - -#[test] -fn reject_non_existent_spend_proposal_fails() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }, - Error::::InvalidIndex - ); - }); -} - -#[test] -fn accept_non_existent_spend_proposal_fails() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, - Error::::InvalidIndex - ); - }); -} - -#[test] -fn accept_already_rejected_spend_proposal_fails() { - ExtBuilder::default().build().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, - Error::::InvalidIndex - ); - }); -} - #[test] fn accepted_spend_proposal_enacted_on_spend_period() { ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); >::on_initialize(2); assert_eq!(Balances::free_balance(3), 100); @@ -484,14 +341,7 @@ fn pot_underflow_should_not_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 150, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 150, 3)); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed @@ -512,26 +362,12 @@ fn treasury_account_doesnt_get_deleted() { assert_eq!(Treasury::pot(), 100); let treasury_balance = Balances::free_balance(&Treasury::account_id()); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), treasury_balance, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), treasury_balance, 3)); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), Treasury::pot(), 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 1) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), Treasury::pot(), 3)); >::on_initialize(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied @@ -554,22 +390,9 @@ fn inexistent_account_works() { assert_eq!(Balances::free_balance(Treasury::account_id()), 0); // Account does not exist assert_eq!(Treasury::pot(), 0); // Pot is empty - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 99, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 1) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 99, 3)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + >::on_initialize(2); assert_eq!(Treasury::pot(), 0); // Pot hasn't changed assert_eq!(Balances::free_balance(3), 0); // Balance of `3` hasn't changed @@ -611,26 +434,12 @@ fn max_approvals_limited() { Balances::make_free_balance_be(&0, u64::MAX); for _ in 0..::MaxApprovals::get() { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); } // One too many will fail - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, + Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3), Error::::TooManyApprovals ); }); @@ -641,14 +450,8 @@ fn remove_already_removed_approval_fails() { ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); + assert_eq!(Treasury::approvals(), vec![0]); assert_ok!(Treasury::remove_approval(RuntimeOrigin::root(), 0)); assert_eq!(Treasury::approvals(), vec![]); @@ -978,91 +781,6 @@ fn check_status_works() { }); } -#[test] -fn try_state_proposals_invariant_1_works() { - ExtBuilder::default().build().execute_with(|| { - use frame_support::pallet_prelude::DispatchError::Other; - // Add a proposal using `propose_spend` - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_eq!(Proposals::::iter().count(), 1); - assert_eq!(ProposalCount::::get(), 1); - // Check invariant 1 holds - assert!(ProposalCount::::get() as usize >= Proposals::::iter().count()); - // Break invariant 1 by decreasing `ProposalCount` - ProposalCount::::put(0); - // Invariant 1 should be violated - assert_eq!( - Treasury::do_try_state(), - Err(Other("Actual number of proposals exceeds `ProposalCount`.")) - ); - }); -} - -#[test] -fn try_state_proposals_invariant_2_works() { - ExtBuilder::default().build().execute_with(|| { - use frame_support::pallet_prelude::DispatchError::Other; - // Add a proposal using `propose_spend` - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_eq!(Proposals::::iter().count(), 1); - let current_proposal_count = ProposalCount::::get(); - assert_eq!(current_proposal_count, 1); - // Check invariant 2 holds - assert!( - Proposals::::iter_keys() - .all(|proposal_index| { - proposal_index < current_proposal_count - }) - ); - // Break invariant 2 by inserting the proposal under key = 1 - let proposal = Proposals::::take(0).unwrap(); - Proposals::::insert(1, proposal); - // Invariant 2 should be violated - assert_eq!( - Treasury::do_try_state(), - Err(Other("`ProposalCount` should by strictly greater than any ProposalIndex used as a key for `Proposals`.")) - ); - }); -} - -#[test] -fn try_state_proposals_invariant_3_works() { - ExtBuilder::default().build().execute_with(|| { - use frame_support::pallet_prelude::DispatchError::Other; - // Add a proposal using `propose_spend` - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 10, 3) - }); - assert_eq!(Proposals::::iter().count(), 1); - // Approve the proposal - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); - assert_eq!(Approvals::::get().len(), 1); - // Check invariant 3 holds - assert!(Approvals::::get() - .iter() - .all(|proposal_index| { Proposals::::contains_key(proposal_index) })); - // Break invariant 3 by adding another key to `Approvals` - let mut approvals_modified = Approvals::::get(); - approvals_modified.try_push(2).unwrap(); - Approvals::::put(approvals_modified); - // Invariant 3 should be violated - assert_eq!( - Treasury::do_try_state(), - Err(Other("Proposal indices in `Approvals` must also be contained in `Proposals`.")) - ); - }); -} - #[test] fn try_state_spends_invariant_1_works() { ExtBuilder::default().build().execute_with(|| { From 1a3d5f1f96756555ddebd1b898c03464ffffdb25 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 25 Mar 2024 16:52:47 +0700 Subject: [PATCH 02/25] Update benchmarking.rs --- substrate/frame/treasury/src/benchmarking.rs | 74 ++------------------ 1 file changed, 7 insertions(+), 67 deletions(-) diff --git a/substrate/frame/treasury/src/benchmarking.rs b/substrate/frame/treasury/src/benchmarking.rs index 0b9999e37fbea..735e1df7b92c7 100644 --- a/substrate/frame/treasury/src/benchmarking.rs +++ b/substrate/frame/treasury/src/benchmarking.rs @@ -73,12 +73,10 @@ fn setup_proposal, I: 'static>( // Create proposals that are approved for use in `on_initialize`. fn create_approved_proposals, I: 'static>(n: u32) -> Result<(), &'static str> { + let origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; for i in 0..n { - let (caller, value, lookup) = setup_proposal::(i); - #[allow(deprecated)] - Treasury::::propose_spend(RawOrigin::Signed(caller).into(), value, lookup)?; - let proposal_id = >::get() - 1; - Approvals::::try_append(proposal_id).unwrap(); + let (_, value, lookup) = setup_proposal::(i); + Treasury::::spend_local(origin.clone(), value, lookup)?; } ensure!(>::get().len() == n as usize, "Not all approved"); Ok(()) @@ -126,71 +124,13 @@ mod benchmarks { Ok(()) } - #[benchmark] - fn propose_spend() -> Result<(), BenchmarkError> { - let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); - // Whitelist caller account from further DB operations. - let caller_key = frame_system::Account::::hashed_key_for(&caller); - frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); - - #[extrinsic_call] - _(RawOrigin::Signed(caller), value, beneficiary_lookup); - - Ok(()) - } - - #[benchmark] - fn reject_proposal() -> Result<(), BenchmarkError> { - let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); - #[allow(deprecated)] - Treasury::::propose_spend( - RawOrigin::Signed(caller).into(), - value, - beneficiary_lookup, - )?; - let proposal_id = Treasury::::proposal_count() - 1; - let reject_origin = - T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - - #[extrinsic_call] - _(reject_origin as T::RuntimeOrigin, proposal_id); - - Ok(()) - } - - #[benchmark] - fn approve_proposal( - p: Linear<0, { T::MaxApprovals::get() - 1 }>, - ) -> Result<(), BenchmarkError> { - let approve_origin = - T::ApproveOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - create_approved_proposals::(p)?; - let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); - #[allow(deprecated)] - Treasury::::propose_spend( - RawOrigin::Signed(caller).into(), - value, - beneficiary_lookup, - )?; - let proposal_id = Treasury::::proposal_count() - 1; - - #[extrinsic_call] - _(approve_origin as T::RuntimeOrigin, proposal_id); - - Ok(()) - } - #[benchmark] fn remove_approval() -> Result<(), BenchmarkError> { - let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); - #[allow(deprecated)] - Treasury::::propose_spend( - RawOrigin::Signed(caller).into(), - value, - beneficiary_lookup, - )?; + let origin = + T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let (_, value, beneficiary_lookup) = setup_proposal::(SEED); + Treasury::::spend_local(origin, value, beneficiary_lookup)?; let proposal_id = Treasury::::proposal_count() - 1; - Approvals::::try_append(proposal_id).unwrap(); let reject_origin = T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; From 3d26a9235d84fb3b353ac537e4c1b49d482581a1 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 25 Mar 2024 17:58:34 +0700 Subject: [PATCH 03/25] Remove unused ProposalBond parameter --- substrate/frame/treasury/src/benchmarking.rs | 2 +- substrate/frame/treasury/src/lib.rs | 22 -------------------- substrate/frame/treasury/src/tests.rs | 4 ---- 3 files changed, 1 insertion(+), 27 deletions(-) diff --git a/substrate/frame/treasury/src/benchmarking.rs b/substrate/frame/treasury/src/benchmarking.rs index 735e1df7b92c7..f5fc4cdcab4c6 100644 --- a/substrate/frame/treasury/src/benchmarking.rs +++ b/substrate/frame/treasury/src/benchmarking.rs @@ -64,7 +64,7 @@ fn setup_proposal, I: 'static>( u: u32, ) -> (T::AccountId, BalanceOf, AccountIdLookupOf) { let caller = account("caller", u, SEED); - let value: BalanceOf = T::ProposalBondMinimum::get().saturating_mul(100u32.into()); + let value: BalanceOf = 100u32.try_into().ok().unwrap(); let _ = T::Currency::make_free_balance_be(&caller, value); let beneficiary = account("beneficiary", u, SEED); let beneficiary_lookup = T::Lookup::unlookup(beneficiary); diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index f7873fe51004f..dc58780f892c6 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -213,19 +213,6 @@ pub mod pallet { /// Handler for the unbalanced decrease when slashing for a rejected proposal or bounty. type OnSlash: OnUnbalanced>; - /// Fraction of a proposal's value that should be bonded in order to place the proposal. - /// An accepted proposal gets these back. A rejected proposal does not. - #[pallet::constant] - type ProposalBond: Get; - - /// Minimum amount of funds that should be placed in a deposit for making a proposal. - #[pallet::constant] - type ProposalBondMinimum: Get>; - - /// Maximum amount of funds that should be placed in a deposit for making a proposal. - #[pallet::constant] - type ProposalBondMaximum: Get>>; - /// Period between successive spends. #[pallet::constant] type SpendPeriod: Get>; @@ -806,15 +793,6 @@ impl, I: 'static> Pallet { T::PalletId::get().into_account_truncating() } - /// The needed bond for a proposal whose spend is `value`. - fn calculate_bond(value: BalanceOf) -> BalanceOf { - let mut r = T::ProposalBondMinimum::get().max(T::ProposalBond::get() * value); - if let Some(m) = T::ProposalBondMaximum::get() { - r = r.min(m); - } - r - } - /// Spend some money! returns number of approvals before spend. pub fn spend_funds() -> Weight { let mut total_weight = Weight::zero(); diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 11e9f76c5b8a5..19318ed036c91 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -136,7 +136,6 @@ impl Pay for TestPay { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub TreasuryAccount: u128 = Treasury::account_id(); @@ -178,9 +177,6 @@ impl Config for Test { type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. From 2f1c63220516be9d50dff104bc41a0621e950c33 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 25 Mar 2024 18:02:46 +0700 Subject: [PATCH 04/25] Remove OnSlash parameter --- substrate/frame/treasury/src/lib.rs | 3 --- substrate/frame/treasury/src/tests.rs | 1 - 2 files changed, 4 deletions(-) diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index dc58780f892c6..7bdd102878d25 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -210,9 +210,6 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; - /// Handler for the unbalanced decrease when slashing for a rejected proposal or bounty. - type OnSlash: OnUnbalanced>; - /// Period between successive spends. #[pallet::constant] type SpendPeriod: Get>; diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 19318ed036c91..6bfa3c426134e 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -176,7 +176,6 @@ impl Config for Test { type Currency = pallet_balances::Pallet; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. From 2243192b472020fd4946543e468ff18e7ae8eada Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Tue, 26 Mar 2024 07:59:46 +0700 Subject: [PATCH 05/25] Update proposal invariant tests --- substrate/frame/treasury/src/tests.rs | 75 +++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 6bfa3c426134e..1c96bc7eeb8f2 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -776,6 +776,81 @@ fn check_status_works() { }); } +#[test] +fn try_state_proposals_invariant_1_works() { + ExtBuilder::default().build().execute_with(|| { + use frame_support::pallet_prelude::DispatchError::Other; + // Add a proposal and approve using `spend_local` + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + + assert_eq!(Proposals::::iter().count(), 1); + assert_eq!(ProposalCount::::get(), 1); + // Check invariant 1 holds + assert!(ProposalCount::::get() as usize >= Proposals::::iter().count()); + // Break invariant 1 by decreasing `ProposalCount` + ProposalCount::::put(0); + // Invariant 1 should be violated + assert_eq!( + Treasury::do_try_state(), + Err(Other("Actual number of proposals exceeds `ProposalCount`.")) + ); + }); +} + +#[test] +fn try_state_proposals_invariant_2_works() { + ExtBuilder::default().build().execute_with(|| { + use frame_support::pallet_prelude::DispatchError::Other; + // Add a proposal and approve using `spend_local` + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + + assert_eq!(Proposals::::iter().count(), 1); + assert_eq!(Approvals::::get().len(), 1); + let current_proposal_count = ProposalCount::::get(); + assert_eq!(current_proposal_count, 1); + // Check invariant 2 holds + assert!( + Proposals::::iter_keys() + .all(|proposal_index| { + proposal_index < current_proposal_count + }) + ); + // Break invariant 2 by inserting the proposal under key = 1 + let proposal = Proposals::::take(0).unwrap(); + Proposals::::insert(1, proposal); + // Invariant 2 should be violated + assert_eq!( + Treasury::do_try_state(), + Err(Other("`ProposalCount` should by strictly greater than any ProposalIndex used as a key for `Proposals`.")) + ); + }); +} + +#[test] +fn try_state_proposals_invariant_3_works() { + ExtBuilder::default().build().execute_with(|| { + use frame_support::pallet_prelude::DispatchError::Other; + // Add a proposal and approve using `spend_local` + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 10, 3)); + + assert_eq!(Proposals::::iter().count(), 1); + assert_eq!(Approvals::::get().len(), 1); + // Check invariant 3 holds + assert!(Approvals::::get() + .iter() + .all(|proposal_index| { Proposals::::contains_key(proposal_index) })); + // Break invariant 3 by adding another key to `Approvals` + let mut approvals_modified = Approvals::::get(); + approvals_modified.try_push(2).unwrap(); + Approvals::::put(approvals_modified); + // Invariant 3 should be violated + assert_eq!( + Treasury::do_try_state(), + Err(Other("Proposal indices in `Approvals` must also be contained in `Proposals`.")) + ); + }); +} + #[test] fn try_state_spends_invariant_1_works() { ExtBuilder::default().build().execute_with(|| { From 903b6201aefe2a9929d9b13b8898a0c902283a0c Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Tue, 26 Mar 2024 09:42:10 +0700 Subject: [PATCH 06/25] Code explicit indexes to event and error enum --- substrate/frame/treasury/src/lib.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 7bdd102878d25..30f44dc3b9327 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -343,24 +343,32 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { /// We have ended a spend period and will now allocate funds. + #[codec(index = 1)] Spending { budget_remaining: BalanceOf }, /// Some funds have been allocated. + #[codec(index = 2)] Awarded { proposal_index: ProposalIndex, award: BalanceOf, account: T::AccountId }, /// Some of our funds have been burnt. + #[codec(index = 4)] Burnt { burnt_funds: BalanceOf }, /// Spending has finished; this is the amount that rolls over until next spend. + #[codec(index = 5)] Rollover { rollover_balance: BalanceOf }, /// Some funds have been deposited. + #[codec(index = 6)] Deposit { value: BalanceOf }, /// A new spend proposal has been approved. + #[codec(index = 7)] SpendApproved { proposal_index: ProposalIndex, amount: BalanceOf, beneficiary: T::AccountId, }, /// The inactive funds of the pallet have been updated. + #[codec(index = 8)] UpdatedInactive { reactivated: BalanceOf, deactivated: BalanceOf }, /// A new asset spend proposal has been approved. + #[codec(index = 9)] AssetSpendApproved { index: SpendIndex, asset_kind: T::AssetKind, @@ -370,13 +378,17 @@ pub mod pallet { expire_at: BlockNumberFor, }, /// An approved spend was voided. + #[codec(index = 10)] AssetSpendVoided { index: SpendIndex }, /// A payment happened. + #[codec(index = 11)] Paid { index: SpendIndex, payment_id: ::Id }, /// A payment failed and can be retried. + #[codec(index = 12)] PaymentFailed { index: SpendIndex, payment_id: ::Id }, /// A spend was processed and removed from the storage. It might have been successfully /// paid or it may have expired. + #[codec(index = 13)] SpendProcessed { index: SpendIndex }, } @@ -384,27 +396,38 @@ pub mod pallet { #[pallet::error] pub enum Error { /// No proposal, bounty or spend at that index. + #[codec(index = 1)] InvalidIndex, /// Too many approvals in the queue. + #[codec(index = 2)] TooManyApprovals, /// The spend origin is valid but the amount it is allowed to spend is lower than the /// amount to be spent. + #[codec(index = 3)] InsufficientPermission, /// Proposal has not been approved. + #[codec(index = 4)] ProposalNotApproved, /// The balance of the asset kind is not convertible to the balance of the native asset. + #[codec(index = 5)] FailedToConvertBalance, /// The spend has expired and cannot be claimed. + #[codec(index = 6)] SpendExpired, /// The spend is not yet eligible for payout. + #[codec(index = 7)] EarlyPayout, /// The payment has already been attempted. + #[codec(index = 8)] AlreadyAttempted, /// There was some issue with the mechanism of payment. + #[codec(index = 9)] PayoutError, /// The payout was not yet attempted/claimed. + #[codec(index = 10)] NotAttempted, /// The payment has neither failed nor succeeded yet. + #[codec(index = 11)] Inconclusive, } From 2e8b334173ace4f8c666ffae1a53583efc4b3a91 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Tue, 26 Mar 2024 09:45:35 +0700 Subject: [PATCH 07/25] Hotfix codec indexes --- substrate/frame/treasury/src/lib.rs | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 30f44dc3b9327..9b5b5ded454dc 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -346,29 +346,23 @@ pub mod pallet { #[codec(index = 1)] Spending { budget_remaining: BalanceOf }, /// Some funds have been allocated. - #[codec(index = 2)] Awarded { proposal_index: ProposalIndex, award: BalanceOf, account: T::AccountId }, /// Some of our funds have been burnt. #[codec(index = 4)] Burnt { burnt_funds: BalanceOf }, /// Spending has finished; this is the amount that rolls over until next spend. - #[codec(index = 5)] Rollover { rollover_balance: BalanceOf }, /// Some funds have been deposited. - #[codec(index = 6)] Deposit { value: BalanceOf }, /// A new spend proposal has been approved. - #[codec(index = 7)] SpendApproved { proposal_index: ProposalIndex, amount: BalanceOf, beneficiary: T::AccountId, }, /// The inactive funds of the pallet have been updated. - #[codec(index = 8)] UpdatedInactive { reactivated: BalanceOf, deactivated: BalanceOf }, /// A new asset spend proposal has been approved. - #[codec(index = 9)] AssetSpendApproved { index: SpendIndex, asset_kind: T::AssetKind, @@ -378,17 +372,13 @@ pub mod pallet { expire_at: BlockNumberFor, }, /// An approved spend was voided. - #[codec(index = 10)] AssetSpendVoided { index: SpendIndex }, /// A payment happened. - #[codec(index = 11)] Paid { index: SpendIndex, payment_id: ::Id }, /// A payment failed and can be retried. - #[codec(index = 12)] PaymentFailed { index: SpendIndex, payment_id: ::Id }, /// A spend was processed and removed from the storage. It might have been successfully /// paid or it may have expired. - #[codec(index = 13)] SpendProcessed { index: SpendIndex }, } @@ -399,35 +389,25 @@ pub mod pallet { #[codec(index = 1)] InvalidIndex, /// Too many approvals in the queue. - #[codec(index = 2)] TooManyApprovals, /// The spend origin is valid but the amount it is allowed to spend is lower than the /// amount to be spent. - #[codec(index = 3)] InsufficientPermission, /// Proposal has not been approved. - #[codec(index = 4)] ProposalNotApproved, /// The balance of the asset kind is not convertible to the balance of the native asset. - #[codec(index = 5)] FailedToConvertBalance, /// The spend has expired and cannot be claimed. - #[codec(index = 6)] SpendExpired, /// The spend is not yet eligible for payout. - #[codec(index = 7)] EarlyPayout, /// The payment has already been attempted. - #[codec(index = 8)] AlreadyAttempted, /// There was some issue with the mechanism of payment. - #[codec(index = 9)] PayoutError, /// The payout was not yet attempted/claimed. - #[codec(index = 10)] NotAttempted, /// The payment has neither failed nor succeeded yet. - #[codec(index = 11)] Inconclusive, } From f9b82de9d042f51fc90b460796dd3173cbdec5c0 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Tue, 26 Mar 2024 22:46:16 +0700 Subject: [PATCH 08/25] Remove explicit coded indexes Discussed here: https://github.com/paritytech/polkadot-sdk/pull/3820#discussion_r1537354813 --- substrate/frame/treasury/src/lib.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 9b5b5ded454dc..7bdd102878d25 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -343,12 +343,10 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { /// We have ended a spend period and will now allocate funds. - #[codec(index = 1)] Spending { budget_remaining: BalanceOf }, /// Some funds have been allocated. Awarded { proposal_index: ProposalIndex, award: BalanceOf, account: T::AccountId }, /// Some of our funds have been burnt. - #[codec(index = 4)] Burnt { burnt_funds: BalanceOf }, /// Spending has finished; this is the amount that rolls over until next spend. Rollover { rollover_balance: BalanceOf }, @@ -386,7 +384,6 @@ pub mod pallet { #[pallet::error] pub enum Error { /// No proposal, bounty or spend at that index. - #[codec(index = 1)] InvalidIndex, /// Too many approvals in the queue. TooManyApprovals, From 8f74134b82df9a6df2824bbbe1555667223f1a83 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Wed, 27 Mar 2024 19:49:23 +0700 Subject: [PATCH 09/25] Remove deprecated weight functions --- substrate/frame/treasury/src/benchmarking.rs | 2 +- substrate/frame/treasury/src/weights.rs | 87 -------------------- 2 files changed, 1 insertion(+), 88 deletions(-) diff --git a/substrate/frame/treasury/src/benchmarking.rs b/substrate/frame/treasury/src/benchmarking.rs index f5fc4cdcab4c6..6272e76908408 100644 --- a/substrate/frame/treasury/src/benchmarking.rs +++ b/substrate/frame/treasury/src/benchmarking.rs @@ -59,7 +59,7 @@ where const SEED: u32 = 0; -// Create the pre-requisite information needed to create a treasury `propose_spend`. +// Create the pre-requisite information needed to create a treasury `spend_local`. fn setup_proposal, I: 'static>( u: u32, ) -> (T::AccountId, BalanceOf, AccountIdLookupOf) { diff --git a/substrate/frame/treasury/src/weights.rs b/substrate/frame/treasury/src/weights.rs index 030e18980eb54..d9f7f61096e28 100644 --- a/substrate/frame/treasury/src/weights.rs +++ b/substrate/frame/treasury/src/weights.rs @@ -48,9 +48,6 @@ use core::marker::PhantomData; /// Weight functions needed for pallet_treasury. pub trait WeightInfo { fn spend_local() -> Weight; - fn propose_spend() -> Weight; - fn reject_proposal() -> Weight; - fn approve_proposal(p: u32, ) -> Weight; fn remove_approval() -> Weight; fn on_initialize_proposals(p: u32, ) -> Weight; fn spend() -> Weight; @@ -77,48 +74,6 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } - /// Storage: Treasury ProposalCount (r:1 w:1) - /// Proof: Treasury ProposalCount (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - /// Storage: Treasury Proposals (r:0 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `177` - // Estimated: `1489` - // Minimum execution time: 349_000_000 picoseconds. - Weight::from_parts(398_000_000, 1489) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - /// Storage: Treasury Proposals (r:1 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `335` - // Estimated: `3593` - // Minimum execution time: 367_000_000 picoseconds. - Weight::from_parts(388_000_000, 3593) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - /// Storage: Treasury Proposals (r:1 w:0) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: Treasury Approvals (r:1 w:1) - /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `483 + p * (9 ±0)` - // Estimated: `3573` - // Minimum execution time: 111_000_000 picoseconds. - Weight::from_parts(108_813_243, 3573) - // Standard Error: 147_887 - .saturating_add(Weight::from_parts(683_216, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } /// Storage: Treasury Approvals (r:1 w:1) /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) fn remove_approval() -> Weight { @@ -228,48 +183,6 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } - /// Storage: Treasury ProposalCount (r:1 w:1) - /// Proof: Treasury ProposalCount (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - /// Storage: Treasury Proposals (r:0 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `177` - // Estimated: `1489` - // Minimum execution time: 349_000_000 picoseconds. - Weight::from_parts(398_000_000, 1489) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - /// Storage: Treasury Proposals (r:1 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `335` - // Estimated: `3593` - // Minimum execution time: 367_000_000 picoseconds. - Weight::from_parts(388_000_000, 3593) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - /// Storage: Treasury Proposals (r:1 w:0) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: Treasury Approvals (r:1 w:1) - /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `483 + p * (9 ±0)` - // Estimated: `3573` - // Minimum execution time: 111_000_000 picoseconds. - Weight::from_parts(108_813_243, 3573) - // Standard Error: 147_887 - .saturating_add(Weight::from_parts(683_216, 0).saturating_mul(p.into())) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } /// Storage: Treasury Approvals (r:1 w:1) /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) fn remove_approval() -> Weight { From 363270159414a78fd52a24fc8083abad3bc9371d Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 15 Apr 2024 19:55:33 +0700 Subject: [PATCH 10/25] Update prdoc message --- prdoc/{pr_3800.prdoc => pr_3820.prdoc} | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) rename prdoc/{pr_3800.prdoc => pr_3820.prdoc} (52%) diff --git a/prdoc/pr_3800.prdoc b/prdoc/pr_3820.prdoc similarity index 52% rename from prdoc/pr_3800.prdoc rename to prdoc/pr_3820.prdoc index 3396e8c21612d..49aed05a50feb 100644 --- a/prdoc/pr_3800.prdoc +++ b/prdoc/pr_3820.prdoc @@ -4,9 +4,12 @@ title: Remove deprecated calls from treasury pallet doc: - - audience: Runtime Dev + - audience: Runtime Dev, Runtime User description: | - This PR remove deprecated calls, relevant tests from `pallet-treasury` + This PR remove deprecated calls, relevant tests from `pallet-treasury`. + - Remove deprecated calls `propose_spend`, `reject_proposal`, `approve_proposal`. + - Replace the code flow of `propose_spend` then `approve_proposal` with `spend_local` + - Remove deprecated calls' related weight functions and test cases. crates: - name: pallet-treasury From c368de826ef1ba2d2d6595e80d5dd1da2b51223a Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Thu, 18 Apr 2024 00:41:40 +0700 Subject: [PATCH 11/25] Update deprecated treasury pallet code in the --- substrate/frame/bounties/src/lib.rs | 3 + substrate/frame/bounties/src/tests.rs | 190 ++------------------------ 2 files changed, 12 insertions(+), 181 deletions(-) diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index c099fc48b7a3b..257763f213fc3 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -245,6 +245,9 @@ pub mod pallet { /// The child bounty manager. type ChildBountyManager: ChildBountyManager>; + + /// Handler for the unbalanced decrease when slashing for a bounty. + type OnSlash: OnUnbalanced>; } #[pallet::error] diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index de747db537499..38708a142c33e 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -95,13 +95,8 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -122,13 +117,8 @@ impl pallet_treasury::Config for Test { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId2; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -155,6 +145,7 @@ parameter_types! { } impl Config for Test { + type OnSlash = (); type RuntimeEvent = RuntimeEvent; type BountyDepositBase = ConstU64<80>; type BountyDepositPayoutDelay = ConstU64<3>; @@ -170,6 +161,7 @@ impl Config for Test { } impl Config for Test { + type OnSlash = (); type RuntimeEvent = RuntimeEvent; type BountyDepositBase = ConstU64<80>; type BountyDepositPayoutDelay = ConstU64<3>; @@ -227,55 +219,13 @@ fn minting_works() { }); } -#[test] -fn spend_proposal_takes_min_deposit() { - new_test_ext().execute_with(|| { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_eq!(Balances::free_balance(0), 99); - assert_eq!(Balances::reserved_balance(0), 1); - }); -} - -#[test] -fn spend_proposal_takes_proportional_deposit() { - new_test_ext().execute_with(|| { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_eq!(Balances::free_balance(0), 95); - assert_eq!(Balances::reserved_balance(0), 5); - }); -} - -#[test] -fn spend_proposal_fails_when_proposer_poor() { - new_test_ext().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(2), 100, 3) - }, - TreasuryError::InsufficientProposersBalance, - ); - }); -} - #[test] fn accepted_spend_proposal_ignored_outside_spend_period() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) + Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); >::on_initialize(1); @@ -297,98 +247,6 @@ fn unused_pot_should_diminish() { }); } -#[test] -fn rejected_spend_proposal_ignored_on_spend_period() { - new_test_ext().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - - >::on_initialize(2); - assert_eq!(Balances::free_balance(3), 0); - assert_eq!(Treasury::pot(), 50); - }); -} - -#[test] -fn reject_already_rejected_spend_proposal_fails() { - new_test_ext().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - assert_noop!( - { - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }, - TreasuryError::InvalidIndex - ); - }); -} - -#[test] -fn reject_non_existent_spend_proposal_fails() { - new_test_ext().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }, - pallet_treasury::Error::::InvalidIndex - ); - }); -} - -#[test] -fn accept_non_existent_spend_proposal_fails() { - new_test_ext().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, - TreasuryError::InvalidIndex - ); - }); -} - -#[test] -fn accept_already_rejected_spend_proposal_fails() { - new_test_ext().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, - TreasuryError::InvalidIndex - ); - }); -} - #[test] fn accepted_spend_proposal_enacted_on_spend_period() { new_test_ext().execute_with(|| { @@ -396,12 +254,7 @@ fn accepted_spend_proposal_enacted_on_spend_period() { assert_eq!(Treasury::pot(), 100); assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) + Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); >::on_initialize(2); @@ -417,12 +270,7 @@ fn pot_underflow_should_not_diminish() { assert_eq!(Treasury::pot(), 100); assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 150, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) + Treasury::spend_local(RuntimeOrigin::root(), 150, 3) }); >::on_initialize(2); @@ -445,24 +293,14 @@ fn treasury_account_doesnt_get_deleted() { let treasury_balance = Balances::free_balance(&Treasury::account_id()); assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), treasury_balance, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) + Treasury::spend_local(RuntimeOrigin::root(), treasury_balance, 3) }); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), Treasury::pot(), 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 1) + Treasury::spend_local(RuntimeOrigin::root(), Treasury::pot(), 3) }); >::on_initialize(4); @@ -487,20 +325,10 @@ fn inexistent_account_works() { assert_eq!(Treasury::pot(), 0); // Pot is empty assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 99, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) + Treasury::spend_local(RuntimeOrigin::root(), 99, 3) }); assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 1) + Treasury::spend_local(RuntimeOrigin::root(), 1, 3) }); >::on_initialize(2); assert_eq!(Treasury::pot(), 0); // Pot hasn't changed From f42fd02746c4bda4e366d1c112709962fbb6fbd3 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Thu, 18 Apr 2024 00:52:45 +0700 Subject: [PATCH 12/25] Move ApproveOrigin from treasury to bounty config --- substrate/frame/bounties/src/lib.rs | 3 +++ substrate/frame/bounties/src/tests.rs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index 257763f213fc3..85759e855f8f0 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -246,6 +246,9 @@ pub mod pallet { /// The child bounty manager. type ChildBountyManager: ChildBountyManager>; + /// Origin from which approvals must come. + type ApproveOrigin: EnsureOrigin; + /// Handler for the unbalanced decrease when slashing for a bounty. type OnSlash: OnUnbalanced>; } diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index 38708a142c33e..2a887b8fd3926 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -146,6 +146,7 @@ parameter_types! { impl Config for Test { type OnSlash = (); + type ApproveOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type BountyDepositBase = ConstU64<80>; type BountyDepositPayoutDelay = ConstU64<3>; @@ -162,6 +163,7 @@ impl Config for Test { impl Config for Test { type OnSlash = (); + type ApproveOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type BountyDepositBase = ConstU64<80>; type BountyDepositPayoutDelay = ConstU64<3>; From ea5ba724bbcbd1e01e5d044c53b2f68b9204f17f Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Thu, 18 Apr 2024 01:11:15 +0700 Subject: [PATCH 13/25] Update child bounties and tip pallet --- substrate/frame/child-bounties/src/tests.rs | 7 ++----- substrate/frame/tips/src/lib.rs | 3 +++ substrate/frame/tips/src/tests.rs | 12 ++---------- 3 files changed, 7 insertions(+), 15 deletions(-) diff --git a/substrate/frame/child-bounties/src/tests.rs b/substrate/frame/child-bounties/src/tests.rs index 30601f821e438..6140bb99e6539 100644 --- a/substrate/frame/child-bounties/src/tests.rs +++ b/substrate/frame/child-bounties/src/tests.rs @@ -95,13 +95,8 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); @@ -126,6 +121,8 @@ parameter_types! { } impl pallet_bounties::Config for Test { + type ApproveOrigin = frame_system::EnsureRoot; + type OnSlash = (); type RuntimeEvent = RuntimeEvent; type BountyDepositBase = ConstU64<80>; type BountyDepositPayoutDelay = ConstU64<3>; diff --git a/substrate/frame/tips/src/lib.rs b/substrate/frame/tips/src/lib.rs index 8c360fb57d724..191e236b6d8e2 100644 --- a/substrate/frame/tips/src/lib.rs +++ b/substrate/frame/tips/src/lib.rs @@ -171,6 +171,9 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; + + /// Handler for the unbalanced decrease when slashing for a bounty. + type OnSlash: OnUnbalanced>; } /// TipsMap that are not yet completed. Keyed by the hash of `(reason, who)` from the value. diff --git a/substrate/frame/tips/src/tests.rs b/substrate/frame/tips/src/tests.rs index 78df3736815a1..24922dca6d403 100644 --- a/substrate/frame/tips/src/tests.rs +++ b/substrate/frame/tips/src/tests.rs @@ -116,13 +116,8 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -143,13 +138,8 @@ impl pallet_treasury::Config for Test { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId2; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -172,6 +162,7 @@ parameter_types! { pub static TipReportDepositBase: u64 = 1; } impl Config for Test { + type OnSlash = (); type MaximumReasonLength = ConstU32<16384>; type Tippers = TenToFourteen; type TipCountdown = ConstU64<1>; @@ -184,6 +175,7 @@ impl Config for Test { } impl Config for Test { + type OnSlash = (); type MaximumReasonLength = ConstU32<16384>; type Tippers = TenToFourteen; type TipCountdown = ConstU64<1>; From 4031443ff7328173972b16f96f926737b646277e Mon Sep 17 00:00:00 2001 From: Tin Chung <56880684+chungquantin@users.noreply.github.com> Date: Fri, 19 Apr 2024 00:00:51 +0700 Subject: [PATCH 14/25] Fix wording --- substrate/frame/tips/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/tips/src/lib.rs b/substrate/frame/tips/src/lib.rs index 191e236b6d8e2..ac8e4617a63d8 100644 --- a/substrate/frame/tips/src/lib.rs +++ b/substrate/frame/tips/src/lib.rs @@ -172,7 +172,7 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; - /// Handler for the unbalanced decrease when slashing for a bounty. + /// Handler for the unbalanced decrease when slashing for a tip. type OnSlash: OnUnbalanced>; } From fb2afc2f22e926b96d995e82ab97e8461c3700b4 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 20 May 2024 07:41:13 +0800 Subject: [PATCH 15/25] Revert the type parameter changes of treasury --- .../src/weights/pallet_treasury.rs | 37 --------------- .../rococo/src/weights/pallet_treasury.rs | 45 ------------------- .../westend/src/weights/pallet_treasury.rs | 45 ------------------- substrate/frame/bounties/src/lib.rs | 6 --- substrate/frame/bounties/src/tests.rs | 42 +++++++---------- substrate/frame/child-bounties/src/tests.rs | 7 ++- substrate/frame/tips/src/lib.rs | 3 -- substrate/frame/tips/src/tests.rs | 12 ++++- substrate/frame/treasury/src/lib.rs | 19 ++++++++ substrate/frame/treasury/src/tests.rs | 6 +++ 10 files changed, 57 insertions(+), 165 deletions(-) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs index 58540e646d8c3..5c513c3754ce8 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs @@ -62,43 +62,6 @@ impl pallet_treasury::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: `FellowshipTreasury::ProposalCount` (r:1 w:1) - /// Proof: `FellowshipTreasury::ProposalCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::Proposals` (r:0 w:1) - /// Proof: `FellowshipTreasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `143` - // Estimated: `1489` - // Minimum execution time: 264_000_000 picoseconds. - Weight::from_parts(277_000_000, 0) - .saturating_add(Weight::from_parts(0, 1489)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `FellowshipTreasury::Proposals` (r:1 w:1) - /// Proof: `FellowshipTreasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `301` - // Estimated: `3593` - // Minimum execution time: 289_000_000 picoseconds. - Weight::from_parts(312_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(_p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 0_000 picoseconds. - Weight::from_parts(0, 0) - .saturating_add(Weight::from_parts(0, 0)) - } /// Storage: `FellowshipTreasury::Approvals` (r:1 w:1) /// Proof: `FellowshipTreasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) fn remove_approval() -> Weight { diff --git a/polkadot/runtime/rococo/src/weights/pallet_treasury.rs b/polkadot/runtime/rococo/src/weights/pallet_treasury.rs index 144e9d5b87238..06246ada72f16 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_treasury.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_treasury.rs @@ -63,51 +63,6 @@ impl pallet_treasury::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: Treasury ProposalCount (r:1 w:1) - /// Proof: Treasury ProposalCount (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - /// Storage: Treasury Proposals (r:0 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `143` - // Estimated: `1489` - // Minimum execution time: 354_000_000 picoseconds. - Weight::from_parts(376_000_000, 0) - .saturating_add(Weight::from_parts(0, 1489)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Treasury Proposals (r:1 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `301` - // Estimated: `3593` - // Minimum execution time: 547_000_000 picoseconds. - Weight::from_parts(550_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Treasury Proposals (r:1 w:0) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: Treasury Approvals (r:1 w:1) - /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `470 + p * (8 ±0)` - // Estimated: `3573` - // Minimum execution time: 104_000_000 picoseconds. - Weight::from_parts(121_184_402, 0) - .saturating_add(Weight::from_parts(0, 3573)) - // Standard Error: 42_854 - .saturating_add(Weight::from_parts(153_112, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } /// Storage: Treasury Approvals (r:1 w:1) /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) fn remove_approval() -> Weight { diff --git a/polkadot/runtime/westend/src/weights/pallet_treasury.rs b/polkadot/runtime/westend/src/weights/pallet_treasury.rs index 144e9d5b87238..06246ada72f16 100644 --- a/polkadot/runtime/westend/src/weights/pallet_treasury.rs +++ b/polkadot/runtime/westend/src/weights/pallet_treasury.rs @@ -63,51 +63,6 @@ impl pallet_treasury::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: Treasury ProposalCount (r:1 w:1) - /// Proof: Treasury ProposalCount (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - /// Storage: Treasury Proposals (r:0 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `143` - // Estimated: `1489` - // Minimum execution time: 354_000_000 picoseconds. - Weight::from_parts(376_000_000, 0) - .saturating_add(Weight::from_parts(0, 1489)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Treasury Proposals (r:1 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `301` - // Estimated: `3593` - // Minimum execution time: 547_000_000 picoseconds. - Weight::from_parts(550_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Treasury Proposals (r:1 w:0) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: Treasury Approvals (r:1 w:1) - /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `470 + p * (8 ±0)` - // Estimated: `3573` - // Minimum execution time: 104_000_000 picoseconds. - Weight::from_parts(121_184_402, 0) - .saturating_add(Weight::from_parts(0, 3573)) - // Standard Error: 42_854 - .saturating_add(Weight::from_parts(153_112, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } /// Storage: Treasury Approvals (r:1 w:1) /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) fn remove_approval() -> Weight { diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index 85759e855f8f0..c099fc48b7a3b 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -245,12 +245,6 @@ pub mod pallet { /// The child bounty manager. type ChildBountyManager: ChildBountyManager>; - - /// Origin from which approvals must come. - type ApproveOrigin: EnsureOrigin; - - /// Handler for the unbalanced decrease when slashing for a bounty. - type OnSlash: OnUnbalanced>; } #[pallet::error] diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index 2a887b8fd3926..18e4695bd9c0b 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -95,8 +95,13 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; + type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; + type OnSlash = (); + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ConstU64<1>; + type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -117,8 +122,13 @@ impl pallet_treasury::Config for Test { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId2; type Currency = pallet_balances::Pallet; + type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; + type OnSlash = (); + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ConstU64<1>; + type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -145,8 +155,6 @@ parameter_types! { } impl Config for Test { - type OnSlash = (); - type ApproveOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type BountyDepositBase = ConstU64<80>; type BountyDepositPayoutDelay = ConstU64<3>; @@ -162,8 +170,6 @@ impl Config for Test { } impl Config for Test { - type OnSlash = (); - type ApproveOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type BountyDepositBase = ConstU64<80>; type BountyDepositPayoutDelay = ConstU64<3>; @@ -226,9 +232,7 @@ fn accepted_spend_proposal_ignored_outside_spend_period() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!({ - Treasury::spend_local(RuntimeOrigin::root(), 100, 3) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); >::on_initialize(1); assert_eq!(Balances::free_balance(3), 0); @@ -255,9 +259,7 @@ fn accepted_spend_proposal_enacted_on_spend_period() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!({ - Treasury::spend_local(RuntimeOrigin::root(), 100, 3) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); >::on_initialize(2); assert_eq!(Balances::free_balance(3), 100); @@ -271,9 +273,7 @@ fn pot_underflow_should_not_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!({ - Treasury::spend_local(RuntimeOrigin::root(), 150, 3) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 150, 3) }); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed @@ -294,16 +294,12 @@ fn treasury_account_doesnt_get_deleted() { assert_eq!(Treasury::pot(), 100); let treasury_balance = Balances::free_balance(&Treasury::account_id()); - assert_ok!({ - Treasury::spend_local(RuntimeOrigin::root(), treasury_balance, 3) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), treasury_balance, 3) }); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed - assert_ok!({ - Treasury::spend_local(RuntimeOrigin::root(), Treasury::pot(), 3) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), Treasury::pot(), 3) }); >::on_initialize(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied @@ -326,12 +322,8 @@ fn inexistent_account_works() { assert_eq!(Balances::free_balance(Treasury::account_id()), 0); // Account does not exist assert_eq!(Treasury::pot(), 0); // Pot is empty - assert_ok!({ - Treasury::spend_local(RuntimeOrigin::root(), 99, 3) - }); - assert_ok!({ - Treasury::spend_local(RuntimeOrigin::root(), 1, 3) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 99, 3) }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 1, 3) }); >::on_initialize(2); assert_eq!(Treasury::pot(), 0); // Pot hasn't changed assert_eq!(Balances::free_balance(3), 0); // Balance of `3` hasn't changed diff --git a/substrate/frame/child-bounties/src/tests.rs b/substrate/frame/child-bounties/src/tests.rs index 6140bb99e6539..30601f821e438 100644 --- a/substrate/frame/child-bounties/src/tests.rs +++ b/substrate/frame/child-bounties/src/tests.rs @@ -95,8 +95,13 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; + type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; + type OnSlash = (); + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ConstU64<1>; + type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); @@ -121,8 +126,6 @@ parameter_types! { } impl pallet_bounties::Config for Test { - type ApproveOrigin = frame_system::EnsureRoot; - type OnSlash = (); type RuntimeEvent = RuntimeEvent; type BountyDepositBase = ConstU64<80>; type BountyDepositPayoutDelay = ConstU64<3>; diff --git a/substrate/frame/tips/src/lib.rs b/substrate/frame/tips/src/lib.rs index ac8e4617a63d8..8c360fb57d724 100644 --- a/substrate/frame/tips/src/lib.rs +++ b/substrate/frame/tips/src/lib.rs @@ -171,9 +171,6 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; - - /// Handler for the unbalanced decrease when slashing for a tip. - type OnSlash: OnUnbalanced>; } /// TipsMap that are not yet completed. Keyed by the hash of `(reason, who)` from the value. diff --git a/substrate/frame/tips/src/tests.rs b/substrate/frame/tips/src/tests.rs index 24922dca6d403..78df3736815a1 100644 --- a/substrate/frame/tips/src/tests.rs +++ b/substrate/frame/tips/src/tests.rs @@ -116,8 +116,13 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; + type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; + type OnSlash = (); + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ConstU64<1>; + type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -138,8 +143,13 @@ impl pallet_treasury::Config for Test { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId2; type Currency = pallet_balances::Pallet; + type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; + type OnSlash = (); + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ConstU64<1>; + type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -162,7 +172,6 @@ parameter_types! { pub static TipReportDepositBase: u64 = 1; } impl Config for Test { - type OnSlash = (); type MaximumReasonLength = ConstU32<16384>; type Tippers = TenToFourteen; type TipCountdown = ConstU64<1>; @@ -175,7 +184,6 @@ impl Config for Test { } impl Config for Test { - type OnSlash = (); type MaximumReasonLength = ConstU32<16384>; type Tippers = TenToFourteen; type TipCountdown = ConstU64<1>; diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 0086031d91222..beca935c4c1d7 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -205,6 +205,9 @@ pub mod pallet { /// The staking balance. type Currency: Currency + ReservableCurrency; + /// Origin from which approvals must come. + type ApproveOrigin: EnsureOrigin; + /// Origin from which rejections must come. type RejectOrigin: EnsureOrigin; @@ -212,6 +215,22 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; + /// Handler for the unbalanced decrease when slashing for a rejected proposal or bounty. + type OnSlash: OnUnbalanced>; + + /// Fraction of a proposal's value that should be bonded in order to place the proposal. + /// An accepted proposal gets these back. A rejected proposal does not. + #[pallet::constant] + type ProposalBond: Get; + + /// Minimum amount of funds that should be placed in a deposit for making a proposal. + #[pallet::constant] + type ProposalBondMinimum: Get>; + + /// Maximum amount of funds that should be placed in a deposit for making a proposal. + #[pallet::constant] + type ProposalBondMaximum: Get>>; + /// Period between successive spends. #[pallet::constant] type SpendPeriod: Get>; diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 1c96bc7eeb8f2..972f76bda2768 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -136,6 +136,7 @@ impl Pay for TestPay { } parameter_types! { + pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub TreasuryAccount: u128 = Treasury::account_id(); @@ -174,8 +175,13 @@ impl> ConversionFromAssetBalance for MulBy { impl Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; + type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; + type OnSlash = (); + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ConstU64<1>; + type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. From 39957953df9a16fbd8fbf367653928027ddb49e8 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 27 May 2024 09:26:27 +0800 Subject: [PATCH 16/25] Remove ProposalBond related parameters --- .../collectives-westend/src/fellowship/mod.rs | 66 +++------ polkadot/runtime/common/src/impls.rs | 3 - polkadot/runtime/rococo/src/lib.rs | 44 +++--- polkadot/runtime/westend/src/lib.rs | 54 ++++---- substrate/bin/node/runtime/src/lib.rs | 52 ++++---- substrate/frame/bounties/src/tests.rs | 26 ++-- substrate/frame/child-bounties/src/tests.rs | 4 - substrate/frame/tips/src/tests.rs | 7 - substrate/frame/treasury/src/lib.rs | 125 +++++------------- substrate/frame/treasury/src/tests.rs | 16 +-- 10 files changed, 141 insertions(+), 256 deletions(-) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs index 6a4a182079671..8467224bb6410 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs @@ -84,19 +84,20 @@ impl pallet_referenda::Config for Runtime { type Scheduler = Scheduler; type Currency = Balances; // Fellows can submit proposals. - type SubmitOrigin = EitherOf< - pallet_ranked_collective::EnsureMember, - MapSuccess< - TryWithMorphedArg< - RuntimeOrigin, - ::PalletsOrigin, - ToVoice, - EnsureOfRank, - (AccountId, u16), + type SubmitOrigin = + EitherOf< + pallet_ranked_collective::EnsureMember, + MapSuccess< + TryWithMorphedArg< + RuntimeOrigin, + ::PalletsOrigin, + ToVoice, + EnsureOfRank, + (AccountId, u16), + >, + TakeFirst, >, - TakeFirst, - >, - >; + >; type CancelOrigin = Architects; type KillOrigin = Masters; type Slash = ToParentTreasury; @@ -270,16 +271,6 @@ parameter_types! { pub SelfParaId: ParaId = ParachainInfo::parachain_id(); } -#[cfg(feature = "runtime-benchmarks")] -parameter_types! { - // Benchmark bond. Needed to make `propose_spend` work. - pub const TenPercent: Permill = Permill::from_percent(10); - // Benchmark minimum. Needed to make `propose_spend` work. - pub const BenchmarkProposalBondMinimum: Balance = 1 * DOLLARS; - // Benchmark maximum. Needed to make `propose_spend` work. - pub const BenchmarkProposalBondMaximum: Balance = 10 * DOLLARS; -} - /// [`PayOverXcm`] setup to pay the Fellowship Treasury. pub type FellowshipTreasuryPaymaster = PayOverXcm< FellowshipTreasuryInteriorLocation, @@ -302,20 +293,6 @@ impl pallet_treasury::Config for Runtime { // TODO: replace with `NeverEnsure` once polkadot-sdk 1.5 is released. type ApproveOrigin = NeverEnsureOrigin<()>; type OnSlash = (); - #[cfg(not(feature = "runtime-benchmarks"))] - type ProposalBond = HundredPercent; - #[cfg(not(feature = "runtime-benchmarks"))] - type ProposalBondMinimum = MaxBalance; - #[cfg(not(feature = "runtime-benchmarks"))] - type ProposalBondMaximum = MaxBalance; - - #[cfg(feature = "runtime-benchmarks")] - type ProposalBond = TenPercent; - #[cfg(feature = "runtime-benchmarks")] - type ProposalBondMinimum = BenchmarkProposalBondMinimum; - #[cfg(feature = "runtime-benchmarks")] - type ProposalBondMaximum = BenchmarkProposalBondMaximum; - // end. type WeightInfo = weights::pallet_treasury::WeightInfo; type PalletId = FellowshipTreasuryPalletId; @@ -350,15 +327,16 @@ impl pallet_treasury::Config for Runtime { type Paymaster = FellowshipTreasuryPaymaster; #[cfg(feature = "runtime-benchmarks")] type Paymaster = PayWithEnsure>>; - type BalanceConverter = UnityOrOuterConversion< - ContainsParts< - FromContains< - xcm_builder::IsSiblingSystemParachain, - xcm_builder::IsParentsOnly>, + type BalanceConverter = + UnityOrOuterConversion< + ContainsParts< + FromContains< + xcm_builder::IsSiblingSystemParachain, + xcm_builder::IsParentsOnly>, + >, >, - >, - AssetRate, - >; + AssetRate, + >; type PayoutPeriod = ConstU32<{ 30 * DAYS }>; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments< diff --git a/polkadot/runtime/common/src/impls.rs b/polkadot/runtime/common/src/impls.rs index 85531e9c04fc4..34e0f5ed05837 100644 --- a/polkadot/runtime/common/src/impls.rs +++ b/polkadot/runtime/common/src/impls.rs @@ -345,9 +345,6 @@ mod tests { type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = (); - type ProposalBondMinimum = (); - type ProposalBondMaximum = (); type SpendPeriod = (); type Burn = (); type BurnDestination = (); diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index c22d5c39b2330..1db4a137c2ca1 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -334,16 +334,17 @@ impl pallet_preimage::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type ManagerOrigin = EnsureRoot; - type Consideration = HoldConsideration< - AccountId, - Balances, - PreimageHoldReason, - LinearStoragePrice< - dynamic_params::preimage::BaseDeposit, - dynamic_params::preimage::ByteDeposit, - Balance, - >, - >; + type Consideration = + HoldConsideration< + AccountId, + Balances, + PreimageHoldReason, + LinearStoragePrice< + dynamic_params::preimage::BaseDeposit, + dynamic_params::preimage::ByteDeposit, + Balance, + >, + >; } parameter_types! { @@ -479,9 +480,6 @@ parameter_types! { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); - pub const ProposalBondMinimum: Balance = 2000 * CENTS; - pub const ProposalBondMaximum: Balance = 1 * GRAND; pub const SpendPeriod: BlockNumber = 6 * DAYS; pub const Burn: Permill = Permill::from_perthousand(2); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); @@ -508,9 +506,6 @@ impl pallet_treasury::Config for Runtime { type RejectOrigin = EitherOfDiverse, Treasurer>; type RuntimeEvent = RuntimeEvent; type OnSlash = Treasury; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; type SpendPeriod = SpendPeriod; type Burn = Burn; type BurnDestination = Society; @@ -644,11 +639,12 @@ where frame_system::CheckWeight::::new(), pallet_transaction_payment::ChargeTransactionPayment::::from(tip), ); - let raw_payload = SignedPayload::new(call, extra) - .map_err(|e| { - log::warn!("Unable to create signed payload: {:?}", e); - }) - .ok()?; + let raw_payload = + SignedPayload::new(call, extra) + .map_err(|e| { + log::warn!("Unable to create signed payload: {:?}", e); + }) + .ok()?; let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?; let (call, extra, _) = raw_payload.deconstruct(); let address = ::Lookup::unlookup(account); @@ -1304,9 +1300,9 @@ impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() .into_iter() - .filter_map(|id| { - parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) - }) + .filter_map( + |id| parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) + ) .collect(); para_heads.sort(); binary_merkle_tree::merkle_root::( diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index b62c6d08201c4..b161526a6ccdd 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -153,16 +153,17 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); /// Runtime version (Westend). #[sp_version::runtime_version] -pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("westend"), - impl_name: create_runtime_str!("parity-westend"), - authoring_version: 2, - spec_version: 1_011_000, - impl_version: 0, - apis: RUNTIME_API_VERSIONS, - transaction_version: 25, - state_version: 1, -}; +pub const VERSION: RuntimeVersion = + RuntimeVersion { + spec_name: create_runtime_str!("westend"), + impl_name: create_runtime_str!("parity-westend"), + authoring_version: 2, + spec_version: 1_011_000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, + transaction_version: 25, + state_version: 1, + }; /// The BABE epoch configuration at genesis. pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration = @@ -362,9 +363,9 @@ impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() .into_iter() - .filter_map(|id| { - parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) - }) + .filter_map( + |id| parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) + ) .collect(); para_heads.sort_by_key(|k| k.0); binary_merkle_tree::merkle_root::( @@ -561,12 +562,10 @@ impl pallet_election_provider_multi_phase::Config for Runtime { #[cfg(any(feature = "fast-runtime", feature = "runtime-benchmarks"))] type Fallback = onchain::OnChainExecution; #[cfg(not(any(feature = "fast-runtime", feature = "runtime-benchmarks")))] - type Fallback = frame_election_provider_support::NoElection<( - AccountId, - BlockNumber, - Staking, - MaxActiveValidators, - )>; + type Fallback = + frame_election_provider_support::NoElection< + (AccountId, BlockNumber, Staking, MaxActiveValidators) + >; type GovernanceFallback = onchain::OnChainExecution; type Solver = SequentialPhragmen< AccountId, @@ -664,9 +663,6 @@ impl pallet_fast_unstake::Config for Runtime { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); - pub const ProposalBondMinimum: Balance = 2000 * CENTS; - pub const ProposalBondMaximum: Balance = 1 * GRAND; pub const SpendPeriod: BlockNumber = 6 * DAYS; pub const Burn: Permill = Permill::from_perthousand(2); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); @@ -693,9 +689,6 @@ impl pallet_treasury::Config for Runtime { type RejectOrigin = EitherOfDiverse, Treasurer>; type RuntimeEvent = RuntimeEvent; type OnSlash = Treasury; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; type SpendPeriod = SpendPeriod; type Burn = Burn; type BurnDestination = (); @@ -798,11 +791,12 @@ where frame_system::CheckWeight::::new(), pallet_transaction_payment::ChargeTransactionPayment::::from(tip), ); - let raw_payload = SignedPayload::new(call, extra) - .map_err(|e| { - log::warn!("Unable to create signed payload: {:?}", e); - }) - .ok()?; + let raw_payload = + SignedPayload::new(call, extra) + .map_err(|e| { + log::warn!("Unable to create signed payload: {:?}", e); + }) + .ok()?; let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?; let (call, extra, _) = raw_payload.deconstruct(); let address = ::Lookup::unlookup(account); diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index b1f948afa561f..2192210158bdf 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -472,16 +472,17 @@ impl pallet_preimage::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type ManagerOrigin = EnsureRoot; - type Consideration = HoldConsideration< - AccountId, - Balances, - PreimageHoldReason, - LinearStoragePrice< - dynamic_params::storage::BaseDeposit, - dynamic_params::storage::ByteDeposit, - Balance, - >, - >; + type Consideration = + HoldConsideration< + AccountId, + Balances, + PreimageHoldReason, + LinearStoragePrice< + dynamic_params::storage::BaseDeposit, + dynamic_params::storage::ByteDeposit, + Balance, + >, + >; } parameter_types! { @@ -1210,8 +1211,6 @@ impl pallet_membership::Config for Runtime { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); - pub const ProposalBondMinimum: Balance = 1 * DOLLARS; pub const SpendPeriod: BlockNumber = 1 * DAYS; pub const Burn: Permill = Permill::from_percent(50); pub const TipCountdown: BlockNumber = 1 * DAYS; @@ -1238,9 +1237,6 @@ impl pallet_treasury::Config for Runtime { >; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = (); type SpendPeriod = SpendPeriod; type Burn = Burn; type BurnDestination = (); @@ -1438,11 +1434,12 @@ where ), ), ); - let raw_payload = SignedPayload::new(call, extra) - .map_err(|e| { - log::warn!("Unable to create signed payload: {:?}", e); - }) - .ok()?; + let raw_payload = + SignedPayload::new(call, extra) + .map_err(|e| { + log::warn!("Unable to create signed payload: {:?}", e); + }) + .ok()?; let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?; let address = Indices::unlookup(account); let (call, extra, _) = raw_payload.deconstruct(); @@ -1799,13 +1796,14 @@ impl pallet_nis::BenchmarkSetup for SetupAsset { fn create_counterpart_asset() { let owner = AccountId::from([0u8; 32]); // this may or may not fail depending on if the chain spec or runtime genesis is used. - let _ = Assets::force_create( - RuntimeOrigin::root(), - 9u32.into(), - sp_runtime::MultiAddress::Id(owner), - true, - 1, - ); + let _ = + Assets::force_create( + RuntimeOrigin::root(), + 9u32.into(), + sp_runtime::MultiAddress::Id(owner), + true, + 1, + ); } } diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index d977ce48250fc..6afaddba98b44 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -82,7 +82,6 @@ impl pallet_balances::Config for Test { type RuntimeFreezeReason = (); } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub static Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub const TreasuryPalletId2: PalletId = PalletId(*b"py/trsr2"); @@ -99,9 +98,6 @@ impl pallet_treasury::Config for Test { type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -126,9 +122,6 @@ impl pallet_treasury::Config for Test { type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -944,15 +937,16 @@ fn test_migration_v4() { status: BountyStatus::::Proposed, }; - let data = vec![ - (pallet_bounties::BountyCount::::hashed_key().to_vec(), 10.encode().to_vec()), - (pallet_bounties::Bounties::::hashed_key_for(index), bounty.encode().to_vec()), - (pallet_bounties::BountyDescriptions::::hashed_key_for(index), vec![0, 0]), - ( - pallet_bounties::BountyApprovals::::hashed_key().to_vec(), - vec![10 as u32].encode().to_vec(), - ), - ]; + let data = + vec![ + (pallet_bounties::BountyCount::::hashed_key().to_vec(), 10.encode().to_vec()), + (pallet_bounties::Bounties::::hashed_key_for(index), bounty.encode().to_vec()), + (pallet_bounties::BountyDescriptions::::hashed_key_for(index), vec![0, 0]), + ( + pallet_bounties::BountyApprovals::::hashed_key().to_vec(), + vec![10 as u32].encode().to_vec(), + ), + ]; s.top = data.into_iter().collect(); diff --git a/substrate/frame/child-bounties/src/tests.rs b/substrate/frame/child-bounties/src/tests.rs index d9405d3d28977..800709ce2ec65 100644 --- a/substrate/frame/child-bounties/src/tests.rs +++ b/substrate/frame/child-bounties/src/tests.rs @@ -85,7 +85,6 @@ impl pallet_balances::Config for Test { type RuntimeFreezeReason = (); } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub TreasuryAccount: u128 = Treasury::account_id(); @@ -99,9 +98,6 @@ impl pallet_treasury::Config for Test { type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); diff --git a/substrate/frame/tips/src/tests.rs b/substrate/frame/tips/src/tests.rs index 78df3736815a1..364bb8b230864 100644 --- a/substrate/frame/tips/src/tests.rs +++ b/substrate/frame/tips/src/tests.rs @@ -105,7 +105,6 @@ impl ContainsLengthBound for TenToFourteen { } } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub const TreasuryPalletId2: PalletId = PalletId(*b"py/trsr2"); @@ -120,9 +119,6 @@ impl pallet_treasury::Config for Test { type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -147,9 +143,6 @@ impl pallet_treasury::Config for Test { type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index beca935c4c1d7..4151d5ece72a3 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -218,19 +218,6 @@ pub mod pallet { /// Handler for the unbalanced decrease when slashing for a rejected proposal or bounty. type OnSlash: OnUnbalanced>; - /// Fraction of a proposal's value that should be bonded in order to place the proposal. - /// An accepted proposal gets these back. A rejected proposal does not. - #[pallet::constant] - type ProposalBond: Get; - - /// Minimum amount of funds that should be placed in a deposit for making a proposal. - #[pallet::constant] - type ProposalBondMinimum: Get>; - - /// Maximum amount of funds that should be placed in a deposit for making a proposal. - #[pallet::constant] - type ProposalBondMaximum: Get>>; - /// Period between successive spends. #[pallet::constant] type SpendPeriod: Get>; @@ -440,10 +427,9 @@ pub mod pallet { T::Currency::reactivate(deactivated); T::Currency::deactivate(pot); Deactivated::::put(&pot); - Self::deposit_event(Event::::UpdatedInactive { - reactivated: deactivated, - deactivated: pot, - }); + Self::deposit_event( + Event::::UpdatedInactive { reactivated: deactivated, deactivated: pot } + ); } // Check to see if we should spend some funds! @@ -535,26 +521,6 @@ pub mod pallet { } /// Force a previously approved proposal to be removed from the approval queue. - /// - /// ## Dispatch Origin - /// - /// Must be [`Config::RejectOrigin`]. - /// - /// ## Details - /// - /// The original deposit will no longer be returned. - /// - /// ### Parameters - /// - `proposal_id`: The index of a proposal - /// - /// ### Complexity - /// - O(A) where `A` is the number of approvals - /// - /// ### Errors - /// - [`Error::ProposalNotApproved`]: The `proposal_id` supplied was not found in the - /// approval queue, i.e., the proposal has not been approved. This could also mean the - /// proposal does not exist altogether, thus there is no way it would have been approved - /// in the first place. #[pallet::call_index(4)] #[pallet::weight((T::WeightInfo::remove_approval(), DispatchClass::Operational))] pub fn remove_approval( @@ -670,22 +636,6 @@ pub mod pallet { /// Claim a spend. /// /// ## Dispatch Origin - /// - /// Must be signed. - /// - /// ## Details - /// - /// Spends must be claimed within some temporal bounds. A spend may be claimed within one - /// [`Config::PayoutPeriod`] from the `valid_from` block. - /// In case of a payout failure, the spend status must be updated with the `check_status` - /// dispatchable before retrying with the current function. - /// - /// ### Parameters - /// - `index`: The spend index. - /// - /// ## Events - /// - /// Emits [`Event::Paid`] if successful. #[pallet::call_index(6)] #[pallet::weight(T::WeightInfo::payout())] pub fn payout(origin: OriginFor, index: SpendIndex) -> DispatchResult { @@ -804,9 +754,6 @@ impl, I: 'static> Pallet { // Add public immutables and private mutables. /// The account ID of the treasury pot. - /// - /// This actually does computation. If you need to keep using it, then make sure you cache the - /// value and only call this once. pub fn account_id() -> T::AccountId { T::PalletId::get().into_account_truncating() } @@ -821,38 +768,40 @@ impl, I: 'static> Pallet { let mut missed_any = false; let mut imbalance = >::zero(); - let proposals_len = Approvals::::mutate(|v| { - let proposals_approvals_len = v.len() as u32; - v.retain(|&index| { - // Should always be true, but shouldn't panic if false or we're screwed. - if let Some(p) = Self::proposals(index) { - if p.value <= budget_remaining { - budget_remaining -= p.value; - >::remove(index); - - // return their deposit. - let err_amount = T::Currency::unreserve(&p.proposer, p.bond); - debug_assert!(err_amount.is_zero()); - - // provide the allocation. - imbalance.subsume(T::Currency::deposit_creating(&p.beneficiary, p.value)); - - Self::deposit_event(Event::Awarded { - proposal_index: index, - award: p.value, - account: p.beneficiary, - }); - false + let proposals_len = + Approvals::::mutate(|v| { + let proposals_approvals_len = v.len() as u32; + v.retain(|&index| { + // Should always be true, but shouldn't panic if false or we're screwed. + if let Some(p) = Self::proposals(index) { + if p.value <= budget_remaining { + budget_remaining -= p.value; + >::remove(index); + + // return their deposit. + let err_amount = T::Currency::unreserve(&p.proposer, p.bond); + debug_assert!(err_amount.is_zero()); + + // provide the allocation. + imbalance + .subsume(T::Currency::deposit_creating(&p.beneficiary, p.value)); + + Self::deposit_event(Event::Awarded { + proposal_index: index, + award: p.value, + account: p.beneficiary, + }); + false + } else { + missed_any = true; + true + } } else { - missed_any = true; - true + false } - } else { - false - } + }); + proposals_approvals_len }); - proposals_approvals_len - }); total_weight += T::WeightInfo::on_initialize_proposals(proposals_len); @@ -946,12 +895,6 @@ impl, I: 'static> Pallet { } /// ## Invariants of spend storage items - /// - /// 1. [`SpendCount`] >= Number of elements in [`Spends`]. - /// 2. Each entry in [`Spends`] should be saved under a key strictly less than current - /// [`SpendCount`]. - /// 3. For each spend entry contained in [`Spends`] we should have spend.expire_at - /// > spend.valid_from. #[cfg(any(feature = "try-runtime", test))] fn try_state_spends() -> Result<(), sp_runtime::TryRuntimeError> { let current_spend_count = SpendCount::::get(); diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 972f76bda2768..8dc2b4a80e2df 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -136,7 +136,6 @@ impl Pay for TestPay { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub TreasuryAccount: u128 = Treasury::account_id(); @@ -179,9 +178,6 @@ impl Config for Test { type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -862,9 +858,9 @@ fn try_state_spends_invariant_1_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; // Propose and approve a spend - assert_ok!({ - Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 1, Box::new(6), None) - }); + assert_ok!( + { Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 1, Box::new(6), None) } + ); assert_eq!(Spends::::iter().count(), 1); assert_eq!(SpendCount::::get(), 1); // Check invariant 1 holds @@ -913,9 +909,9 @@ fn try_state_spends_invariant_3_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; // Propose and approve a spend - assert_ok!({ - Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 1, Box::new(6), None) - }); + assert_ok!( + { Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 1, Box::new(6), None) } + ); assert_eq!(Spends::::iter().count(), 1); let current_spend_count = SpendCount::::get(); assert_eq!(current_spend_count, 1); From f692eaf109484828c920d6b6e4550001d9c8de5e Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 27 May 2024 10:18:32 +0800 Subject: [PATCH 17/25] Reformat --- .../collectives-westend/src/fellowship/mod.rs | 42 ++++++------ polkadot/runtime/rococo/src/lib.rs | 27 ++++---- polkadot/runtime/westend/src/lib.rs | 27 ++++---- substrate/bin/node/runtime/src/lib.rs | 47 ++++++------- substrate/frame/bounties/src/tests.rs | 19 +++--- substrate/frame/treasury/src/lib.rs | 67 +++++++++---------- substrate/frame/treasury/src/tests.rs | 12 ++-- 7 files changed, 117 insertions(+), 124 deletions(-) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs index 8467224bb6410..7592bca566015 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs @@ -84,20 +84,19 @@ impl pallet_referenda::Config for Runtime { type Scheduler = Scheduler; type Currency = Balances; // Fellows can submit proposals. - type SubmitOrigin = - EitherOf< - pallet_ranked_collective::EnsureMember, - MapSuccess< - TryWithMorphedArg< - RuntimeOrigin, - ::PalletsOrigin, - ToVoice, - EnsureOfRank, - (AccountId, u16), - >, - TakeFirst, + type SubmitOrigin = EitherOf< + pallet_ranked_collective::EnsureMember, + MapSuccess< + TryWithMorphedArg< + RuntimeOrigin, + ::PalletsOrigin, + ToVoice, + EnsureOfRank, + (AccountId, u16), >, - >; + TakeFirst, + >, + >; type CancelOrigin = Architects; type KillOrigin = Masters; type Slash = ToParentTreasury; @@ -327,16 +326,15 @@ impl pallet_treasury::Config for Runtime { type Paymaster = FellowshipTreasuryPaymaster; #[cfg(feature = "runtime-benchmarks")] type Paymaster = PayWithEnsure>>; - type BalanceConverter = - UnityOrOuterConversion< - ContainsParts< - FromContains< - xcm_builder::IsSiblingSystemParachain, - xcm_builder::IsParentsOnly>, - >, + type BalanceConverter = UnityOrOuterConversion< + ContainsParts< + FromContains< + xcm_builder::IsSiblingSystemParachain, + xcm_builder::IsParentsOnly>, >, - AssetRate, - >; + >, + AssetRate, + >; type PayoutPeriod = ConstU32<{ 30 * DAYS }>; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments< diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 4ef72a68f51c4..a4c918a0d6ffa 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -334,17 +334,16 @@ impl pallet_preimage::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type ManagerOrigin = EnsureRoot; - type Consideration = - HoldConsideration< - AccountId, - Balances, - PreimageHoldReason, - LinearStoragePrice< - dynamic_params::preimage::BaseDeposit, - dynamic_params::preimage::ByteDeposit, - Balance, - >, - >; + type Consideration = HoldConsideration< + AccountId, + Balances, + PreimageHoldReason, + LinearStoragePrice< + dynamic_params::preimage::BaseDeposit, + dynamic_params::preimage::ByteDeposit, + Balance, + >, + >; } parameter_types! { @@ -1301,9 +1300,9 @@ impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() .into_iter() - .filter_map( - |id| parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) - ) + .filter_map(|id| { + parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) + }) .collect(); para_heads.sort(); binary_merkle_tree::merkle_root::( diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index b8d54ff0daea2..fda87ecea33b8 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -362,9 +362,9 @@ impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() .into_iter() - .filter_map( - |id| parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) - ) + .filter_map(|id| { + parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) + }) .collect(); para_heads.sort_by_key(|k| k.0); binary_merkle_tree::merkle_root::( @@ -561,10 +561,12 @@ impl pallet_election_provider_multi_phase::Config for Runtime { #[cfg(any(feature = "fast-runtime", feature = "runtime-benchmarks"))] type Fallback = onchain::OnChainExecution; #[cfg(not(any(feature = "fast-runtime", feature = "runtime-benchmarks")))] - type Fallback = - frame_election_provider_support::NoElection< - (AccountId, BlockNumber, Staking, MaxActiveValidators) - >; + type Fallback = frame_election_provider_support::NoElection<( + AccountId, + BlockNumber, + Staking, + MaxActiveValidators, + )>; type GovernanceFallback = onchain::OnChainExecution; type Solver = SequentialPhragmen< AccountId, @@ -791,12 +793,11 @@ where pallet_transaction_payment::ChargeTransactionPayment::::from(tip), frame_metadata_hash_extension::CheckMetadataHash::::new(true), ); - let raw_payload = - SignedPayload::new(call, extra) - .map_err(|e| { - log::warn!("Unable to create signed payload: {:?}", e); - }) - .ok()?; + let raw_payload = SignedPayload::new(call, extra) + .map_err(|e| { + log::warn!("Unable to create signed payload: {:?}", e); + }) + .ok()?; let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?; let (call, extra, _) = raw_payload.deconstruct(); let address = ::Lookup::unlookup(account); diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 1be6c5a16d9aa..12c9803a1a453 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -474,17 +474,16 @@ impl pallet_preimage::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type ManagerOrigin = EnsureRoot; - type Consideration = - HoldConsideration< - AccountId, - Balances, - PreimageHoldReason, - LinearStoragePrice< - dynamic_params::storage::BaseDeposit, - dynamic_params::storage::ByteDeposit, - Balance, - >, - >; + type Consideration = HoldConsideration< + AccountId, + Balances, + PreimageHoldReason, + LinearStoragePrice< + dynamic_params::storage::BaseDeposit, + dynamic_params::storage::ByteDeposit, + Balance, + >, + >; } parameter_types! { @@ -1437,12 +1436,11 @@ where ), frame_metadata_hash_extension::CheckMetadataHash::new(false), ); - let raw_payload = - SignedPayload::new(call, extra) - .map_err(|e| { - log::warn!("Unable to create signed payload: {:?}", e); - }) - .ok()?; + let raw_payload = SignedPayload::new(call, extra) + .map_err(|e| { + log::warn!("Unable to create signed payload: {:?}", e); + }) + .ok()?; let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?; let address = Indices::unlookup(account); let (call, extra, _) = raw_payload.deconstruct(); @@ -1799,14 +1797,13 @@ impl pallet_nis::BenchmarkSetup for SetupAsset { fn create_counterpart_asset() { let owner = AccountId::from([0u8; 32]); // this may or may not fail depending on if the chain spec or runtime genesis is used. - let _ = - Assets::force_create( - RuntimeOrigin::root(), - 9u32.into(), - sp_runtime::MultiAddress::Id(owner), - true, - 1, - ); + let _ = Assets::force_create( + RuntimeOrigin::root(), + 9u32.into(), + sp_runtime::MultiAddress::Id(owner), + true, + 1, + ); } } diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index 6afaddba98b44..1ae4db5c89370 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -937,16 +937,15 @@ fn test_migration_v4() { status: BountyStatus::::Proposed, }; - let data = - vec![ - (pallet_bounties::BountyCount::::hashed_key().to_vec(), 10.encode().to_vec()), - (pallet_bounties::Bounties::::hashed_key_for(index), bounty.encode().to_vec()), - (pallet_bounties::BountyDescriptions::::hashed_key_for(index), vec![0, 0]), - ( - pallet_bounties::BountyApprovals::::hashed_key().to_vec(), - vec![10 as u32].encode().to_vec(), - ), - ]; + let data = vec![ + (pallet_bounties::BountyCount::::hashed_key().to_vec(), 10.encode().to_vec()), + (pallet_bounties::Bounties::::hashed_key_for(index), bounty.encode().to_vec()), + (pallet_bounties::BountyDescriptions::::hashed_key_for(index), vec![0, 0]), + ( + pallet_bounties::BountyApprovals::::hashed_key().to_vec(), + vec![10 as u32].encode().to_vec(), + ), + ]; s.top = data.into_iter().collect(); diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 4151d5ece72a3..8989c3ba92b5c 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -427,9 +427,10 @@ pub mod pallet { T::Currency::reactivate(deactivated); T::Currency::deactivate(pot); Deactivated::::put(&pot); - Self::deposit_event( - Event::::UpdatedInactive { reactivated: deactivated, deactivated: pot } - ); + Self::deposit_event(Event::::UpdatedInactive { + reactivated: deactivated, + deactivated: pot, + }); } // Check to see if we should spend some funds! @@ -768,40 +769,38 @@ impl, I: 'static> Pallet { let mut missed_any = false; let mut imbalance = >::zero(); - let proposals_len = - Approvals::::mutate(|v| { - let proposals_approvals_len = v.len() as u32; - v.retain(|&index| { - // Should always be true, but shouldn't panic if false or we're screwed. - if let Some(p) = Self::proposals(index) { - if p.value <= budget_remaining { - budget_remaining -= p.value; - >::remove(index); - - // return their deposit. - let err_amount = T::Currency::unreserve(&p.proposer, p.bond); - debug_assert!(err_amount.is_zero()); - - // provide the allocation. - imbalance - .subsume(T::Currency::deposit_creating(&p.beneficiary, p.value)); - - Self::deposit_event(Event::Awarded { - proposal_index: index, - award: p.value, - account: p.beneficiary, - }); - false - } else { - missed_any = true; - true - } - } else { + let proposals_len = Approvals::::mutate(|v| { + let proposals_approvals_len = v.len() as u32; + v.retain(|&index| { + // Should always be true, but shouldn't panic if false or we're screwed. + if let Some(p) = Self::proposals(index) { + if p.value <= budget_remaining { + budget_remaining -= p.value; + >::remove(index); + + // return their deposit. + let err_amount = T::Currency::unreserve(&p.proposer, p.bond); + debug_assert!(err_amount.is_zero()); + + // provide the allocation. + imbalance.subsume(T::Currency::deposit_creating(&p.beneficiary, p.value)); + + Self::deposit_event(Event::Awarded { + proposal_index: index, + award: p.value, + account: p.beneficiary, + }); false + } else { + missed_any = true; + true } - }); - proposals_approvals_len + } else { + false + } }); + proposals_approvals_len + }); total_weight += T::WeightInfo::on_initialize_proposals(proposals_len); diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 8dc2b4a80e2df..9dcafbda57c75 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -858,9 +858,9 @@ fn try_state_spends_invariant_1_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; // Propose and approve a spend - assert_ok!( - { Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 1, Box::new(6), None) } - ); + assert_ok!({ + Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 1, Box::new(6), None) + }); assert_eq!(Spends::::iter().count(), 1); assert_eq!(SpendCount::::get(), 1); // Check invariant 1 holds @@ -909,9 +909,9 @@ fn try_state_spends_invariant_3_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; // Propose and approve a spend - assert_ok!( - { Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 1, Box::new(6), None) } - ); + assert_ok!({ + Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 1, Box::new(6), None) + }); assert_eq!(Spends::::iter().count(), 1); let current_spend_count = SpendCount::::get(); assert_eq!(current_spend_count, 1); From 1bdc38d209123c4e3ca29c275380cb88143446c6 Mon Sep 17 00:00:00 2001 From: tin-snowflake Date: Mon, 27 May 2024 10:49:35 +0800 Subject: [PATCH 18/25] Update pr_3820.prdoc --- prdoc/pr_3820.prdoc | 1 + 1 file changed, 1 insertion(+) diff --git a/prdoc/pr_3820.prdoc b/prdoc/pr_3820.prdoc index 49aed05a50feb..b0966561a1a78 100644 --- a/prdoc/pr_3820.prdoc +++ b/prdoc/pr_3820.prdoc @@ -10,6 +10,7 @@ doc: - Remove deprecated calls `propose_spend`, `reject_proposal`, `approve_proposal`. - Replace the code flow of `propose_spend` then `approve_proposal` with `spend_local` - Remove deprecated calls' related weight functions and test cases. + - Remove deprecated parameter types: ProposalBond, ProposalBondMaximum, ProposalBondMinimum crates: - name: pallet-treasury From 56221616ad79d8196b189482b6a208868434dce2 Mon Sep 17 00:00:00 2001 From: tin-snowflake <56880684+chungquantin@users.noreply.github.com> Date: Mon, 3 Jun 2024 10:25:11 +0800 Subject: [PATCH 19/25] Remove unused variables in westend runtime benchmarks --- .../collectives/collectives-westend/src/fellowship/mod.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs index 7592bca566015..6f13c3d9d5dec 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs @@ -55,8 +55,6 @@ use xcm_builder::{AliasesIntoAccountId32, PayOverXcm}; #[cfg(feature = "runtime-benchmarks")] use crate::impls::benchmarks::{OpenHrmpChannel, PayWithEnsure}; -#[cfg(feature = "runtime-benchmarks")] -use testnet_parachains_constants::westend::currency::DOLLARS; /// The Fellowship members' ranks. pub mod ranks { From 432a110abc57563bbd8a8646ed07263accd42982 Mon Sep 17 00:00:00 2001 From: tin-snowflake <56880684+chungquantin@users.noreply.github.com> Date: Fri, 14 Jun 2024 10:16:28 +0800 Subject: [PATCH 20/25] Update bump attribute for updated pallet crates --- prdoc/pr_3820.prdoc | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/prdoc/pr_3820.prdoc b/prdoc/pr_3820.prdoc index b0966561a1a78..da0037fa9bcf9 100644 --- a/prdoc/pr_3820.prdoc +++ b/prdoc/pr_3820.prdoc @@ -11,6 +11,14 @@ doc: - Replace the code flow of `propose_spend` then `approve_proposal` with `spend_local` - Remove deprecated calls' related weight functions and test cases. - Remove deprecated parameter types: ProposalBond, ProposalBondMaximum, ProposalBondMinimum + - Remove pallet treasury's relevant deprecated code in pallet-tips, pallet-bounties and pallet-child-bounties crates: - name: pallet-treasury + bump: major + - name: pallet-tips + bump: minor + - name: pallet-child-bounties + bump: minor + - name: pallet-bounties + bump: minor From ca49d524549e912bf893c6b7ab6cb5d1ee1778dc Mon Sep 17 00:00:00 2001 From: tin-snowflake <56880684+chungquantin@users.noreply.github.com> Date: Fri, 14 Jun 2024 10:38:00 +0800 Subject: [PATCH 21/25] Refromat prdoc --- prdoc/pr_3820.prdoc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/prdoc/pr_3820.prdoc b/prdoc/pr_3820.prdoc index da0037fa9bcf9..a99935e752698 100644 --- a/prdoc/pr_3820.prdoc +++ b/prdoc/pr_3820.prdoc @@ -4,12 +4,12 @@ title: Remove deprecated calls from treasury pallet doc: - - audience: Runtime Dev, Runtime User + - audience: Runtime User description: | This PR remove deprecated calls, relevant tests from `pallet-treasury`. - - Remove deprecated calls `propose_spend`, `reject_proposal`, `approve_proposal`. - - Replace the code flow of `propose_spend` then `approve_proposal` with `spend_local` - - Remove deprecated calls' related weight functions and test cases. + - Remove deprecated calls `propose_spend`, `reject_proposal`, `approve_proposal`. + - Replace the code flow of `propose_spend` then `approve_proposal` with `spend_local` + - Remove deprecated calls' related weight functions and test cases. - Remove deprecated parameter types: ProposalBond, ProposalBondMaximum, ProposalBondMinimum - Remove pallet treasury's relevant deprecated code in pallet-tips, pallet-bounties and pallet-child-bounties From e911eb636a244dd97ece2642388f69aa53129440 Mon Sep 17 00:00:00 2001 From: tin-snowflake <56880684+chungquantin@users.noreply.github.com> Date: Fri, 14 Jun 2024 14:06:47 +0800 Subject: [PATCH 22/25] update prdoc bump for relevant crates --- prdoc/pr_3820.prdoc | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/prdoc/pr_3820.prdoc b/prdoc/pr_3820.prdoc index a99935e752698..0549657c1692b 100644 --- a/prdoc/pr_3820.prdoc +++ b/prdoc/pr_3820.prdoc @@ -15,10 +15,18 @@ doc: crates: - name: pallet-treasury - bump: major + bump: patch - name: pallet-tips - bump: minor + bump: patch - name: pallet-child-bounties - bump: minor + bump: patch - name: pallet-bounties - bump: minor + bump: patch + - name: polkadot-runtime-common + bump: patch + - name: rococo-runtime + bump: patch + - name: westend-runtime + bump: patch + - name: collectives-westend-runtime + bump: patch From 4eb538c0b5727669eb37ec4cfd5ba37f392b642a Mon Sep 17 00:00:00 2001 From: tin-snowflake <56880684+chungquantin@users.noreply.github.com> Date: Sun, 16 Jun 2024 11:57:30 +0800 Subject: [PATCH 23/25] Revert doc changes and update setup_proposal --- substrate/frame/treasury/src/benchmarking.rs | 2 +- substrate/frame/treasury/src/lib.rs | 44 ++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/substrate/frame/treasury/src/benchmarking.rs b/substrate/frame/treasury/src/benchmarking.rs index 6272e76908408..63978c94e682f 100644 --- a/substrate/frame/treasury/src/benchmarking.rs +++ b/substrate/frame/treasury/src/benchmarking.rs @@ -64,7 +64,7 @@ fn setup_proposal, I: 'static>( u: u32, ) -> (T::AccountId, BalanceOf, AccountIdLookupOf) { let caller = account("caller", u, SEED); - let value: BalanceOf = 100u32.try_into().ok().unwrap(); + let value: BalanceOf = T::Currency::minimum_balance() * 100u32.into(); let _ = T::Currency::make_free_balance_be(&caller, value); let beneficiary = account("beneficiary", u, SEED); let beneficiary_lookup = T::Lookup::unlookup(beneficiary); diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 8989c3ba92b5c..1cf311df342ef 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -522,6 +522,26 @@ pub mod pallet { } /// Force a previously approved proposal to be removed from the approval queue. + /// + /// ## Dispatch Origin + /// + /// Must be [`Config::RejectOrigin`]. + /// + /// ## Details + /// + /// The original deposit will no longer be returned. + /// + /// ### Parameters + /// - `proposal_id`: The index of a proposal + /// + /// ### Complexity + /// - O(A) where `A` is the number of approvals + /// + /// ### Errors + /// - [`Error::ProposalNotApproved`]: The `proposal_id` supplied was not found in the + /// approval queue, i.e., the proposal has not been approved. This could also mean the + /// proposal does not exist altogether, thus there is no way it would have been approved + /// in the first place. #[pallet::call_index(4)] #[pallet::weight((T::WeightInfo::remove_approval(), DispatchClass::Operational))] pub fn remove_approval( @@ -637,6 +657,21 @@ pub mod pallet { /// Claim a spend. /// /// ## Dispatch Origin + /// + /// + /// ## Details + /// + /// Spends must be claimed within some temporal bounds. A spend may be claimed within one + /// [`Config::PayoutPeriod`] from the `valid_from` block. + /// In case of a payout failure, the spend status must be updated with the `check_status` + /// dispatchable before retrying with the current function. + /// + /// ### Parameters + /// - `index`: The spend index. + /// + /// ## Events + /// + /// Emits [`Event::Paid`] if successful. #[pallet::call_index(6)] #[pallet::weight(T::WeightInfo::payout())] pub fn payout(origin: OriginFor, index: SpendIndex) -> DispatchResult { @@ -755,6 +790,9 @@ impl, I: 'static> Pallet { // Add public immutables and private mutables. /// The account ID of the treasury pot. + /// + /// This actually does computation. If you need to keep using it, then make sure you cache the + /// value and only call this once. pub fn account_id() -> T::AccountId { T::PalletId::get().into_account_truncating() } @@ -894,6 +932,12 @@ impl, I: 'static> Pallet { } /// ## Invariants of spend storage items + /// + /// 1. [`SpendCount`] >= Number of elements in [`Spends`]. + /// 2. Each entry in [`Spends`] should be saved under a key strictly less than current + /// [`SpendCount`]. + /// 3. For each spend entry contained in [`Spends`] we should have spend.expire_at + /// > spend.valid_from. #[cfg(any(feature = "try-runtime", test))] fn try_state_spends() -> Result<(), sp_runtime::TryRuntimeError> { let current_spend_count = SpendCount::::get(); From ee8bdb2a77851cf09c09d9a3b74426de3197b550 Mon Sep 17 00:00:00 2001 From: tin-snowflake <56880684+chungquantin@users.noreply.github.com> Date: Sun, 16 Jun 2024 15:54:05 +0800 Subject: [PATCH 24/25] fix prdoc --- prdoc/pr_3820.prdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prdoc/pr_3820.prdoc b/prdoc/pr_3820.prdoc index 0549657c1692b..33e8129df92a3 100644 --- a/prdoc/pr_3820.prdoc +++ b/prdoc/pr_3820.prdoc @@ -15,7 +15,7 @@ doc: crates: - name: pallet-treasury - bump: patch + bump: major - name: pallet-tips bump: patch - name: pallet-child-bounties From 3b2ae664b35f5ad0a42f2bea2a159543139d7757 Mon Sep 17 00:00:00 2001 From: tin-snowflake <56880684+chungquantin@users.noreply.github.com> Date: Mon, 17 Jun 2024 22:16:35 +0800 Subject: [PATCH 25/25] revert missing doc --- substrate/frame/treasury/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 1cf311df342ef..4677a0e0335cd 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -658,6 +658,7 @@ pub mod pallet { /// /// ## Dispatch Origin /// + /// Must be signed /// /// ## Details ///