Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Pallets: Treasury spends various asset kinds #14434

Open
wants to merge 43 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 32 commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
2362c00
api draft
muharem Jun 21, 2023
36a74c1
separate asset kind and amount
muharem Jun 23, 2023
5843711
add amount to the spend
muharem Jun 23, 2023
7afa3c3
beneficiary lookup
muharem Jun 23, 2023
bfccac0
asset-rate rename asset_id to asset_kind
muharem Jun 25, 2023
5fb73fa
fex bench
muharem Jun 25, 2023
004534e
fix docs
muharem Jun 25, 2023
6ff5c5d
Revert "asset-rate rename asset_id to asset_kind"
muharem Jun 26, 2023
edec800
update docs
muharem Jun 26, 2023
ee7be40
clone identity
muharem Jun 26, 2023
7a623f5
payout, check_status dispatchables, tests
muharem Jun 28, 2023
7658928
spend bench
muharem Jun 29, 2023
38b029c
benches
muharem Jun 30, 2023
ab15fe6
remove dev mode
muharem Jun 30, 2023
d06e9f9
tests fix
muharem Jul 1, 2023
de45379
migrate to v2 benchmarks
muharem Jul 1, 2023
22e1c4f
benchmark helper for tests setup
muharem Jul 2, 2023
76d76af
benchmarks
muharem Jul 2, 2023
3f314cb
benchmarks bounds for parameters
muharem Jul 2, 2023
9eb50e2
benchmarks fix
muharem Jul 2, 2023
0f490e1
benchmarks fix
muharem Jul 3, 2023
6f78a7f
fix docs
muharem Jul 3, 2023
2ef382c
asset-rate pallet benchmarks asset kind factory
muharem Jul 4, 2023
9b21932
test nits
muharem Jul 4, 2023
aa83c6c
asset balance conversion changes
muharem Jul 4, 2023
727e309
fix tests
muharem Jul 4, 2023
c503805
Merge remote-tracking branch 'origin/master' into muharem-multi-asset…
muharem Jul 4, 2023
7c1d3f9
docs fixes
muharem Jul 7, 2023
6324f42
spend valid from, void spend
muharem Jul 8, 2023
51492ea
use reject origin
muharem Jul 8, 2023
84d0451
store expire_at
muharem Jul 8, 2023
dfe7502
docs according to guidelines
muharem Jul 10, 2023
2ea9379
valid_from and expiration constraints
muharem Jul 12, 2023
7c7790e
check status removes expired spends
muharem Jul 12, 2023
88ed340
Merge remote-tracking branch 'origin/master' into muharem-multi-asset…
muharem Jul 12, 2023
9ad15a2
Merge remote-tracking branch 'origin/master' into muharem-multi-asset…
muharem Jul 27, 2023
a78c770
Merge branch 'master' into muharem-multi-asset-treasury
muharem Jul 27, 2023
0d8ebcb
fixes after master merge
muharem Jul 27, 2023
147e918
update docify version
muharem Jul 28, 2023
0211314
Merge remote-tracking branch 'origin/master' into muharem-multi-asset…
Jul 30, 2023
c94585d
Merge remote-tracking branch 'origin/master' into muharem-multi-asset…
Aug 1, 2023
5c78c38
correct docs
muharem Aug 2, 2023
a300d5e
Merge remote-tracking branch 'origin/master' into muharem-multi-asset…
muharem Aug 2, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

13 changes: 12 additions & 1 deletion bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use frame_support::{
parameter_types,
traits::{
fungible::ItemOf,
tokens::{nonfungibles_v2::Inspect, GetSalary, PayFromAccount},
tokens::{nonfungibles_v2::Inspect, pay::PayAssetFromAccount, GetSalary, PayFromAccount},
AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU16, ConstU32, Currency, EitherOfDiverse,
EqualPrivilegeOnly, Everything, Imbalance, InstanceFilter, KeyOwnerProofSystem,
LockIdentifier, Nothing, OnUnbalanced, U128CurrencyToVote, WithdrawReasons,
Expand Down Expand Up @@ -1112,6 +1112,7 @@ parameter_types! {
pub const MaximumReasonLength: u32 = 300;
pub const MaxApprovals: u32 = 100;
pub const MaxBalance: Balance = Balance::max_value();
pub const SpendPayoutPeriod: BlockNumber = 30 * DAYS;
}

impl pallet_treasury::Config for Runtime {
Expand All @@ -1137,6 +1138,14 @@ impl pallet_treasury::Config for Runtime {
type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;
type MaxApprovals = MaxApprovals;
type SpendOrigin = EnsureWithSuccess<EnsureRoot<AccountId>, AccountId, MaxBalance>;
type AssetKind = u32;
type Beneficiary = AccountId;
type BeneficiaryLookup = Indices;
type Paymaster = PayAssetFromAccount<Assets, TreasuryAccount>;
type BalanceConverter = AssetRate;
type PayoutPeriod = SpendPayoutPeriod;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}

impl pallet_asset_rate::Config for Runtime {
Expand All @@ -1148,6 +1157,8 @@ impl pallet_asset_rate::Config for Runtime {
type AssetId = u32;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_asset_rate::weights::SubstrateWeight<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}

parameter_types! {
Expand Down
2 changes: 1 addition & 1 deletion frame/asset-rate/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ frame-support = { version = "4.0.0-dev", default-features = false, path = "../su
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-runtime = { version = "24.0.0", default-features = false, path = "../../primitives/runtime" }
sp-std = { version = "8.0.0", default-features = false, path = "../../primitives/std" }
sp-core = { version = "21.0.0", default-features = false, path = "../../primitives/core" }

[dev-dependencies]
pallet-balances = { version = "4.0.0-dev", path = "../balances" }
sp-core = { version = "21.0.0", path = "../../primitives/core" }
sp-io = { version = "23.0.0", path = "../../primitives/io" }

[features]
Expand Down
25 changes: 20 additions & 5 deletions frame/asset-rate/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,38 @@
use super::*;
use crate::{pallet as pallet_asset_rate, Pallet as AssetRate};

use codec::Encode;
use frame_benchmarking::v2::*;
use frame_support::assert_ok;
use frame_system::RawOrigin;
use sp_core::crypto::FromEntropy;

/// Trait describing the factory function for AssetKind parameter
pub trait AssetKindFactory<AssetKind> {
muharem marked this conversation as resolved.
Show resolved Hide resolved
fn create_asset_kind(seed: u32) -> AssetKind;
}
impl<AssetKind> AssetKindFactory<AssetKind> for ()
where
AssetKind: FromEntropy,
{
fn create_asset_kind(seed: u32) -> AssetKind {
AssetKind::from_entropy(&mut seed.encode().as_slice()).unwrap()
}
}

const ASSET_ID: u32 = 1;

fn default_conversion_rate() -> FixedU128 {
FixedU128::from_u32(1u32)
}

#[benchmarks(where <T as Config>::AssetId: From<u32>)]
#[benchmarks]
mod benchmarks {
use super::*;

#[benchmark]
fn create() -> Result<(), BenchmarkError> {
let asset_id: T::AssetId = ASSET_ID.into();
let asset_id: T::AssetId = T::BenchmarkHelper::create_asset_kind(ASSET_ID);
#[extrinsic_call]
_(RawOrigin::Root, asset_id.clone(), default_conversion_rate());

Expand All @@ -49,7 +64,7 @@ mod benchmarks {

#[benchmark]
fn update() -> Result<(), BenchmarkError> {
let asset_id: T::AssetId = ASSET_ID.into();
let asset_id: T::AssetId = T::BenchmarkHelper::create_asset_kind(ASSET_ID);
assert_ok!(AssetRate::<T>::create(
RawOrigin::Root.into(),
asset_id.clone(),
Expand All @@ -68,10 +83,10 @@ mod benchmarks {

#[benchmark]
fn remove() -> Result<(), BenchmarkError> {
let asset_id: T::AssetId = ASSET_ID.into();
let asset_id: T::AssetId = T::BenchmarkHelper::create_asset_kind(ASSET_ID);
assert_ok!(AssetRate::<T>::create(
RawOrigin::Root.into(),
ASSET_ID.into(),
asset_id.clone(),
default_conversion_rate()
));

Expand Down
13 changes: 12 additions & 1 deletion frame/asset-rate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,14 @@ pub use pallet::*;
pub use weights::WeightInfo;

#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub mod weights;
#[cfg(feature = "runtime-benchmarks")]
pub use benchmarking::AssetKindFactory;

// Type alias for `frame_system`'s account id.
type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
Expand Down Expand Up @@ -117,6 +119,10 @@ pub mod pallet {

/// The identifier for the class of asset.
type AssetId: frame_support::traits::tokens::AssetId;

/// Helper type for benchmarks.
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper: crate::AssetKindFactory<Self::AssetId>;
}

/// Maps an asset to its fixed point representation in the native balance.
Expand Down Expand Up @@ -236,4 +242,9 @@ where
.ok_or(pallet::Error::<T>::UnknownAssetId.into())?;
Ok(rate.saturating_mul_int(balance))
}
/// Set a conversion rate to `1` for the `asset_id`.
#[cfg(feature = "runtime-benchmarks")]
fn ensure_successful(asset_id: AssetIdOf<T>) {
pallet::ConversionRateToNative::<T>::set(asset_id.clone(), Some(1.into()));
}
}
2 changes: 2 additions & 0 deletions frame/asset-rate/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ impl pallet_asset_rate::Config for Test {
type Balance = u64;
type Currency = Balances;
type AssetId = u32;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}

// Build genesis storage according to the mock runtime.
Expand Down
23 changes: 22 additions & 1 deletion frame/bounties/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ use frame_support::{
assert_noop, assert_ok,
pallet_prelude::GenesisBuild,
parameter_types,
traits::{ConstU32, ConstU64, OnInitialize},
traits::{
tokens::{PayFromAccount, UnityAssetBalanceConversion},
ConstU32, ConstU64, OnInitialize,
},
PalletId,
};

Expand Down Expand Up @@ -112,6 +115,8 @@ parameter_types! {
pub const TreasuryPalletId2: PalletId = PalletId(*b"py/trsr2");
pub static SpendLimit: Balance = u64::MAX;
pub static SpendLimit1: Balance = u64::MAX;
pub TreasuryAccount: u128 = Treasury::account_id();
pub TreasuryAccount1: u128 = Treasury1::account_id();
}

impl pallet_treasury::Config for Test {
Expand All @@ -131,6 +136,14 @@ impl pallet_treasury::Config for Test {
type SpendFunds = Bounties;
type MaxApprovals = ConstU32<100>;
type SpendOrigin = frame_system::EnsureRootWithSuccess<Self::AccountId, SpendLimit>;
type AssetKind = ();
type Beneficiary = Self::AccountId;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
type BalanceConverter = UnityAssetBalanceConversion;
type PayoutPeriod = ConstU64<10>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}

impl pallet_treasury::Config<Instance1> for Test {
Expand All @@ -150,6 +163,14 @@ impl pallet_treasury::Config<Instance1> for Test {
type SpendFunds = Bounties1;
type MaxApprovals = ConstU32<100>;
type SpendOrigin = frame_system::EnsureRootWithSuccess<Self::AccountId, SpendLimit1>;
type AssetKind = ();
type Beneficiary = Self::AccountId;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
type Paymaster = PayFromAccount<Balances, TreasuryAccount1>;
type BalanceConverter = UnityAssetBalanceConversion;
type PayoutPeriod = ConstU64<10>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}

parameter_types! {
Expand Down
14 changes: 13 additions & 1 deletion frame/child-bounties/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ use frame_support::{
assert_noop, assert_ok,
pallet_prelude::GenesisBuild,
parameter_types,
traits::{ConstU32, ConstU64, OnInitialize},
traits::{
tokens::{PayFromAccount, UnityAssetBalanceConversion},
ConstU32, ConstU64, OnInitialize,
},
weights::Weight,
PalletId,
};
Expand Down Expand Up @@ -112,6 +115,7 @@ 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();
pub const SpendLimit: Balance = u64::MAX;
}

Expand All @@ -132,6 +136,14 @@ impl pallet_treasury::Config for Test {
type SpendFunds = Bounties;
type MaxApprovals = ConstU32<100>;
type SpendOrigin = frame_system::EnsureRootWithSuccess<Self::AccountId, SpendLimit>;
type AssetKind = ();
type Beneficiary = Self::AccountId;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
type BalanceConverter = UnityAssetBalanceConversion;
type PayoutPeriod = ConstU64<10>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}
parameter_types! {
// This will be 50% of the bounty fee.
Expand Down
3 changes: 2 additions & 1 deletion frame/support/src/traits/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub mod pay;
pub use misc::{
AssetId, Balance, BalanceStatus, ConversionFromAssetBalance, ConversionToAssetBalance,
ConvertRank, DepositConsequence, ExistenceRequirement, Fortitude, GetSalary, Locker, Precision,
Preservation, Provenance, Restriction, WithdrawConsequence, WithdrawReasons,
Preservation, Provenance, Restriction, UnityAssetBalanceConversion, WithdrawConsequence,
WithdrawReasons,
};
pub use pay::{Pay, PayFromAccount, PaymentStatus};
20 changes: 20 additions & 0 deletions frame/support/src/traits/tokens/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,26 @@ pub trait ConversionFromAssetBalance<AssetBalance, AssetId, OutBalance> {
balance: AssetBalance,
asset_id: AssetId,
) -> Result<OutBalance, Self::Error>;
/// Ensures that a conversion for the `asset_id` will be successful if done immediately after
/// this call.
#[cfg(feature = "runtime-benchmarks")]
fn ensure_successful(asset_id: AssetId);
}

/// Implements the [`ConversionFromAssetBalance`] enabling a 1:1 conversion of the asset balance
/// value to the balance.
pub struct UnityAssetBalanceConversion;
impl<AssetBalance, AssetId, OutBalance>
ConversionFromAssetBalance<AssetBalance, AssetId, OutBalance> for UnityAssetBalanceConversion
where
AssetBalance: Into<OutBalance>,
{
type Error = ();
fn from_asset_balance(balance: AssetBalance, _: AssetId) -> Result<OutBalance, Self::Error> {
Ok(balance.into())
}
#[cfg(feature = "runtime-benchmarks")]
fn ensure_successful(_: AssetId) {}
}

/// Trait to handle NFT locking mechanism to ensure interactions with the asset can be implemented
Expand Down
35 changes: 34 additions & 1 deletion frame/support/src/traits/tokens/pay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use sp_core::{RuntimeDebug, TypedGet};
use sp_runtime::DispatchError;
use sp_std::fmt::Debug;

use super::{fungible, Balance, Preservation::Expendable};
use super::{fungible, fungibles, Balance, Preservation::Expendable};

/// Can be implemented by `PayFromAccount` using a `fungible` impl, but can also be implemented with
/// XCM/MultiAsset and made generic over assets.
Expand Down Expand Up @@ -107,3 +107,36 @@ impl<A: TypedGet, F: fungible::Mutate<A::Type>> Pay for PayFromAccount<F, A> {
#[cfg(feature = "runtime-benchmarks")]
fn ensure_concluded(_: Self::Id) {}
}

/// Simple implementation of `Pay` for assets which makes a payment from a "pot" - i.e. a single
/// account.
pub struct PayAssetFromAccount<F, A>(sp_std::marker::PhantomData<(F, A)>);
impl<A, F> frame_support::traits::tokens::Pay for PayAssetFromAccount<F, A>
where
A: TypedGet,
F: fungibles::Mutate<A::Type> + fungibles::Create<A::Type>,
{
type Balance = F::Balance;
type Beneficiary = A::Type;
type AssetKind = F::AssetId;
type Id = ();
type Error = DispatchError;
fn pay(
who: &Self::Beneficiary,
asset: Self::AssetKind,
amount: Self::Balance,
) -> Result<Self::Id, Self::Error> {
<F as fungibles::Mutate<_>>::transfer(asset, &A::get(), who, amount, Expendable)?;
Ok(())
}
fn check_payment(_: ()) -> PaymentStatus {
PaymentStatus::Success
}
#[cfg(feature = "runtime-benchmarks")]
fn ensure_successful(_: &Self::Beneficiary, asset: Self::AssetKind, amount: Self::Balance) {
<F as fungibles::Create<_>>::create(asset.clone(), A::get(), true, amount).unwrap();
<F as fungibles::Mutate<_>>::mint_into(asset, &A::get(), amount).unwrap();
}
#[cfg(feature = "runtime-benchmarks")]
fn ensure_concluded(_: Self::Id) {}
}
24 changes: 23 additions & 1 deletion frame/tips/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ use frame_support::{
pallet_prelude::GenesisBuild,
parameter_types,
storage::StoragePrefixedMap,
traits::{ConstU32, ConstU64, SortedMembers, StorageVersion},
traits::{
tokens::{PayFromAccount, UnityAssetBalanceConversion},
ConstU32, ConstU64, SortedMembers, StorageVersion,
},
PalletId,
};

Expand Down Expand Up @@ -131,7 +134,10 @@ parameter_types! {
pub const Burn: Permill = Permill::from_percent(50);
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
pub const TreasuryPalletId2: PalletId = PalletId(*b"py/trsr2");
pub TreasuryAccount: u128 = Treasury::account_id();
pub TreasuryAccount1: u128 = Treasury1::account_id();
}

impl pallet_treasury::Config for Test {
type PalletId = TreasuryPalletId;
type Currency = pallet_balances::Pallet<Test>;
Expand All @@ -149,6 +155,14 @@ impl pallet_treasury::Config for Test {
type SpendFunds = ();
type MaxApprovals = ConstU32<100>;
type SpendOrigin = frame_support::traits::NeverEnsureOrigin<u64>;
type AssetKind = ();
type Beneficiary = Self::AccountId;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
type BalanceConverter = UnityAssetBalanceConversion;
type PayoutPeriod = ConstU64<10>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}

impl pallet_treasury::Config<Instance1> for Test {
Expand All @@ -168,6 +182,14 @@ impl pallet_treasury::Config<Instance1> for Test {
type SpendFunds = ();
type MaxApprovals = ConstU32<100>;
type SpendOrigin = frame_support::traits::NeverEnsureOrigin<u64>;
type AssetKind = ();
type Beneficiary = Self::AccountId;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
type Paymaster = PayFromAccount<Balances, TreasuryAccount1>;
type BalanceConverter = UnityAssetBalanceConversion;
type PayoutPeriod = ConstU64<10>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}

parameter_types! {
Expand Down
Loading