From d078b43c02c48d59015fba18afd89c0f4212ef72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dino=20Pa=C4=8Dandi?= <3002868+Dinonard@users.noreply.github.com> Date: Thu, 30 Jan 2025 11:22:41 +0100 Subject: [PATCH] pallet-treasury cleanup (#1416) --- Cargo.lock | 28 +- runtime/astar/src/lib.rs | 32 +- runtime/local/src/lib.rs | 32 +- runtime/shibuya/src/lib.rs | 32 +- vendor/treasury/Cargo.toml | 2 +- vendor/treasury/README.md | 25 - vendor/treasury/src/benchmarking.rs | 273 +---------- vendor/treasury/src/lib.rs | 573 +--------------------- vendor/treasury/src/tests.rs | 735 +--------------------------- vendor/treasury/src/weights.rs | 166 ------- 10 files changed, 47 insertions(+), 1851 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fca53e5857..95b258ad93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -593,7 +593,7 @@ dependencies = [ "pallet-evm-precompile-assets-erc20", "pallet-evm-precompile-dispatch", "pallet-membership", - "pallet-treasury 36.0.1", + "pallet-treasury 37.0.0", "pallet-xc-asset-config", "parity-scale-codec", "scale-info", @@ -684,7 +684,7 @@ dependencies = [ "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury 36.0.1", + "pallet-treasury 37.0.0", "pallet-utility", "pallet-vesting", "pallet-xc-asset-config", @@ -6548,7 +6548,7 @@ dependencies = [ "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury 36.0.1", + "pallet-treasury 37.0.0", "pallet-tx-pause", "pallet-unified-accounts", "pallet-utility", @@ -8176,7 +8176,7 @@ dependencies = [ "frame-support", "frame-system", "log", - "pallet-treasury 36.0.1 (git+https://github.com/paritytech/polkadot-sdk?branch=stable2407)", + "pallet-treasury 36.0.1", "parity-scale-codec", "scale-info", "sp-core", @@ -8254,7 +8254,7 @@ dependencies = [ "frame-system", "log", "pallet-bounties", - "pallet-treasury 36.0.1 (git+https://github.com/paritytech/polkadot-sdk?branch=stable2407)", + "pallet-treasury 36.0.1", "parity-scale-codec", "scale-info", "sp-core", @@ -9544,7 +9544,7 @@ dependencies = [ "frame-support", "frame-system", "log", - "pallet-treasury 36.0.1 (git+https://github.com/paritytech/polkadot-sdk?branch=stable2407)", + "pallet-treasury 36.0.1", "parity-scale-codec", "scale-info", "serde", @@ -9599,6 +9599,7 @@ dependencies = [ [[package]] name = "pallet-treasury" version = "36.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#b98e0b32c68ba10a345a5f6c9edf7e2648c3daac" dependencies = [ "docify", "frame-benchmarking", @@ -9606,19 +9607,16 @@ dependencies = [ "frame-system", "impl-trait-for-tuples", "pallet-balances", - "pallet-utility", "parity-scale-codec", "scale-info", "serde", "sp-core", - "sp-io", "sp-runtime", ] [[package]] name = "pallet-treasury" -version = "36.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=stable2407#b98e0b32c68ba10a345a5f6c9edf7e2648c3daac" +version = "37.0.0" dependencies = [ "docify", "frame-benchmarking", @@ -9626,10 +9624,12 @@ dependencies = [ "frame-system", "impl-trait-for-tuples", "pallet-balances", + "pallet-utility", "parity-scale-codec", "scale-info", "serde", "sp-core", + "sp-io", "sp-runtime", ] @@ -10961,7 +10961,7 @@ dependencies = [ "pallet-staking-reward-fn", "pallet-timestamp", "pallet-transaction-payment", - "pallet-treasury 36.0.1 (git+https://github.com/paritytech/polkadot-sdk?branch=stable2407)", + "pallet-treasury 36.0.1", "pallet-vesting", "parity-scale-codec", "polkadot-primitives", @@ -12303,7 +12303,7 @@ dependencies = [ "pallet-tips", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury 36.0.1 (git+https://github.com/paritytech/polkadot-sdk?branch=stable2407)", + "pallet-treasury 36.0.1", "pallet-utility", "pallet-vesting", "pallet-whitelist", @@ -14434,7 +14434,7 @@ dependencies = [ "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury 36.0.1", + "pallet-treasury 37.0.0", "pallet-tx-pause", "pallet-unified-accounts", "pallet-utility", @@ -17469,7 +17469,7 @@ dependencies = [ "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury 36.0.1 (git+https://github.com/paritytech/polkadot-sdk?branch=stable2407)", + "pallet-treasury 36.0.1", "pallet-utility", "pallet-vesting", "pallet-whitelist", diff --git a/runtime/astar/src/lib.rs b/runtime/astar/src/lib.rs index 61b6f7f780..d360cbb0a6 100644 --- a/runtime/astar/src/lib.rs +++ b/runtime/astar/src/lib.rs @@ -29,7 +29,6 @@ use frame_support::{ genesis_builder_helper, parameter_types, traits::{ fungible::{Balanced, Credit, HoldConsideration}, - tokens::{PayFromAccount, UnityAssetBalanceConversion}, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, Contains, EqualPrivilegeOnly, FindAuthor, Get, Imbalance, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize, OnUnbalanced, Randomness, WithdrawReasons, @@ -63,8 +62,7 @@ use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, - DispatchInfoOf, Dispatchable, IdentityLookup, OpaqueKeys, PostDispatchInfoOf, - UniqueSaturatedInto, Zero, + DispatchInfoOf, Dispatchable, OpaqueKeys, PostDispatchInfoOf, UniqueSaturatedInto, Zero, }, transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError}, ApplyExtrinsicResult, FixedPointNumber, FixedU128, Perbill, Permill, Perquintill, RuntimeDebug, @@ -1404,20 +1402,8 @@ impl pallet_treasury::Config for Runtime { type Burn = (); type BurnDestination = (); type SpendFunds = (); - type MaxApprovals = ConstU32<64>; - type AssetKind = (); // Only native asset is supported - type Beneficiary = AccountId; - type BeneficiaryLookup = IdentityLookup; - type Paymaster = PayFromAccount; - type BalanceConverter = UnityAssetBalanceConversion; - - // New approach to using treasury, useful for OpenGov but not necessarily for us. - type SpendOrigin = frame_support::traits::NeverEnsureOrigin; - // Only used by 'spend' approach which is disabled - type PayoutPeriod = ConstU32<0>; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); + type WeightInfo = pallet_treasury::weights::SubstrateWeight; } @@ -1444,20 +1430,8 @@ impl pallet_treasury::Config for Runtime { type Burn = (); type BurnDestination = (); type SpendFunds = (); - type MaxApprovals = ConstU32<64>; - type AssetKind = (); // Only native asset is supported - type Beneficiary = AccountId; - type BeneficiaryLookup = IdentityLookup; - type Paymaster = PayFromAccount; - type BalanceConverter = UnityAssetBalanceConversion; - - // New approach to using treasury, useful for OpenGov but not necessarily for us. - type SpendOrigin = frame_support::traits::NeverEnsureOrigin; - // Only used by 'spend' approach which is disabled - type PayoutPeriod = ConstU32<0>; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); + type WeightInfo = pallet_treasury::weights::SubstrateWeight; } diff --git a/runtime/local/src/lib.rs b/runtime/local/src/lib.rs index 7ce660b321..b050b1e0a8 100644 --- a/runtime/local/src/lib.rs +++ b/runtime/local/src/lib.rs @@ -28,7 +28,6 @@ use frame_support::{ construct_runtime, genesis_builder_helper, parameter_types, traits::{ fungible::{Balanced, Credit, HoldConsideration}, - tokens::{PayFromAccount, UnityAssetBalanceConversion}, AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, Contains, EqualPrivilegeOnly, FindAuthor, Get, InsideBoth, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize, WithdrawReasons, @@ -56,8 +55,7 @@ use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, - DispatchInfoOf, Dispatchable, IdentityLookup, NumberFor, PostDispatchInfoOf, - UniqueSaturatedInto, + DispatchInfoOf, Dispatchable, NumberFor, PostDispatchInfoOf, UniqueSaturatedInto, }, transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError}, ApplyExtrinsicResult, FixedPointNumber, FixedU128, Perbill, Permill, Perquintill, RuntimeDebug, @@ -1048,20 +1046,8 @@ impl pallet_treasury::Config for Runtime { type Burn = (); type BurnDestination = (); type SpendFunds = (); - type MaxApprovals = ConstU32<64>; - type AssetKind = (); // Only native asset is supported - type Beneficiary = AccountId; - type BeneficiaryLookup = IdentityLookup; - type Paymaster = PayFromAccount; - type BalanceConverter = UnityAssetBalanceConversion; - - // New approach to using treasury, useful for OpenGov but not necessarily for us. - type SpendOrigin = frame_support::traits::NeverEnsureOrigin; - // Only used by 'spend' approach which is disabled - type PayoutPeriod = ConstU32<0>; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); + type WeightInfo = pallet_treasury::weights::SubstrateWeight; } @@ -1088,20 +1074,8 @@ impl pallet_treasury::Config for Runtime { type Burn = (); type BurnDestination = (); type SpendFunds = (); - type MaxApprovals = ConstU32<64>; - type AssetKind = (); // Only native asset is supported - type Beneficiary = AccountId; - type BeneficiaryLookup = IdentityLookup; - type Paymaster = PayFromAccount; - type BalanceConverter = UnityAssetBalanceConversion; - - // New approach to using treasury, useful for OpenGov but not necessarily for us. - type SpendOrigin = frame_support::traits::NeverEnsureOrigin; - // Only used by 'spend' approach which is disabled - type PayoutPeriod = ConstU32<0>; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); + type WeightInfo = pallet_treasury::weights::SubstrateWeight; } diff --git a/runtime/shibuya/src/lib.rs b/runtime/shibuya/src/lib.rs index bf839ea052..66d0c48f0b 100644 --- a/runtime/shibuya/src/lib.rs +++ b/runtime/shibuya/src/lib.rs @@ -29,7 +29,6 @@ use frame_support::{ genesis_builder_helper, parameter_types, traits::{ fungible::{Balanced, Credit, HoldConsideration}, - tokens::{PayFromAccount, UnityAssetBalanceConversion}, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, Contains, EqualPrivilegeOnly, FindAuthor, Get, Imbalance, InsideBoth, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize, OnUnbalanced, WithdrawReasons, @@ -62,8 +61,7 @@ use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, - DispatchInfoOf, Dispatchable, IdentityLookup, OpaqueKeys, PostDispatchInfoOf, - UniqueSaturatedInto, + DispatchInfoOf, Dispatchable, OpaqueKeys, PostDispatchInfoOf, UniqueSaturatedInto, }, transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError}, ApplyExtrinsicResult, FixedPointNumber, FixedU128, Perbill, Permill, Perquintill, RuntimeDebug, @@ -1444,20 +1442,8 @@ impl pallet_treasury::Config for Runtime { type Burn = (); type BurnDestination = (); type SpendFunds = (); - type MaxApprovals = ConstU32<64>; - type AssetKind = (); // Only native asset is supported - type Beneficiary = AccountId; - type BeneficiaryLookup = IdentityLookup; - type Paymaster = PayFromAccount; - type BalanceConverter = UnityAssetBalanceConversion; - - // New approach to using treasury, useful for OpenGov but not necessarily for us. - type SpendOrigin = frame_support::traits::NeverEnsureOrigin; - // Only used by 'spend' approach which is disabled - type PayoutPeriod = ConstU32<0>; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); + type WeightInfo = pallet_treasury::weights::SubstrateWeight; } @@ -1484,20 +1470,8 @@ impl pallet_treasury::Config for Runtime { type Burn = (); type BurnDestination = (); type SpendFunds = (); - type MaxApprovals = ConstU32<64>; - type AssetKind = (); // Only native asset is supported - type Beneficiary = AccountId; - type BeneficiaryLookup = IdentityLookup; - type Paymaster = PayFromAccount; - type BalanceConverter = UnityAssetBalanceConversion; - - // New approach to using treasury, useful for OpenGov but not necessarily for us. - type SpendOrigin = frame_support::traits::NeverEnsureOrigin; - // Only used by 'spend' approach which is disabled - type PayoutPeriod = ConstU32<0>; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); + type WeightInfo = pallet_treasury::weights::SubstrateWeight; } diff --git a/vendor/treasury/Cargo.toml b/vendor/treasury/Cargo.toml index e60c43416c..b6929aacb3 100644 --- a/vendor/treasury/Cargo.toml +++ b/vendor/treasury/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-treasury" -version = "36.0.1" +version = "37.0.0" authors = ["Parity Technologies "] edition = "2021" homepage = "https://paritytech.github.io/polkadot-sdk/" diff --git a/vendor/treasury/README.md b/vendor/treasury/README.md index 48fd1e2699..8173f68829 100644 --- a/vendor/treasury/README.md +++ b/vendor/treasury/README.md @@ -20,28 +20,3 @@ and use the funds to pay developers. - **Deposit:** Funds that a proposer must lock when making a proposal. The deposit will be returned or slashed if the proposal is approved or rejected respectively. - **Pot:** Unspent funds accumulated by the treasury pallet. - -## Interface - -### Dispatchable Functions - -General spending/proposal protocol: -- `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 - - -## Release - -polkadot v1.15.0 -- `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. diff --git a/vendor/treasury/src/benchmarking.rs b/vendor/treasury/src/benchmarking.rs index 2a8b080d3e..168dc459f2 100644 --- a/vendor/treasury/src/benchmarking.rs +++ b/vendor/treasury/src/benchmarking.rs @@ -26,36 +26,10 @@ use frame_benchmarking::{ v2::*, }; use frame_support::{ - assert_err, assert_ok, ensure, - traits::{ - tokens::{ConversionFromAssetBalance, PaymentStatus}, - EnsureOrigin, OnInitialize, - }, + ensure, + traits::{EnsureOrigin, OnInitialize}, }; use frame_system::RawOrigin; -use sp_core::crypto::FromEntropy; - -/// Trait describing factory functions for dispatchables' parameters. -pub trait ArgumentsFactory { - /// Factory function for an asset kind. - fn create_asset_kind(seed: u32) -> AssetKind; - /// Factory function for a beneficiary. - fn create_beneficiary(seed: [u8; 32]) -> Beneficiary; -} - -/// Implementation that expects the parameters implement the [`FromEntropy`] trait. -impl ArgumentsFactory for () -where - AssetKind: FromEntropy, - Beneficiary: FromEntropy, -{ - fn create_asset_kind(seed: u32) -> AssetKind { - AssetKind::from_entropy(&mut seed.encode().as_slice()).unwrap() - } - fn create_beneficiary(seed: [u8; 32]) -> Beneficiary { - Beneficiary::from_entropy(&mut seed.as_slice()).unwrap() - } -} const SEED: u32 = 0; @@ -95,52 +69,10 @@ fn setup_pot_account, I: 'static>() { let _ = T::Currency::make_free_balance_be(&pot_account, value); } -fn assert_last_event, I: 'static>(generic_event: >::RuntimeEvent) { - frame_system::Pallet::::assert_last_event(generic_event.into()); -} - -// Create the arguments for the `spend` dispatchable. -fn create_spend_arguments, I: 'static>( - seed: u32, -) -> ( - T::AssetKind, - AssetBalanceOf, - T::Beneficiary, - BeneficiaryLookupOf, -) { - let asset_kind = T::BenchmarkHelper::create_asset_kind(seed); - let beneficiary = T::BenchmarkHelper::create_beneficiary([seed.try_into().unwrap(); 32]); - let beneficiary_lookup = T::BeneficiaryLookup::unlookup(beneficiary.clone()); - (asset_kind, 100u32.into(), beneficiary, beneficiary_lookup) -} - #[instance_benchmarks] mod benchmarks { use super::*; - /// This benchmark is short-circuited if `SpendOrigin` cannot provide - /// a successful origin, in which case `spend` is un-callable and can use weight=0. - #[benchmark] - fn spend_local() -> Result<(), BenchmarkError> { - let (_, value, beneficiary_lookup) = setup_proposal::(SEED); - let origin = - T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let beneficiary = T::Lookup::lookup(beneficiary_lookup.clone()).unwrap(); - - #[extrinsic_call] - _(origin as T::RuntimeOrigin, value, beneficiary_lookup); - - assert_last_event::( - Event::SpendApproved { - proposal_index: 0, - amount: value, - beneficiary, - } - .into(), - ); - Ok(()) - } - #[benchmark] fn propose_spend() -> Result<(), BenchmarkError> { let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); @@ -193,26 +125,6 @@ mod benchmarks { 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 proposal_id = Treasury::::proposal_count() - 1; - Approvals::::try_append(proposal_id).unwrap(); - let reject_origin = - T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - - #[extrinsic_call] - _(reject_origin as T::RuntimeOrigin, proposal_id); - - Ok(()) - } - #[benchmark] fn on_initialize_proposals( p: Linear<0, { T::MaxApprovals::get() - 1 }>, @@ -228,183 +140,6 @@ mod benchmarks { Ok(()) } - /// This benchmark is short-circuited if `SpendOrigin` cannot provide - /// a successful origin, in which case `spend` is un-callable and can use weight=0. - #[benchmark] - fn spend() -> Result<(), BenchmarkError> { - let origin = - T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let (asset_kind, amount, beneficiary, beneficiary_lookup) = - create_spend_arguments::(SEED); - T::BalanceConverter::ensure_successful(asset_kind.clone()); - - #[extrinsic_call] - _( - origin as T::RuntimeOrigin, - Box::new(asset_kind.clone()), - amount, - Box::new(beneficiary_lookup), - None, - ); - - let valid_from = frame_system::Pallet::::block_number(); - let expire_at = valid_from.saturating_add(T::PayoutPeriod::get()); - assert_last_event::( - Event::AssetSpendApproved { - index: 0, - asset_kind, - amount, - beneficiary, - valid_from, - expire_at, - } - .into(), - ); - Ok(()) - } - - #[benchmark] - fn payout() -> Result<(), BenchmarkError> { - let (asset_kind, amount, beneficiary, beneficiary_lookup) = - create_spend_arguments::(SEED); - T::BalanceConverter::ensure_successful(asset_kind.clone()); - - let spend_exists = if let Ok(origin) = T::SpendOrigin::try_successful_origin() { - Treasury::::spend( - origin, - Box::new(asset_kind.clone()), - amount, - Box::new(beneficiary_lookup), - None, - )?; - - true - } else { - false - }; - - T::Paymaster::ensure_successful(&beneficiary, asset_kind, amount); - let caller: T::AccountId = account("caller", 0, SEED); - - #[block] - { - let res = Treasury::::payout(RawOrigin::Signed(caller.clone()).into(), 0u32); - - if spend_exists { - assert_ok!(res); - } else { - assert_err!(res, crate::Error::::InvalidIndex); - } - } - - if spend_exists { - let id = match Spends::::get(0).unwrap().status { - PaymentState::Attempted { id, .. } => { - assert_ne!(T::Paymaster::check_payment(id), PaymentStatus::Failure); - id - } - _ => panic!("No payout attempt made"), - }; - assert_last_event::( - Event::Paid { - index: 0, - payment_id: id, - } - .into(), - ); - assert!(Treasury::::payout(RawOrigin::Signed(caller).into(), 0u32).is_err()); - } - - Ok(()) - } - - #[benchmark] - fn check_status() -> Result<(), BenchmarkError> { - let (asset_kind, amount, beneficiary, beneficiary_lookup) = - create_spend_arguments::(SEED); - - T::BalanceConverter::ensure_successful(asset_kind.clone()); - T::Paymaster::ensure_successful(&beneficiary, asset_kind.clone(), amount); - let caller: T::AccountId = account("caller", 0, SEED); - - let spend_exists = if let Ok(origin) = T::SpendOrigin::try_successful_origin() { - Treasury::::spend( - origin, - Box::new(asset_kind), - amount, - Box::new(beneficiary_lookup), - None, - )?; - - Treasury::::payout(RawOrigin::Signed(caller.clone()).into(), 0u32)?; - match Spends::::get(0).unwrap().status { - PaymentState::Attempted { id, .. } => { - T::Paymaster::ensure_concluded(id); - } - _ => panic!("No payout attempt made"), - }; - - true - } else { - false - }; - - #[block] - { - let res = - Treasury::::check_status(RawOrigin::Signed(caller.clone()).into(), 0u32); - - if spend_exists { - assert_ok!(res); - } else { - assert_err!(res, crate::Error::::InvalidIndex); - } - } - - if let Some(s) = Spends::::get(0) { - assert!(!matches!(s.status, PaymentState::Attempted { .. })); - } - - Ok(()) - } - - #[benchmark] - fn void_spend() -> Result<(), BenchmarkError> { - let (asset_kind, amount, _, beneficiary_lookup) = create_spend_arguments::(SEED); - T::BalanceConverter::ensure_successful(asset_kind.clone()); - let spend_exists = if let Ok(origin) = T::SpendOrigin::try_successful_origin() { - Treasury::::spend( - origin, - Box::new(asset_kind.clone()), - amount, - Box::new(beneficiary_lookup), - None, - )?; - assert!(Spends::::get(0).is_some()); - - true - } else { - false - }; - - let origin = - T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - - #[block] - { - let res = Treasury::::void_spend(origin as T::RuntimeOrigin, 0u32); - - if spend_exists { - assert_ok!(res); - } else { - assert_err!(res, crate::Error::::InvalidIndex); - } - } - - assert!(Spends::::get(0).is_none()); - Ok(()) - } - impl_benchmark_test_suite!( Treasury, crate::tests::ExtBuilder::default().build(), @@ -416,9 +151,7 @@ mod benchmarks { impl_benchmark_test_suite!( Treasury, - crate::tests::ExtBuilder::default() - .spend_origin_succesful_origin_err() - .build(), + crate::tests::ExtBuilder::default().build(), crate::tests::Test, benchmarks_path = benchmarking ); diff --git a/vendor/treasury/src/lib.rs b/vendor/treasury/src/lib.rs index fcf99f7188..3e85a36e40 100644 --- a/vendor/treasury/src/lib.rs +++ b/vendor/treasury/src/lib.rs @@ -43,32 +43,12 @@ //! - **Beneficiary:** An account who will receive the funds from a proposal iff the proposal is //! approved. //! - **Pot:** Unspent funds accumulated by the treasury pallet. -//! - **Spend** An approved proposal for transferring a specific amount of funds to a designated -//! beneficiary. -//! -//! ### Example -//! -//! 1. Multiple local spends approved by spend origins and received by a beneficiary. -#![doc = docify::embed!("src/tests.rs", spend_local_origin_works)] -//! -//! 2. Approve a spend of some asset kind and claim it. -#![doc = docify::embed!("src/tests.rs", spend_payout_works)] //! //! ## Pallet API //! //! See the [`pallet`] module for more information about the interfaces this pallet exposes, //! including its configuration trait, dispatchables, storage items, events and errors. //! -//! ## Low Level / Implementation Details -//! -//! Spends can be initiated using either the `spend_local` or `spend` dispatchable. The -//! `spend_local` dispatchable enables the creation of spends using the native currency of the -//! chain, utilizing the funds stored in the pot. These spends are automatically paid out every -//! [`pallet::Config::SpendPeriod`]. On the other hand, the `spend` dispatchable allows spending of -//! any asset kind managed by the treasury, with payment facilitated by a designated -//! [`pallet::Config::Paymaster`]. To claim these spends, the `payout` dispatchable should be called -//! within some temporal bounds, starting from the moment they become valid and within one -//! [`pallet::Config::PayoutPeriod`]. #![cfg_attr(not(feature = "std"), no_std)] @@ -78,25 +58,21 @@ mod tests; pub mod weights; use core::marker::PhantomData; -#[cfg(feature = "runtime-benchmarks")] -pub use benchmarking::ArgumentsFactory; - extern crate alloc; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -use alloc::{boxed::Box, collections::btree_map::BTreeMap}; use sp_runtime::{ - traits::{AccountIdConversion, CheckedAdd, Saturating, StaticLookup, Zero}, + traits::{AccountIdConversion, Saturating, StaticLookup, Zero}, Permill, RuntimeDebug, }; use frame_support::{ - dispatch::{DispatchResult, DispatchResultWithPostInfo}, + dispatch::DispatchResult, ensure, print, traits::{ - tokens::Pay, Currency, ExistenceRequirement::KeepAlive, Get, Imbalance, OnUnbalanced, + Currency, ExistenceRequirement::KeepAlive, Get, Imbalance, OnUnbalanced, ReservableCurrency, WithdrawReasons, }, weights::Weight, @@ -108,7 +84,6 @@ pub use weights::WeightInfo; pub type BalanceOf = <>::Currency as Currency<::AccountId>>::Balance; -pub type AssetBalanceOf = <>::Paymaster as Pay>::Balance; pub type PositiveImbalanceOf = <>::Currency as Currency< ::AccountId, >>::PositiveImbalance; @@ -116,7 +91,6 @@ pub type NegativeImbalanceOf = <>::Currency as Currenc ::AccountId, >>::NegativeImbalance; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; -type BeneficiaryLookupOf = <>::BeneficiaryLookup as StaticLookup>::Source; /// A trait to allow the Treasury Pallet to spend it's funds for other purposes. /// There is an expectation that the implementer of this trait will correctly manage @@ -156,47 +130,10 @@ pub struct Proposal { bond: Balance, } -/// The state of the payment claim. -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[derive(Encode, Decode, Clone, PartialEq, Eq, MaxEncodedLen, RuntimeDebug, TypeInfo)] -pub enum PaymentState { - /// Pending claim. - Pending, - /// Payment attempted with a payment identifier. - Attempted { id: Id }, - /// Payment failed. - Failed, -} - -/// Info regarding an approved treasury spend. -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[derive(Encode, Decode, Clone, PartialEq, Eq, MaxEncodedLen, RuntimeDebug, TypeInfo)] -pub struct SpendStatus { - // The kind of asset to be spent. - asset_kind: AssetKind, - /// The asset amount of the spend. - amount: AssetBalance, - /// The beneficiary of the spend. - beneficiary: Beneficiary, - /// The block number from which the spend can be claimed. - valid_from: BlockNumber, - /// The block number by which the spend has to be claimed. - expire_at: BlockNumber, - /// The status of the payout/claim. - status: PaymentState, -} - -/// Index of an approved treasury spend. -pub type SpendIndex = u32; - #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::{ - dispatch_context::with_context, - pallet_prelude::*, - traits::tokens::{ConversionFromAssetBalance, PaymentStatus}, - }; + use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::pallet] @@ -259,40 +196,6 @@ pub mod pallet { /// NOTE: This parameter is also used within the Bounties Pallet extension if enabled. #[pallet::constant] type MaxApprovals: Get; - - /// The origin required for approving spends from the treasury outside of the proposal - /// process. The `Success` value is the maximum amount in a native asset that this origin - /// is allowed to spend at a time. - type SpendOrigin: EnsureOrigin>; - - /// Type parameter representing the asset kinds to be spent from the treasury. - type AssetKind: Parameter + MaxEncodedLen; - - /// Type parameter used to identify the beneficiaries eligible to receive treasury spends. - type Beneficiary: Parameter + MaxEncodedLen; - - /// Converting trait to take a source type and convert to [`Self::Beneficiary`]. - type BeneficiaryLookup: StaticLookup; - - /// Type for processing spends of [Self::AssetKind] in favor of [`Self::Beneficiary`]. - type Paymaster: Pay; - - /// Type for converting the balance of an [Self::AssetKind] to the balance of the native - /// asset, solely for the purpose of asserting the result against the maximum allowed spend - /// amount of the [`Self::SpendOrigin`]. - type BalanceConverter: ConversionFromAssetBalance< - ::Balance, - Self::AssetKind, - BalanceOf, - >; - - /// The period during which an approved treasury spend has to be claimed. - #[pallet::constant] - type PayoutPeriod: Get>; - - /// Helper type for benchmarks. - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper: ArgumentsFactory; } /// Number of proposals that have been made. @@ -322,27 +225,6 @@ pub mod pallet { pub type Approvals, I: 'static = ()> = StorageValue<_, BoundedVec, ValueQuery>; - /// The count of spends that have been made. - #[pallet::storage] - pub(crate) type SpendCount = StorageValue<_, SpendIndex, ValueQuery>; - - /// Spends that have been approved and being processed. - // Hasher: Twox safe since `SpendIndex` is an internal count based index. - #[pallet::storage] - pub type Spends, I: 'static = ()> = StorageMap< - _, - Twox64Concat, - SpendIndex, - SpendStatus< - T::AssetKind, - AssetBalanceOf, - T::Beneficiary, - BlockNumberFor, - ::Id, - >, - OptionQuery, - >; - #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig, I: 'static = ()> { @@ -364,63 +246,35 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] + #[repr(u8)] pub enum Event, I: 'static = ()> { /// New proposal. - Proposed { proposal_index: ProposalIndex }, + Proposed { proposal_index: ProposalIndex } = 0, /// We have ended a spend period and will now allocate funds. - Spending { budget_remaining: BalanceOf }, + Spending { budget_remaining: BalanceOf } = 1, /// Some funds have been allocated. Awarded { proposal_index: ProposalIndex, award: BalanceOf, account: T::AccountId, - }, + } = 2, /// A proposal was rejected; funds were slashed. Rejected { proposal_index: ProposalIndex, slashed: BalanceOf, - }, + } = 3, /// Some of our funds have been burnt. - Burnt { burnt_funds: BalanceOf }, + Burnt { burnt_funds: BalanceOf } = 4, /// Spending has finished; this is the amount that rolls over until next spend. - Rollover { rollover_balance: BalanceOf }, + Rollover { rollover_balance: BalanceOf } = 5, /// Some funds have been deposited. - Deposit { value: BalanceOf }, + Deposit { value: BalanceOf } = 6, /// A new spend proposal has been approved. - SpendApproved { - proposal_index: ProposalIndex, - amount: BalanceOf, - beneficiary: T::AccountId, - }, /// The inactive funds of the pallet have been updated. UpdatedInactive { reactivated: BalanceOf, deactivated: BalanceOf, - }, - /// A new asset spend proposal has been approved. - AssetSpendApproved { - index: SpendIndex, - asset_kind: T::AssetKind, - amount: AssetBalanceOf, - beneficiary: T::Beneficiary, - valid_from: BlockNumberFor, - expire_at: BlockNumberFor, - }, - /// An approved spend was voided. - AssetSpendVoided { index: SpendIndex }, - /// A payment happened. - Paid { - index: SpendIndex, - payment_id: ::Id, - }, - /// A payment failed and can be retried. - 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. - SpendProcessed { index: SpendIndex }, + } = 8, } /// Error for the treasury pallet. @@ -437,20 +291,6 @@ pub mod pallet { InsufficientPermission, /// Proposal has not been approved. ProposalNotApproved, - /// The balance of the asset kind is not convertible to the balance of the native asset. - FailedToConvertBalance, - /// The spend has expired and cannot be claimed. - SpendExpired, - /// The spend is not yet eligible for payout. - EarlyPayout, - /// The payment has already been attempted. - AlreadyAttempted, - /// There was some issue with the mechanism of payment. - PayoutError, - /// The payout was not yet attempted/claimed. - NotAttempted, - /// The payment has neither failed nor succeeded yet. - Inconclusive, } #[pallet::hooks] @@ -487,11 +327,6 @@ pub mod pallet { } } - #[derive(Default)] - struct SpendContext { - spend_in_context: BTreeMap, - } - #[pallet::call] impl, I: 'static> Pallet { /// Put forward a suggestion for spending. @@ -621,352 +456,6 @@ pub mod pallet { .map_err(|_| Error::::TooManyApprovals)?; Ok(()) } - - /// Propose and approve a spend of treasury funds. - /// - /// ## Dispatch Origin - /// - /// Must be [`Config::SpendOrigin`] with the `Success` value being at least `amount`. - /// - /// ### Details - /// NOTE: For record-keeping purposes, the proposer is deemed to be equivalent to the - /// beneficiary. - /// - /// ### Parameters - /// - `amount`: The amount to be transferred from the treasury to the `beneficiary`. - /// - `beneficiary`: The destination account for the transfer. - /// - /// ## Events - /// - /// Emits [`Event::SpendApproved`] if successful. - #[pallet::call_index(3)] - #[pallet::weight(T::WeightInfo::spend_local())] - pub fn spend_local( - origin: OriginFor, - #[pallet::compact] amount: BalanceOf, - beneficiary: AccountIdLookupOf, - ) -> DispatchResult { - let max_amount = T::SpendOrigin::ensure_origin(origin)?; - ensure!(amount <= max_amount, Error::::InsufficientPermission); - - with_context::>, _>(|v| { - let context = v.or_default(); - - // We group based on `max_amount`, to distinguish between different kind of - // origins. (assumes that all origins have different `max_amount`) - // - // Worst case is that we reject some "valid" request. - let spend = context.spend_in_context.entry(max_amount).or_default(); - - // Ensure that we don't overflow nor use more than `max_amount` - if spend - .checked_add(&amount) - .map(|s| s > max_amount) - .unwrap_or(true) - { - Err(Error::::InsufficientPermission) - } else { - *spend = spend.saturating_add(amount); - - Ok(()) - } - }) - .unwrap_or(Ok(()))?; - - let beneficiary = T::Lookup::lookup(beneficiary)?; - let proposal_index = Self::proposal_count(); - Approvals::::try_append(proposal_index) - .map_err(|_| Error::::TooManyApprovals)?; - let proposal = Proposal { - proposer: beneficiary.clone(), - value: amount, - beneficiary: beneficiary.clone(), - bond: Default::default(), - }; - Proposals::::insert(proposal_index, proposal); - ProposalCount::::put(proposal_index + 1); - - Self::deposit_event(Event::SpendApproved { - proposal_index, - amount, - beneficiary, - }); - Ok(()) - } - - /// 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( - origin: OriginFor, - #[pallet::compact] proposal_id: ProposalIndex, - ) -> DispatchResult { - T::RejectOrigin::ensure_origin(origin)?; - - Approvals::::try_mutate(|v| -> DispatchResult { - if let Some(index) = v.iter().position(|x| x == &proposal_id) { - v.remove(index); - Ok(()) - } else { - Err(Error::::ProposalNotApproved.into()) - } - })?; - - Ok(()) - } - - /// Propose and approve a spend of treasury funds. - /// - /// ## Dispatch Origin - /// - /// Must be [`Config::SpendOrigin`] with the `Success` value being at least - /// `amount` of `asset_kind` in the native asset. The amount of `asset_kind` is converted - /// for assertion using the [`Config::BalanceConverter`]. - /// - /// ## Details - /// - /// Create an approved spend for transferring a specific `amount` of `asset_kind` to a - /// designated beneficiary. The spend must be claimed using the `payout` dispatchable within - /// the [`Config::PayoutPeriod`]. - /// - /// ### Parameters - /// - `asset_kind`: An indicator of the specific asset class to be spent. - /// - `amount`: The amount to be transferred from the treasury to the `beneficiary`. - /// - `beneficiary`: The beneficiary of the spend. - /// - `valid_from`: The block number from which the spend can be claimed. It can refer to - /// the past if the resulting spend has not yet expired according to the - /// [`Config::PayoutPeriod`]. If `None`, the spend can be claimed immediately after - /// approval. - /// - /// ## Events - /// - /// Emits [`Event::AssetSpendApproved`] if successful. - #[pallet::call_index(5)] - #[pallet::weight(T::WeightInfo::spend())] - pub fn spend( - origin: OriginFor, - asset_kind: Box, - #[pallet::compact] amount: AssetBalanceOf, - beneficiary: Box>, - valid_from: Option>, - ) -> DispatchResult { - let max_amount = T::SpendOrigin::ensure_origin(origin)?; - let beneficiary = T::BeneficiaryLookup::lookup(*beneficiary)?; - - let now = frame_system::Pallet::::block_number(); - let valid_from = valid_from.unwrap_or(now); - let expire_at = valid_from.saturating_add(T::PayoutPeriod::get()); - ensure!(expire_at > now, Error::::SpendExpired); - - let native_amount = - T::BalanceConverter::from_asset_balance(amount, *asset_kind.clone()) - .map_err(|_| Error::::FailedToConvertBalance)?; - - ensure!( - native_amount <= max_amount, - Error::::InsufficientPermission - ); - - with_context::>, _>(|v| { - let context = v.or_default(); - // We group based on `max_amount`, to distinguish between different kind of - // origins. (assumes that all origins have different `max_amount`) - // - // Worst case is that we reject some "valid" request. - let spend = context.spend_in_context.entry(max_amount).or_default(); - - // Ensure that we don't overflow nor use more than `max_amount` - if spend - .checked_add(&native_amount) - .map(|s| s > max_amount) - .unwrap_or(true) - { - Err(Error::::InsufficientPermission) - } else { - *spend = spend.saturating_add(native_amount); - Ok(()) - } - }) - .unwrap_or(Ok(()))?; - - let index = SpendCount::::get(); - Spends::::insert( - index, - SpendStatus { - asset_kind: *asset_kind.clone(), - amount, - beneficiary: beneficiary.clone(), - valid_from, - expire_at, - status: PaymentState::Pending, - }, - ); - SpendCount::::put(index + 1); - - Self::deposit_event(Event::AssetSpendApproved { - index, - asset_kind: *asset_kind, - amount, - beneficiary, - valid_from, - expire_at, - }); - Ok(()) - } - - /// 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 { - ensure_signed(origin)?; - let mut spend = Spends::::get(index).ok_or(Error::::InvalidIndex)?; - let now = frame_system::Pallet::::block_number(); - ensure!(now >= spend.valid_from, Error::::EarlyPayout); - ensure!(spend.expire_at > now, Error::::SpendExpired); - ensure!( - matches!(spend.status, PaymentState::Pending | PaymentState::Failed), - Error::::AlreadyAttempted - ); - - let id = T::Paymaster::pay(&spend.beneficiary, spend.asset_kind.clone(), spend.amount) - .map_err(|_| Error::::PayoutError)?; - - spend.status = PaymentState::Attempted { id }; - Spends::::insert(index, spend); - - Self::deposit_event(Event::::Paid { - index, - payment_id: id, - }); - - Ok(()) - } - - /// Check the status of the spend and remove it from the storage if processed. - /// - /// ## Dispatch Origin - /// - /// Must be signed. - /// - /// ## Details - /// - /// The status check is a prerequisite for retrying a failed payout. - /// If a spend has either succeeded or expired, it is removed from the storage by this - /// function. In such instances, transaction fees are refunded. - /// - /// ### Parameters - /// - `index`: The spend index. - /// - /// ## Events - /// - /// Emits [`Event::PaymentFailed`] if the spend payout has failed. - /// Emits [`Event::SpendProcessed`] if the spend payout has succeed. - #[pallet::call_index(7)] - #[pallet::weight(T::WeightInfo::check_status())] - pub fn check_status(origin: OriginFor, index: SpendIndex) -> DispatchResultWithPostInfo { - use PaymentState as State; - use PaymentStatus as Status; - - ensure_signed(origin)?; - let mut spend = Spends::::get(index).ok_or(Error::::InvalidIndex)?; - let now = frame_system::Pallet::::block_number(); - - if now > spend.expire_at && !matches!(spend.status, State::Attempted { .. }) { - // spend has expired and no further status update is expected. - Spends::::remove(index); - Self::deposit_event(Event::::SpendProcessed { index }); - return Ok(Pays::No.into()); - } - - let payment_id = match spend.status { - State::Attempted { id } => id, - _ => return Err(Error::::NotAttempted.into()), - }; - - match T::Paymaster::check_payment(payment_id) { - Status::Failure => { - spend.status = PaymentState::Failed; - Spends::::insert(index, spend); - Self::deposit_event(Event::::PaymentFailed { index, payment_id }); - } - Status::Success | Status::Unknown => { - Spends::::remove(index); - Self::deposit_event(Event::::SpendProcessed { index }); - return Ok(Pays::No.into()); - } - Status::InProgress => return Err(Error::::Inconclusive.into()), - } - return Ok(Pays::Yes.into()); - } - - /// Void previously approved spend. - /// - /// ## Dispatch Origin - /// - /// Must be [`Config::RejectOrigin`]. - /// - /// ## Details - /// - /// A spend void is only possible if the payout has not been attempted yet. - /// - /// ### Parameters - /// - `index`: The spend index. - /// - /// ## Events - /// - /// Emits [`Event::AssetSpendVoided`] if successful. - #[pallet::call_index(8)] - #[pallet::weight(T::WeightInfo::void_spend())] - pub fn void_spend(origin: OriginFor, index: SpendIndex) -> DispatchResult { - T::RejectOrigin::ensure_origin(origin)?; - let spend = Spends::::get(index).ok_or(Error::::InvalidIndex)?; - ensure!( - matches!(spend.status, PaymentState::Pending | PaymentState::Failed), - Error::::AlreadyAttempted - ); - - Spends::::remove(index); - Self::deposit_event(Event::::AssetSpendVoided { index }); - Ok(()) - } } } @@ -1085,8 +574,6 @@ impl, I: 'static> Pallet { #[cfg(any(feature = "try-runtime", test))] fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> { Self::try_state_proposals()?; - Self::try_state_spends()?; - Ok(()) } @@ -1125,40 +612,6 @@ impl, I: 'static> Pallet { Ok(()) } - - /// ## 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(); - ensure!( - current_spend_count as usize >= Spends::::iter().count(), - "Actual number of spends exceeds `SpendCount`." - ); - - Spends::::iter_keys().try_for_each(|spend_index| -> DispatchResult { - ensure!( - current_spend_count > spend_index, - "`SpendCount` should by strictly greater than any SpendIndex used as a key for `Spends`." - ); - Ok(()) - })?; - - Spends::::iter().try_for_each(|(_index, spend)| -> DispatchResult { - ensure!( - spend.valid_from < spend.expire_at, - "Spend cannot expire before it becomes valid." - ); - Ok(()) - })?; - - Ok(()) - } } impl, I: 'static> OnUnbalanced> for Pallet { diff --git a/vendor/treasury/src/tests.rs b/vendor/treasury/src/tests.rs index 2bda67d364..584f99806c 100644 --- a/vendor/treasury/src/tests.rs +++ b/vendor/treasury/src/tests.rs @@ -19,20 +19,12 @@ #![cfg(test)] -use core::{cell::RefCell, marker::PhantomData}; -use sp_runtime::{ - traits::{BadOrigin, Dispatchable, IdentityLookup}, - BuildStorage, -}; +use core::marker::PhantomData; +use sp_runtime::{traits::IdentityLookup, BuildStorage}; use frame_support::{ - assert_err_ignore_postinfo, assert_noop, assert_ok, derive_impl, - pallet_prelude::Pays, - parameter_types, - traits::{ - tokens::{ConversionFromAssetBalance, PaymentStatus}, - ConstU32, ConstU64, OnInitialize, - }, + assert_noop, assert_ok, derive_impl, parameter_types, + traits::{tokens::ConversionFromAssetBalance, ConstU32, ConstU64, OnInitialize}, PalletId, }; @@ -40,8 +32,6 @@ use super::*; use crate as treasury; type Block = frame_system::mocking::MockBlock; -type UtilityCall = pallet_utility::Call; -type TreasuryCall = crate::Call; frame_support::construct_runtime!( pub enum Test @@ -73,71 +63,6 @@ impl pallet_utility::Config for Test { type WeightInfo = (); } -thread_local! { - pub static PAID: RefCell> = RefCell::new(BTreeMap::new()); - pub static STATUS: RefCell> = RefCell::new(BTreeMap::new()); - pub static LAST_ID: RefCell = RefCell::new(0u64); - - #[cfg(feature = "runtime-benchmarks")] - pub static TEST_SPEND_ORIGIN_TRY_SUCCESFUL_ORIGIN_ERR: RefCell = RefCell::new(false); -} - -/// paid balance for a given account and asset ids -fn paid(who: u128, asset_id: u32) -> u64 { - PAID.with(|p| p.borrow().get(&(who, asset_id)).cloned().unwrap_or(0)) -} - -/// reduce paid balance for a given account and asset ids -fn unpay(who: u128, asset_id: u32, amount: u64) { - PAID.with(|p| { - p.borrow_mut() - .entry((who, asset_id)) - .or_default() - .saturating_reduce(amount) - }) -} - -/// set status for a given payment id -fn set_status(id: u64, s: PaymentStatus) { - STATUS.with(|m| m.borrow_mut().insert(id, s)); -} - -pub struct TestPay; -impl Pay for TestPay { - type Beneficiary = u128; - type Balance = u64; - type Id = u64; - type AssetKind = u32; - type Error = (); - - fn pay( - who: &Self::Beneficiary, - asset_kind: Self::AssetKind, - amount: Self::Balance, - ) -> Result { - PAID.with(|paid| *paid.borrow_mut().entry((*who, asset_kind)).or_default() += amount); - Ok(LAST_ID.with(|lid| { - let x = *lid.borrow(); - lid.replace(x + 1); - x - })) - } - fn check_payment(id: Self::Id) -> PaymentStatus { - STATUS.with(|s| { - s.borrow() - .get(&id) - .cloned() - .unwrap_or(PaymentStatus::Unknown) - }) - } - #[cfg(feature = "runtime-benchmarks")] - fn ensure_successful(_: &Self::Beneficiary, _: Self::AssetKind, _: Self::Balance) {} - #[cfg(feature = "runtime-benchmarks")] - fn ensure_concluded(id: Self::Id) { - set_status(id, PaymentStatus::Failure) - } -} - parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); @@ -161,11 +86,7 @@ impl frame_support::traits::EnsureOrigin for TestSpendOrigin { } #[cfg(feature = "runtime-benchmarks")] fn try_successful_origin() -> Result { - if TEST_SPEND_ORIGIN_TRY_SUCCESFUL_ORIGIN_ERR.with(|i| *i.borrow()) { - Err(()) - } else { - Ok(frame_system::RawOrigin::Root.into()) - } + Ok(frame_system::RawOrigin::Root.into()) } } @@ -195,35 +116,11 @@ impl Config for Test { type WeightInfo = (); type SpendFunds = (); type MaxApprovals = ConstU32<100>; - type SpendOrigin = TestSpendOrigin; - type AssetKind = u32; - type Beneficiary = u128; - type BeneficiaryLookup = IdentityLookup; - type Paymaster = TestPay; - type BalanceConverter = MulBy>; - type PayoutPeriod = SpendPayoutPeriod; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); -} - -pub struct ExtBuilder {} - -impl Default for ExtBuilder { - fn default() -> Self { - #[cfg(feature = "runtime-benchmarks")] - TEST_SPEND_ORIGIN_TRY_SUCCESFUL_ORIGIN_ERR.with(|i| *i.borrow_mut() = false); - - Self {} - } } +#[derive(Default)] +pub struct ExtBuilder; impl ExtBuilder { - #[cfg(feature = "runtime-benchmarks")] - pub fn spend_origin_succesful_origin_err(self) -> Self { - TEST_SPEND_ORIGIN_TRY_SUCCESFUL_ORIGIN_ERR.with(|i| *i.borrow_mut() = true); - self - } - pub fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::::default() .build_storage() @@ -243,14 +140,6 @@ impl ExtBuilder { } } -fn get_payment_id(i: SpendIndex) -> Option { - let spend = Spends::::get(i).expect("no spend"); - match spend.status { - PaymentState::Attempted { id } => Some(id), - _ => None, - } -} - #[test] fn genesis_config_works() { ExtBuilder::default().build().execute_with(|| { @@ -259,57 +148,6 @@ fn genesis_config_works() { }); } -#[test] -fn spend_local_origin_permissioning_works() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - Treasury::spend_local(RuntimeOrigin::signed(1), 1, 1), - BadOrigin - ); - assert_noop!( - Treasury::spend_local(RuntimeOrigin::signed(10), 6, 1), - Error::::InsufficientPermission - ); - assert_noop!( - Treasury::spend_local(RuntimeOrigin::signed(11), 11, 1), - Error::::InsufficientPermission - ); - assert_noop!( - Treasury::spend_local(RuntimeOrigin::signed(12), 21, 1), - Error::::InsufficientPermission - ); - assert_noop!( - Treasury::spend_local(RuntimeOrigin::signed(13), 51, 1), - Error::::InsufficientPermission - ); - }); -} - -#[docify::export] -#[test] -fn spend_local_origin_works() { - ExtBuilder::default().build().execute_with(|| { - // Check that accumulate works when we have Some value in Dummy already. - Balances::make_free_balance_be(&Treasury::account_id(), 101); - // approve spend of some amount to beneficiary `6`. - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(11), 10, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(12), 20, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(13), 50, 6)); - // free balance of `6` is zero, spend period has not passed. - >::on_initialize(1); - assert_eq!(Balances::free_balance(6), 0); - // free balance of `6` is `100`, spend period has passed. - >::on_initialize(2); - assert_eq!(Balances::free_balance(6), 100); - // `100` spent, `1` burned. - assert_eq!(Treasury::pot(), 0); - }); -} - #[test] fn minting_works() { ExtBuilder::default().build().execute_with(|| { @@ -674,477 +512,6 @@ fn max_approvals_limited() { }); } -#[test] -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_eq!(Treasury::approvals(), vec![0]); - assert_ok!(Treasury::remove_approval(RuntimeOrigin::root(), 0)); - assert_eq!(Treasury::approvals(), vec![]); - - assert_noop!( - Treasury::remove_approval(RuntimeOrigin::root(), 0), - Error::::ProposalNotApproved - ); - }); -} - -#[test] -fn spending_local_in_batch_respects_max_total() { - ExtBuilder::default().build().execute_with(|| { - // Respect the `max_total` for the given origin. - assert_ok!(RuntimeCall::from(UtilityCall::batch_all { - calls: vec![ - RuntimeCall::from(TreasuryCall::spend_local { - amount: 2, - beneficiary: 100 - }), - RuntimeCall::from(TreasuryCall::spend_local { - amount: 2, - beneficiary: 101 - }) - ] - }) - .dispatch(RuntimeOrigin::signed(10))); - - assert_err_ignore_postinfo!( - RuntimeCall::from(UtilityCall::batch_all { - calls: vec![ - RuntimeCall::from(TreasuryCall::spend_local { - amount: 2, - beneficiary: 100 - }), - RuntimeCall::from(TreasuryCall::spend_local { - amount: 4, - beneficiary: 101 - }) - ] - }) - .dispatch(RuntimeOrigin::signed(10)), - Error::::InsufficientPermission - ); - }) -} - -#[test] -fn spending_in_batch_respects_max_total() { - ExtBuilder::default().build().execute_with(|| { - // Respect the `max_total` for the given origin. - assert_ok!(RuntimeCall::from(UtilityCall::batch_all { - calls: vec![ - RuntimeCall::from(TreasuryCall::spend { - asset_kind: Box::new(1), - amount: 1, - beneficiary: Box::new(100), - valid_from: None, - }), - RuntimeCall::from(TreasuryCall::spend { - asset_kind: Box::new(1), - amount: 1, - beneficiary: Box::new(101), - valid_from: None, - }) - ] - }) - .dispatch(RuntimeOrigin::signed(10))); - - assert_err_ignore_postinfo!( - RuntimeCall::from(UtilityCall::batch_all { - calls: vec![ - RuntimeCall::from(TreasuryCall::spend { - asset_kind: Box::new(1), - amount: 2, - beneficiary: Box::new(100), - valid_from: None, - }), - RuntimeCall::from(TreasuryCall::spend { - asset_kind: Box::new(1), - amount: 2, - beneficiary: Box::new(101), - valid_from: None, - }) - ] - }) - .dispatch(RuntimeOrigin::signed(10)), - Error::::InsufficientPermission - ); - }) -} - -#[test] -fn spend_origin_works() { - ExtBuilder::default().build().execute_with(|| { - 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), - 2, - Box::new(6), - None - )); - assert_noop!( - Treasury::spend(RuntimeOrigin::signed(10), Box::new(1), 3, Box::new(6), None), - Error::::InsufficientPermission - ); - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(11), - Box::new(1), - 5, - Box::new(6), - None - )); - assert_noop!( - Treasury::spend(RuntimeOrigin::signed(11), Box::new(1), 6, Box::new(6), None), - Error::::InsufficientPermission - ); - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(12), - Box::new(1), - 10, - Box::new(6), - None - )); - assert_noop!( - Treasury::spend( - RuntimeOrigin::signed(12), - Box::new(1), - 11, - Box::new(6), - None - ), - Error::::InsufficientPermission - ); - - assert_eq!(SpendCount::::get(), 4); - assert_eq!(Spends::::iter().count(), 4); - }); -} - -#[test] -fn spend_works() { - ExtBuilder::default().build().execute_with(|| { - System::set_block_number(1); - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - - assert_eq!(SpendCount::::get(), 1); - assert_eq!( - Spends::::get(0).unwrap(), - SpendStatus { - asset_kind: 1, - amount: 2, - beneficiary: 6, - valid_from: 1, - expire_at: 6, - status: PaymentState::Pending, - } - ); - System::assert_last_event( - Event::::AssetSpendApproved { - index: 0, - asset_kind: 1, - amount: 2, - beneficiary: 6, - valid_from: 1, - expire_at: 6, - } - .into(), - ); - }); -} - -#[test] -fn spend_expires() { - ExtBuilder::default().build().execute_with(|| { - assert_eq!(::PayoutPeriod::get(), 5); - - // spend `0` expires in 5 blocks after the creating. - System::set_block_number(1); - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - System::set_block_number(6); - assert_noop!( - Treasury::payout(RuntimeOrigin::signed(1), 0), - Error::::SpendExpired - ); - - // spend cannot be approved since its already expired. - assert_noop!( - Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - Some(0) - ), - Error::::SpendExpired - ); - }); -} - -#[docify::export] -#[test] -fn spend_payout_works() { - ExtBuilder::default().build().execute_with(|| { - System::set_block_number(1); - // approve a `2` coins spend of asset `1` to beneficiary `6`, the spend valid from now. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - // payout the spend. - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 0)); - // beneficiary received `2` coins of asset `1`. - assert_eq!(paid(6, 1), 2); - assert_eq!(SpendCount::::get(), 1); - let payment_id = get_payment_id(0).expect("no payment attempt"); - System::assert_last_event( - Event::::Paid { - index: 0, - payment_id, - } - .into(), - ); - set_status(payment_id, PaymentStatus::Success); - // the payment succeed. - assert_ok!(Treasury::check_status(RuntimeOrigin::signed(1), 0)); - System::assert_last_event(Event::::SpendProcessed { index: 0 }.into()); - // cannot payout the same spend twice. - assert_noop!( - Treasury::payout(RuntimeOrigin::signed(1), 0), - Error::::InvalidIndex - ); - }); -} - -#[test] -fn payout_retry_works() { - ExtBuilder::default().build().execute_with(|| { - System::set_block_number(1); - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 0)); - assert_eq!(paid(6, 1), 2); - let payment_id = get_payment_id(0).expect("no payment attempt"); - // spend payment is failed - set_status(payment_id, PaymentStatus::Failure); - unpay(6, 1, 2); - // cannot payout a spend in the attempted state - assert_noop!( - Treasury::payout(RuntimeOrigin::signed(1), 0), - Error::::AlreadyAttempted - ); - // check status and update it to retry the payout again - assert_ok!(Treasury::check_status(RuntimeOrigin::signed(1), 0)); - System::assert_last_event( - Event::::PaymentFailed { - index: 0, - payment_id, - } - .into(), - ); - // the payout can be retried now - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 0)); - assert_eq!(paid(6, 1), 2); - }); -} - -#[test] -fn spend_valid_from_works() { - ExtBuilder::default().build().execute_with(|| { - assert_eq!(::PayoutPeriod::get(), 5); - System::set_block_number(1); - - // spend valid from block `2`. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - Some(2) - )); - assert_noop!( - Treasury::payout(RuntimeOrigin::signed(1), 0), - Error::::EarlyPayout - ); - System::set_block_number(2); - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 0)); - - System::set_block_number(5); - // spend approved even if `valid_from` in the past since the payout period has not passed. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - Some(4) - )); - // spend paid. - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 1)); - }); -} - -#[test] -fn void_spend_works() { - ExtBuilder::default().build().execute_with(|| { - System::set_block_number(1); - // spend cannot be voided if already attempted. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - Some(1) - )); - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 0)); - assert_noop!( - Treasury::void_spend(RuntimeOrigin::root(), 0), - Error::::AlreadyAttempted - ); - - // void spend. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - Some(10) - )); - assert_ok!(Treasury::void_spend(RuntimeOrigin::root(), 1)); - assert_eq!(Spends::::get(1), None); - }); -} - -#[test] -fn check_status_works() { - ExtBuilder::default().build().execute_with(|| { - assert_eq!(::PayoutPeriod::get(), 5); - System::set_block_number(1); - - // spend `0` expired and can be removed. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - System::set_block_number(7); - let info = Treasury::check_status(RuntimeOrigin::signed(1), 0).unwrap(); - assert_eq!(info.pays_fee, Pays::No); - System::assert_last_event(Event::::SpendProcessed { index: 0 }.into()); - - // spend `1` payment failed and expired hence can be removed. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - assert_noop!( - Treasury::check_status(RuntimeOrigin::signed(1), 1), - Error::::NotAttempted - ); - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 1)); - let payment_id = get_payment_id(1).expect("no payment attempt"); - set_status(payment_id, PaymentStatus::Failure); - // spend expired. - System::set_block_number(13); - let info = Treasury::check_status(RuntimeOrigin::signed(1), 1).unwrap(); - assert_eq!(info.pays_fee, Pays::Yes); - System::assert_last_event( - Event::::PaymentFailed { - index: 1, - payment_id, - } - .into(), - ); - let info = Treasury::check_status(RuntimeOrigin::signed(1), 1).unwrap(); - assert_eq!(info.pays_fee, Pays::No); - System::assert_last_event(Event::::SpendProcessed { index: 1 }.into()); - - // spend `2` payment succeed. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 2)); - let payment_id = get_payment_id(2).expect("no payment attempt"); - set_status(payment_id, PaymentStatus::Success); - let info = Treasury::check_status(RuntimeOrigin::signed(1), 2).unwrap(); - assert_eq!(info.pays_fee, Pays::No); - System::assert_last_event(Event::::SpendProcessed { index: 2 }.into()); - - // spend `3` payment in process. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 3)); - let payment_id = get_payment_id(3).expect("no payment attempt"); - set_status(payment_id, PaymentStatus::InProgress); - assert_noop!( - Treasury::check_status(RuntimeOrigin::signed(1), 3), - Error::::Inconclusive - ); - - // spend `4` removed since the payment status is unknown. - assert_ok!(Treasury::spend( - RuntimeOrigin::signed(10), - Box::new(1), - 2, - Box::new(6), - None - )); - assert_ok!(Treasury::payout(RuntimeOrigin::signed(1), 4)); - let payment_id = get_payment_id(4).expect("no payment attempt"); - set_status(payment_id, PaymentStatus::Unknown); - let info = Treasury::check_status(RuntimeOrigin::signed(1), 4).unwrap(); - assert_eq!(info.pays_fee, Pays::No); - System::assert_last_event(Event::::SpendProcessed { index: 4 }.into()); - }); -} - #[test] fn try_state_proposals_invariant_1_works() { ExtBuilder::default().build().execute_with(|| { @@ -1231,91 +598,3 @@ fn try_state_proposals_invariant_3_works() { ); }); } - -#[test] -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_eq!(Spends::::iter().count(), 1); - assert_eq!(SpendCount::::get(), 1); - // Check invariant 1 holds - assert!(SpendCount::::get() as usize >= Spends::::iter().count()); - // Break invariant 1 by decreasing `SpendCount` - SpendCount::::put(0); - // Invariant 1 should be violated - assert_eq!( - Treasury::do_try_state(), - Err(Other("Actual number of spends exceeds `SpendCount`.")) - ); - }); -} - -#[test] -fn try_state_spends_invariant_2_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_eq!(Spends::::iter().count(), 1); - let current_spend_count = SpendCount::::get(); - assert_eq!(current_spend_count, 1); - // Check invariant 2 holds - assert!( - Spends::::iter_keys() - .all(|spend_index| { - spend_index < current_spend_count - }) - ); - // Break invariant 2 by inserting the spend under key = 1 - let spend = Spends::::take(0).unwrap(); - Spends::::insert(1, spend); - // Invariant 2 should be violated - assert_eq!( - Treasury::do_try_state(), - Err(Other("`SpendCount` should by strictly greater than any SpendIndex used as a key for `Spends`.")) - ); - }); -} - -#[test] -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_eq!(Spends::::iter().count(), 1); - let current_spend_count = SpendCount::::get(); - assert_eq!(current_spend_count, 1); - // Check invariant 3 holds - assert!(Spends::::iter_values().all( - |SpendStatus { - valid_from, - expire_at, - .. - }| { valid_from < expire_at } - )); - // Break invariant 3 by reversing spend.expire_at and spend.valid_from - let spend = Spends::::take(0).unwrap(); - Spends::::insert( - 0, - SpendStatus { - valid_from: spend.expire_at, - expire_at: spend.valid_from, - ..spend - }, - ); - // Invariant 3 should be violated - assert_eq!( - Treasury::do_try_state(), - Err(Other("Spend cannot expire before it becomes valid.")) - ); - }); -} diff --git a/vendor/treasury/src/weights.rs b/vendor/treasury/src/weights.rs index 82277e2d28..f46b9435de 100644 --- a/vendor/treasury/src/weights.rs +++ b/vendor/treasury/src/weights.rs @@ -51,36 +51,15 @@ 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; - fn payout() -> Weight; - fn check_status() -> Weight; - fn void_spend() -> Weight; } /// Weights for `pallet_treasury` using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - /// Storage: `Treasury::ProposalCount` (r:1 w:1) - /// Proof: `Treasury::ProposalCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Approvals` (r:1 w:1) - /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Proposals` (r:0 w:1) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - fn spend_local() -> Weight { - // Proof Size summary in bytes: - // Measured: `76` - // Estimated: `1887` - // Minimum execution time: 11_910_000 picoseconds. - Weight::from_parts(12_681_000, 1887) - .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) @@ -123,17 +102,6 @@ impl WeightInfo for SubstrateWeight { .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 { - // Proof Size summary in bytes: - // Measured: `161` - // Estimated: `1887` - // Minimum execution time: 6_372_000 picoseconds. - Weight::from_parts(6_567_000, 1887) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } /// Storage: `Treasury::Deactivated` (r:1 w:1) /// Proof: `Treasury::Deactivated` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Treasury::Approvals` (r:1 w:1) @@ -159,79 +127,10 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(p.into()))) .saturating_add(Weight::from_parts(0, 5206).saturating_mul(p.into())) } - /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:0) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `Treasury::SpendCount` (r:1 w:1) - /// Proof: `Treasury::SpendCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Spends` (r:0 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - fn spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `140` - // Estimated: `3501` - // Minimum execution time: 14_233_000 picoseconds. - Weight::from_parts(14_842_000, 3501) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn payout() -> Weight { - // Proof Size summary in bytes: - // Measured: `709` - // Estimated: `6208` - // Minimum execution time: 58_857_000 picoseconds. - Weight::from_parts(61_291_000, 6208) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) - } - /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - fn check_status() -> Weight { - // Proof Size summary in bytes: - // Measured: `198` - // Estimated: `3538` - // Minimum execution time: 12_116_000 picoseconds. - Weight::from_parts(12_480_000, 3538) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - fn void_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `198` - // Estimated: `3538` - // Minimum execution time: 10_834_000 picoseconds. - Weight::from_parts(11_427_000, 3538) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } } // For backwards compatibility and tests. impl WeightInfo for () { - /// Storage: `Treasury::ProposalCount` (r:1 w:1) - /// Proof: `Treasury::ProposalCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Approvals` (r:1 w:1) - /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Proposals` (r:0 w:1) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - fn spend_local() -> Weight { - // Proof Size summary in bytes: - // Measured: `76` - // Estimated: `1887` - // Minimum execution time: 11_910_000 picoseconds. - Weight::from_parts(12_681_000, 1887) - .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) @@ -274,17 +173,6 @@ impl WeightInfo for () { .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 { - // Proof Size summary in bytes: - // Measured: `161` - // Estimated: `1887` - // Minimum execution time: 6_372_000 picoseconds. - Weight::from_parts(6_567_000, 1887) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } /// Storage: `Treasury::Deactivated` (r:1 w:1) /// Proof: `Treasury::Deactivated` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Treasury::Approvals` (r:1 w:1) @@ -310,58 +198,4 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(p.into()))) .saturating_add(Weight::from_parts(0, 5206).saturating_mul(p.into())) } - /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:0) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `Treasury::SpendCount` (r:1 w:1) - /// Proof: `Treasury::SpendCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Spends` (r:0 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - fn spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `140` - // Estimated: `3501` - // Minimum execution time: 14_233_000 picoseconds. - Weight::from_parts(14_842_000, 3501) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn payout() -> Weight { - // Proof Size summary in bytes: - // Measured: `709` - // Estimated: `6208` - // Minimum execution time: 58_857_000 picoseconds. - Weight::from_parts(61_291_000, 6208) - .saturating_add(RocksDbWeight::get().reads(5_u64)) - .saturating_add(RocksDbWeight::get().writes(5_u64)) - } - /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - fn check_status() -> Weight { - // Proof Size summary in bytes: - // Measured: `198` - // Estimated: `3538` - // Minimum execution time: 12_116_000 picoseconds. - Weight::from_parts(12_480_000, 3538) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - fn void_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `198` - // Estimated: `3538` - // Minimum execution time: 10_834_000 picoseconds. - Weight::from_parts(11_427_000, 3538) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } }