From 979cc5419679a77929453f909f0c1dd489ed058a Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 23 May 2022 16:12:42 +0800 Subject: [PATCH 01/49] fee distributionn framework --- Cargo.lock | 20 +++ modules/fees/Cargo.toml | 44 +++++++ modules/fees/src/lib.rs | 238 ++++++++++++++++++++++++++++++++++++ modules/fees/src/weights.rs | 102 ++++++++++++++++ modules/support/src/lib.rs | 4 + primitives/src/lib.rs | 11 ++ 6 files changed, 419 insertions(+) create mode 100644 modules/fees/Cargo.toml create mode 100644 modules/fees/src/lib.rs create mode 100644 modules/fees/src/weights.rs diff --git a/Cargo.lock b/Cargo.lock index 84f6704156..569eab3532 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6211,6 +6211,26 @@ dependencies = [ "sp-runtime", ] +[[package]] +name = "module-fees" +version = "2.6.3" +dependencies = [ + "acala-primitives", + "frame-support", + "frame-system", + "module-support", + "orml-traits", + "pallet-balances", + "parity-scale-codec", + "paste", + "scale-info", + "serde", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", +] + [[package]] name = "module-homa" version = "2.6.3" diff --git a/modules/fees/Cargo.toml b/modules/fees/Cargo.toml new file mode 100644 index 0000000000..ddb50da713 --- /dev/null +++ b/modules/fees/Cargo.toml @@ -0,0 +1,44 @@ +[package] +name = "module-fees" +version = "2.6.3" +authors = ["Acala Developers"] +edition = "2021" + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } +scale-info = { version = "2.1", default-features = false, features = ["derive"] } +serde = { version = "1.0.136", optional = true } + +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } + +orml-traits = { package = "orml-traits", path = "../../orml/traits", default-features = false } + +support = { package = "module-support", path = "../support", default-features = false } +primitives = { package = "acala-primitives", path = "../../primitives", default-features = false } + +paste = "1.0" + +[dev-dependencies] +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19" } + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "scale-info/std", + "sp-runtime/std", + "frame-support/std", + "frame-system/std", + "sp-core/std", + "sp-std/std", + "orml-traits/std", + "support/std", + "primitives/std", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs new file mode 100644 index 0000000000..97dbfeb54d --- /dev/null +++ b/modules/fees/src/lib.rs @@ -0,0 +1,238 @@ +// This file is part of Acala. + +// Copyright (C) 2020-2022 Acala Foundation. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! # Network Fee Distribution & Incentive Pools Module + +#![cfg_attr(not(feature = "std"), no_std)] +#![allow(clippy::unused_unit)] + +use frame_support::traits::Imbalance; +use frame_support::{ + pallet_prelude::*, + parameter_types, + traits::{Currency, OnUnbalanced}, + transactional, +}; +use frame_system::pallet_prelude::*; +use orml_traits::MultiCurrency; +use primitives::{Balance, CurrencyId, IncomeSource}; +use sp_runtime::{traits::Saturating, FixedPointNumber, Percent}; +use support::{FeeToTreasuryPool, Rate}; + +pub use module::*; + +// mod mock; +// mod tests; +pub mod weights; +pub use weights::WeightInfo; + +#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] +pub struct PoolPercent { + pool: AccountId, + rate: Rate, +} + +type PalletBalanceOf = <::Currency as Currency<::AccountId>>::Balance; + +pub type NegativeImbalanceOf = + <::Currency as Currency<::AccountId>>::NegativeImbalance; + +#[frame_support::pallet] +pub mod module { + use super::*; + + parameter_types! { + pub const MaxSize: u8 = 10; + } + + #[pallet::config] + pub trait Config: frame_system::Config { + type Event: From> + IsType<::Event>; + + type UpdateOrigin: EnsureOrigin; + + #[pallet::constant] + type NativeCurrencyId: Get; + + type Currency: Currency + + MultiCurrency; + + #[pallet::constant] + type NetworkTreasuryPoolAccount: Get; + + type OnUnbalanced: OnUnbalanced>; + + type WeightInfo: WeightInfo; + } + + #[pallet::error] + pub enum Error { + InvalidParams, + } + + #[pallet::event] + #[pallet::generate_deposit(pub(crate) fn deposit_event)] + pub enum Event { + IncomeFeeSet { + income: IncomeSource, + pools: Vec>, + }, + TreasuryPoolSet { + treasury: T::AccountId, + pools: Vec>, + }, + } + + /// Income fee source mapping to different treasury pools. + /// + /// IncomeToTreasuries: map IncomeSource => Vec + #[pallet::storage] + #[pallet::getter(fn income_to_treasuries)] + pub type IncomeToTreasuries = + StorageMap<_, Twox64Concat, IncomeSource, BoundedVec, MaxSize>, ValueQuery>; + + /// Treasury pool allocation mapping to different income pools. + /// + /// TreasuryToIncentives: map AccountId => Vec + #[pallet::storage] + #[pallet::getter(fn treasury_to_incentives)] + pub type TreasuryToIncentives = + StorageMap<_, Twox64Concat, T::AccountId, BoundedVec, MaxSize>, ValueQuery>; + + #[pallet::pallet] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::hooks] + impl Hooks for Pallet { + fn on_initialize(_: T::BlockNumber) -> Weight { + // TODO: trigger transfer from treasury pool to incentive pools + ::WeightInfo::on_initialize() + } + } + + #[pallet::call] + impl Pallet { + /// Set how much percentage of income fee go to different treasury pools + #[pallet::weight(10_000)] + #[transactional] + pub fn set_income_fee( + origin: OriginFor, + income_source: IncomeSource, + treasury_pool_rates: Vec<(T::AccountId, u32)>, + ) -> DispatchResult { + T::UpdateOrigin::ensure_origin(origin)?; + Self::do_set_treasury_rate(income_source, treasury_pool_rates) + } + + /// Set how much percentage of treasury pool go to different incentive pools + #[pallet::weight(10_000)] + #[transactional] + pub fn set_treasury_pool( + origin: OriginFor, + treasury: T::AccountId, + incentive_pools: Vec<(T::AccountId, u32)>, + ) -> DispatchResult { + T::UpdateOrigin::ensure_origin(origin)?; + Self::do_set_incentive_rate(treasury, incentive_pools) + } + + /// Force transfer balance from treasury pool to incentive pool. + #[pallet::weight(10_000)] + #[transactional] + pub fn force_transfer_to_incentive( + origin: OriginFor, + _treasury: T::AccountId, + _incentive: T::AccountId, + ) -> DispatchResult { + T::UpdateOrigin::ensure_origin(origin)?; + + Ok(()) + } + } +} + +impl Pallet { + fn do_set_treasury_rate( + income_source: IncomeSource, + treasury_pool_rates: Vec<(T::AccountId, u32)>, + ) -> DispatchResult { + let pools: Vec> = treasury_pool_rates + .into_iter() + .map(|p| { + let rate = Rate::saturating_from_rational(p.1, 100); + PoolPercent { pool: p.0, rate } + }) + .collect(); + + IncomeToTreasuries::::try_mutate(income_source, |rates| -> DispatchResult { + let percents: BoundedVec, MaxSize> = + pools.clone().try_into().map_err(|_| Error::::InvalidParams)?; + *rates = percents; + Ok(()) + })?; + + Self::deposit_event(Event::IncomeFeeSet { + income: income_source, + pools, + }); + Ok(()) + } + + fn do_set_incentive_rate(treasury: T::AccountId, incentive_pools: Vec<(T::AccountId, u32)>) -> DispatchResult { + let pools: Vec> = incentive_pools + .into_iter() + .map(|p| { + let rate = Rate::saturating_from_rational(p.1, 100); + PoolPercent { pool: p.0, rate } + }) + .collect(); + + TreasuryToIncentives::::try_mutate(&treasury, |rates| -> DispatchResult { + let percents: BoundedVec, MaxSize> = + pools.clone().try_into().map_err(|_| Error::::InvalidParams)?; + *rates = percents; + Ok(()) + })?; + + Self::deposit_event(Event::TreasuryPoolSet { treasury, pools }); + Ok(()) + } +} + +impl FeeToTreasuryPool for Pallet { + // TODO: maybe use `Happened<(AccountId,CurrencyId,Balance)>` instead of new trait? + fn on_fee_changed(account_id: T::AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult { + // TODO: use `IncomeSource` to determine destination + T::Currency::deposit(currency_id, &account_id, amount) + } +} + +impl OnUnbalanced> for Pallet { + fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { + if let Some(mut fees) = fees_then_tips.next() { + if let Some(tips) = fees_then_tips.next() { + tips.merge_into(&mut fees); + } + + // Must resolve into existing but better to be safe. + let _ = T::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), fees); + // TODO: deposit event + } + } +} diff --git a/modules/fees/src/weights.rs b/modules/fees/src/weights.rs new file mode 100644 index 0000000000..ac365ab82b --- /dev/null +++ b/modules/fees/src/weights.rs @@ -0,0 +1,102 @@ +// This file is part of Acala. + +// Copyright (C) 2020-2022 Acala Foundation. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Autogenerated weights for module_asset_registry +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-03-24, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 + +// Executed Command: +// target/release/acala +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=module_asset_registry +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./modules/asset-registry/src/weights.rs +// --template=./templates/module-weight-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for module_asset_registry. +pub trait WeightInfo { + fn on_initialize() -> Weight; + fn set_income_fee() -> Weight; + fn set_treasury_pool() -> Weight; + fn force_transfer_to_incentive() -> Weight; +} + +/// Weights for module_fees using the Acala node and recommended hardware. +pub struct AcalaWeight(PhantomData); +impl WeightInfo for AcalaWeight { + fn on_initialize() -> Weight { + (6_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + } + + fn set_income_fee() -> Weight { + (21_475_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + fn set_treasury_pool() -> Weight { + (21_475_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + fn force_transfer_to_incentive() -> Weight { + (21_475_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } +} + +// For backwards compatibility and tests +impl WeightInfo for () { + fn on_initialize() -> Weight { + (6_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + } + + fn set_income_fee() -> Weight { + (21_475_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + fn set_treasury_pool() -> Weight { + (21_475_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + fn force_transfer_to_incentive() -> Weight { + (21_475_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } +} diff --git a/modules/support/src/lib.rs b/modules/support/src/lib.rs index 3e39ab512c..bc17aa636c 100644 --- a/modules/support/src/lib.rs +++ b/modules/support/src/lib.rs @@ -105,6 +105,10 @@ pub trait TransactionPayment { fn apply_multiplier_to_fee(fee: Balance, multiplier: Option) -> Balance; } +pub trait FeeToTreasuryPool { + fn on_fee_changed(account_id: AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult; +} + /// Used to interface with the Compound's Cash module pub trait CompoundCashTrait { fn set_future_yield(next_cash_yield: Balance, yield_index: u128, timestamp_effective: Moment) -> DispatchResult; diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 9ef1ea2d29..395f0e0400 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -184,6 +184,17 @@ pub enum ReserveIdentifier { Count, } +#[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, TypeInfo)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub enum IncomeSource { + TxFee, + XcmFee, + DexSwapFee, + HonzonStabilityFee, + HonzonLiquidationFee, + HomaStakingRewardFee, +} + pub type CashYieldIndex = u128; /// Convert any type that implements Into into byte representation ([u8, 32]) From 5e67844d81a0b94d067bc8b3db40bdc164eb879d Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 24 May 2022 10:18:57 +0800 Subject: [PATCH 02/49] do_set_rate --- Cargo.lock | 1 + modules/fees/src/lib.rs | 23 ++++++++++++++--------- runtime/mandala/Cargo.toml | 2 ++ runtime/mandala/src/lib.rs | 10 ++++++++++ 4 files changed, 27 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 569eab3532..7b560ffa1f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5514,6 +5514,7 @@ dependencies = [ "module-evm-bridge", "module-evm-rpc-runtime-api", "module-evm-utility", + "module-fees", "module-homa", "module-honzon", "module-idle-scheduler", diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 97dbfeb54d..222a9d2b7c 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -31,7 +31,8 @@ use frame_support::{ use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; use primitives::{Balance, CurrencyId, IncomeSource}; -use sp_runtime::{traits::Saturating, FixedPointNumber, Percent}; +use sp_runtime::FixedPointNumber; +use sp_std::vec::Vec; use support::{FeeToTreasuryPool, Rate}; pub use module::*; @@ -47,7 +48,8 @@ pub struct PoolPercent { rate: Rate, } -type PalletBalanceOf = <::Currency as Currency<::AccountId>>::Balance; +// type PalletBalanceOf = <::Currency as Currency<::AccountId>>::Balance; pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; @@ -66,16 +68,17 @@ pub mod module { type UpdateOrigin: EnsureOrigin; - #[pallet::constant] - type NativeCurrencyId: Get; + // #[pallet::constant] + // type NativeCurrencyId: Get; + + type Currency: Currency; - type Currency: Currency - + MultiCurrency; + type Currencies: MultiCurrency; #[pallet::constant] type NetworkTreasuryPoolAccount: Get; - type OnUnbalanced: OnUnbalanced>; + // type OnUnbalanced: OnUnbalanced>; type WeightInfo: WeightInfo; } @@ -137,6 +140,7 @@ pub mod module { treasury_pool_rates: Vec<(T::AccountId, u32)>, ) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; + Self::do_set_treasury_rate(income_source, treasury_pool_rates) } @@ -149,10 +153,11 @@ pub mod module { incentive_pools: Vec<(T::AccountId, u32)>, ) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; + Self::do_set_incentive_rate(treasury, incentive_pools) } - /// Force transfer balance from treasury pool to incentive pool. + /// Force transfer token from treasury pool to incentive pool. #[pallet::weight(10_000)] #[transactional] pub fn force_transfer_to_incentive( @@ -219,7 +224,7 @@ impl FeeToTreasuryPool` instead of new trait? fn on_fee_changed(account_id: T::AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult { // TODO: use `IncomeSource` to determine destination - T::Currency::deposit(currency_id, &account_id, amount) + T::Currencies::deposit(currency_id, &account_id, amount) } } diff --git a/runtime/mandala/Cargo.toml b/runtime/mandala/Cargo.toml index 754aea24a4..8177b9fd38 100644 --- a/runtime/mandala/Cargo.toml +++ b/runtime/mandala/Cargo.toml @@ -127,6 +127,7 @@ module-session-manager = { path = "../../modules/session-manager", default-featu module-relaychain = { path = "../../modules/relaychain", default-features = false, features = ["polkadot"]} module-idle-scheduler = { path = "../../modules/idle-scheduler", default-features = false } module-aggregated-dex = { path = "../../modules/aggregated-dex", default-features = false } +module-fees = { path = "../../modules/fees", default-features = false } primitives = { package = "acala-primitives", path = "../../primitives", default-features = false } runtime-common = { path = "../common", default-features = false } @@ -263,6 +264,7 @@ std = [ "module-relaychain/std", "module-idle-scheduler/std", "module-aggregated-dex/std", + "module-fees/std", "primitives/std", "runtime-common/std", diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index ed59aecf42..4a3e73fbad 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1756,6 +1756,15 @@ impl module_idle_scheduler::Config for Runtime { type DisableBlockThreshold = ConstU32<6>; } +impl module_fees::Config for Runtime { + type Event = Event; + type WeightInfo = (); + type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; + type Currency = Balances; + type Currencies = Currencies; + type NetworkTreasuryPoolAccount = TreasuryAccount; +} + impl cumulus_pallet_aura_ext::Config for Runtime {} #[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug)] @@ -1925,6 +1934,7 @@ construct_runtime!( Currencies: module_currencies = 12, Vesting: orml_vesting = 13, TransactionPayment: module_transaction_payment = 14, + Fees: module_fees = 15, // Treasury Treasury: pallet_treasury = 20, From 143de0ab2b5d270c1e92a9885a85c3de7902f032 Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 24 May 2022 15:36:59 +0800 Subject: [PATCH 03/49] xcm fee --- Cargo.lock | 1 + modules/fees/src/lib.rs | 5 +- modules/support/src/lib.rs | 2 +- runtime/common/src/lib.rs | 25 ++++++++- runtime/karura/Cargo.toml | 2 + .../karura/src/integration_tests_config.rs | 24 ++++----- runtime/karura/src/lib.rs | 10 ++++ runtime/karura/src/xcm_config.rs | 52 +++++++------------ runtime/mandala/src/lib.rs | 23 +------- runtime/mandala/src/xcm_config.rs | 36 ++++--------- 10 files changed, 82 insertions(+), 98 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7b560ffa1f..d190f6bb4f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4513,6 +4513,7 @@ dependencies = [ "module-evm-accounts", "module-evm-bridge", "module-evm-rpc-runtime-api", + "module-fees", "module-homa", "module-honzon", "module-honzon-bridge", diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 222a9d2b7c..a853dbfbcc 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -222,12 +222,13 @@ impl Pallet { impl FeeToTreasuryPool for Pallet { // TODO: maybe use `Happened<(AccountId,CurrencyId,Balance)>` instead of new trait? - fn on_fee_changed(account_id: T::AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult { + fn on_fee_changed(account_id: &T::AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult { // TODO: use `IncomeSource` to determine destination - T::Currencies::deposit(currency_id, &account_id, amount) + T::Currencies::deposit(currency_id, account_id, amount) } } +// Transaction payment module `OnTransactionPayment` distribution transaction fee impl OnUnbalanced> for Pallet { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(mut fees) = fees_then_tips.next() { diff --git a/modules/support/src/lib.rs b/modules/support/src/lib.rs index bc17aa636c..260d6453d6 100644 --- a/modules/support/src/lib.rs +++ b/modules/support/src/lib.rs @@ -106,7 +106,7 @@ pub trait TransactionPayment { } pub trait FeeToTreasuryPool { - fn on_fee_changed(account_id: AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult; + fn on_fee_changed(account_id: &AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult; } /// Used to interface with the Compound's Cash module diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index a43e67d336..9a53f56d8b 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -32,7 +32,7 @@ use frame_support::{ RuntimeDebug, }; use frame_system::{limits, EnsureRoot}; -pub use module_support::{ExchangeRate, PrecompileCallerFilter, Price, Rate, Ratio}; +pub use module_support::{ExchangeRate, FeeToTreasuryPool, PrecompileCallerFilter, Price, Rate, Ratio}; use primitives::{evm::is_system_contract, Balance, CurrencyId, Nonce}; use scale_info::TypeInfo; use sp_core::{Bytes, H160}; @@ -346,6 +346,29 @@ impl Default for ProxyType { } } +pub struct XcmFeeToTreasury(PhantomData<(T, C, F)>); +impl TakeRevenue for XcmFeeToTreasury +where + T: Get, + C: Convert>, + F: FeeToTreasuryPool, +{ + fn take_revenue(revenue: MultiAsset) { + if let MultiAsset { + id: Concrete(location), + fun: Fungible(amount), + } = revenue + { + if let Some(currency_id) = C::convert(location) { + // Ensure given treasury account have ed requirement for native asset, but don't need + // ed requirement for cross-chain asset because it's one of whitelist accounts. + // Ignore the result. + let _ = F::on_fee_changed(&T::get(), currency_id, amount); + } + } + } +} + /// `DropAssets` implementation support asset amount lower thant ED handled by `TakeRevenue`. /// /// parameters type: diff --git a/runtime/karura/Cargo.toml b/runtime/karura/Cargo.toml index cd4ebdd9bd..e8860788b4 100644 --- a/runtime/karura/Cargo.toml +++ b/runtime/karura/Cargo.toml @@ -120,6 +120,7 @@ module-relaychain = { path = "../../modules/relaychain", default-features = fals module-idle-scheduler = { path = "../../modules/idle-scheduler", default-features = false } module-honzon-bridge = { path = "../../modules/honzon-bridge", default-features = false } module-aggregated-dex = { path = "../../modules/aggregated-dex", default-features = false } +module-fees = { path = "../../modules/fees", default-features = false } primitives = { package = "acala-primitives", path = "../../primitives", default-features = false } runtime-common = { path = "../common", default-features = false } @@ -246,6 +247,7 @@ std = [ "module-idle-scheduler/std", "module-honzon-bridge/std", "module-aggregated-dex/std", + "module-fees/std", "primitives/std", "runtime-common/std", diff --git a/runtime/karura/src/integration_tests_config.rs b/runtime/karura/src/integration_tests_config.rs index 149e444ad6..7229802edf 100644 --- a/runtime/karura/src/integration_tests_config.rs +++ b/runtime/karura/src/integration_tests_config.rs @@ -34,16 +34,16 @@ parameter_types! { } pub type Trader = ( - TransactionFeePoolTrader, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfForeignAsset, + TransactionFeePoolTrader, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfForeignAsset, ); diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index c5ec94f1d3..e32706bea0 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1546,6 +1546,15 @@ impl module_idle_scheduler::Config for Runtime { type DisableBlockThreshold = ConstU32<6>; } +impl module_fees::Config for Runtime { + type Event = Event; + type WeightInfo = (); + type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; + type Currency = Balances; + type Currencies = Currencies; + type NetworkTreasuryPoolAccount = KaruraTreasuryAccount; +} + parameter_types! { pub WormholeAUSDCurrencyId: CurrencyId = CurrencyId::Erc20(EvmAddress::from(hex_literal::hex!["0000000000000000000100000000000000000001"])); pub const StableCoinCurrencyId: CurrencyId = KUSD; @@ -1646,6 +1655,7 @@ construct_runtime!( Currencies: module_currencies = 12, Vesting: orml_vesting = 13, TransactionPayment: module_transaction_payment = 14, + Fees: module_fees = 15, // Treasury Treasury: pallet_treasury = 20, diff --git a/runtime/karura/src/xcm_config.rs b/runtime/karura/src/xcm_config.rs index b7d76a5197..6a944e2b9b 100644 --- a/runtime/karura/src/xcm_config.rs +++ b/runtime/karura/src/xcm_config.rs @@ -19,8 +19,8 @@ use super::{ constants::{fee::*, parachains}, AccountId, AssetIdMapping, AssetIdMaps, Balance, Call, Convert, Currencies, CurrencyId, Event, ExistentialDeposits, - GetNativeCurrencyId, KaruraTreasuryAccount, NativeTokenExistentialDeposit, Origin, ParachainInfo, ParachainSystem, - PolkadotXcm, Runtime, UnknownTokens, XcmInterface, XcmpQueue, KAR, KUSD, LKSM, + Fees, GetNativeCurrencyId, KaruraTreasuryAccount, NativeTokenExistentialDeposit, Origin, ParachainInfo, + ParachainSystem, PolkadotXcm, Runtime, UnknownTokens, XcmInterface, XcmpQueue, KAR, KUSD, LKSM, }; use codec::{Decode, Encode}; pub use cumulus_primitives_core::ParaId; @@ -30,11 +30,11 @@ pub use frame_support::{ weights::Weight, }; use module_support::HomaSubAccountXcm; -use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key, MultiCurrency}; +use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key}; use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; -use runtime_common::{AcalaDropAssets, EnsureRootOrHalfGeneralCouncil}; +use runtime_common::{AcalaDropAssets, EnsureRootOrHalfGeneralCouncil, XcmFeeToTreasury}; use xcm::latest::prelude::*; pub use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -99,24 +99,6 @@ pub type Barrier = ( AllowSubscriptionsFrom, ); -pub struct ToTreasury; -impl TakeRevenue for ToTreasury { - fn take_revenue(revenue: MultiAsset) { - if let MultiAsset { - id: Concrete(location), - fun: Fungible(amount), - } = revenue - { - if let Some(currency_id) = CurrencyIdConvert::convert(location) { - // Ensure KaruraTreasuryAccount have ed requirement for native asset, but don't need - // ed requirement for cross-chain asset because it's one of whitelist accounts. - // Ignore the result. - let _ = Currencies::deposit(currency_id, &KaruraTreasuryAccount::get(), amount); - } - } - } -} - parameter_types! { // One XCM operation is 200_000_000 weight, cross-chain transfer ~= 2x of transfer. pub const UnitWeightCost: Weight = 200_000_000; @@ -190,19 +172,21 @@ parameter_types! { pub KarPerSecondAsBased: u128 = kar_per_second(); } +pub type XcmToTreasury = XcmFeeToTreasury; + #[cfg(not(feature = "integration-tests"))] pub type Trader = ( - TransactionFeePoolTrader, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfForeignAsset, + TransactionFeePoolTrader, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfForeignAsset, ); pub struct XcmConfig; @@ -222,7 +206,7 @@ impl xcm_executor::Config for XcmConfig { type ResponseHandler = PolkadotXcm; type AssetTrap = AcalaDropAssets< PolkadotXcm, - ToTreasury, + XcmToTreasury, CurrencyIdConvert, GetNativeCurrencyId, NativeTokenExistentialDeposit, diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 4a3e73fbad..a5b1d98435 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1202,34 +1202,13 @@ parameter_types! { pub const AlternativeFeeSurplus: Percent = Percent::from_percent(25); } -type NegativeImbalance = >::NegativeImbalance; -pub struct DealWithFees; -impl OnUnbalanced for DealWithFees { - fn on_unbalanceds(mut fees_then_tips: impl Iterator) { - if let Some(mut fees) = fees_then_tips.next() { - if let Some(tips) = fees_then_tips.next() { - tips.merge_into(&mut fees); - } - // for fees and tips, 80% to treasury, 20% to collator-selection pot. - let split = fees.ration(80, 20); - Treasury::on_unbalanced(split.0); - - Balances::resolve_creating(&CollatorSelection::account_id(), split.1); - // Due to performance consideration remove the event. - // let numeric_amount = split.1.peek(); - // let staking_pot = CollatorSelection::account_id(); - // System::deposit_event(pallet_balances::Event::Deposit(staking_pot, numeric_amount)); - } - } -} - impl module_transaction_payment::Config for Runtime { type Event = Event; type Call = Call; type NativeCurrencyId = GetNativeCurrencyId; type Currency = Balances; type MultiCurrency = Currencies; - type OnTransactionPayment = DealWithFees; + type OnTransactionPayment = Fees; type AlternativeFeeSwapDeposit = NativeTokenExistentialDeposit; type TransactionByteFee = TransactionByteFee; type OperationalFeeMultiplier = OperationalFeeMultiplier; diff --git a/runtime/mandala/src/xcm_config.rs b/runtime/mandala/src/xcm_config.rs index 36ea9babc5..e96c72476a 100644 --- a/runtime/mandala/src/xcm_config.rs +++ b/runtime/mandala/src/xcm_config.rs @@ -18,7 +18,7 @@ use super::{ constants::fee::*, AccountId, AssetIdMapping, AssetIdMaps, Balance, Call, Convert, Currencies, CurrencyId, Event, - ExistentialDeposits, FixedRateOfForeignAsset, GetNativeCurrencyId, NativeTokenExistentialDeposit, Origin, + ExistentialDeposits, Fees, FixedRateOfForeignAsset, GetNativeCurrencyId, NativeTokenExistentialDeposit, Origin, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, TransactionFeePoolTrader, TreasuryAccount, UnknownTokens, XcmpQueue, ACA, }; @@ -29,11 +29,11 @@ pub use frame_support::{ traits::{Everything, Get, Nothing}, weights::Weight, }; -use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key, MultiCurrency}; +use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key}; use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; -use runtime_common::{AcalaDropAssets, EnsureRootOrHalfGeneralCouncil}; +use runtime_common::{AcalaDropAssets, EnsureRootOrHalfGeneralCouncil, XcmFeeToTreasury}; use xcm::latest::prelude::*; pub use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -93,24 +93,6 @@ pub type Barrier = ( AllowSubscriptionsFrom, ); -pub struct ToTreasury; -impl TakeRevenue for ToTreasury { - fn take_revenue(revenue: MultiAsset) { - if let MultiAsset { - id: Concrete(location), - fun: Fungible(amount), - } = revenue - { - if let Some(currency_id) = CurrencyIdConvert::convert(location) { - // Ensure TreasuryAccount have ed requirement for native asset, but don't need - // ed requirement for cross-chain asset because it's one of whitelist accounts. - // Ignore the result. - let _ = Currencies::deposit(currency_id, &TreasuryAccount::get(), amount); - } - } - } -} - parameter_types! { // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate. pub UnitWeightCost: Weight = 1_000_000; @@ -127,11 +109,13 @@ parameter_types! { pub AcaPerSecondAsBased: u128 = aca_per_second(); } +type XcmToTreasury = XcmFeeToTreasury; + pub type Trader = ( - TransactionFeePoolTrader, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfForeignAsset, + TransactionFeePoolTrader, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfForeignAsset, ); pub struct XcmConfig; @@ -152,7 +136,7 @@ impl xcm_executor::Config for XcmConfig { type ResponseHandler = (); // Don't handle responses for now. type AssetTrap = AcalaDropAssets< PolkadotXcm, - ToTreasury, + XcmToTreasury, CurrencyIdConvert, GetNativeCurrencyId, NativeTokenExistentialDeposit, From f9fcd8cafb7426a6fbd98bdbe752706f4db13ed6 Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 24 May 2022 16:45:27 +0800 Subject: [PATCH 04/49] income source as paramter --- modules/fees/src/lib.rs | 33 +++++++++++++++++++++++---------- modules/support/src/lib.rs | 9 +++++++-- runtime/common/src/lib.rs | 4 ++-- 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index a853dbfbcc..df8deecce2 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -48,9 +48,6 @@ pub struct PoolPercent { rate: Rate, } -// type PalletBalanceOf = <::Currency as Currency<::AccountId>>::Balance; - pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; @@ -68,9 +65,6 @@ pub mod module { type UpdateOrigin: EnsureOrigin; - // #[pallet::constant] - // type NativeCurrencyId: Get; - type Currency: Currency; type Currencies: MultiCurrency; @@ -222,13 +216,32 @@ impl Pallet { impl FeeToTreasuryPool for Pallet { // TODO: maybe use `Happened<(AccountId,CurrencyId,Balance)>` instead of new trait? - fn on_fee_changed(account_id: &T::AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult { - // TODO: use `IncomeSource` to determine destination - T::Currencies::deposit(currency_id, account_id, amount) + fn on_fee_changed( + income: IncomeSource, + account_id: Option<&T::AccountId>, + currency_id: CurrencyId, + amount: Balance, + ) -> DispatchResult { + // TODO: remove manual account_id + if let Some(account_id) = account_id { + return T::Currencies::deposit(currency_id, account_id, amount); + } + + // use `IncomeSource` to determine destination + let pools: BoundedVec, MaxSize> = IncomeToTreasuries::::get(income); + pools.into_iter().for_each(|pool| { + let pool_account = pool.pool; + let rate = pool.rate; + let amount_to_pool = rate.saturating_mul_int(amount); + // TODO: deal with result + let _ = T::Currencies::deposit(currency_id, &pool_account, amount_to_pool); + }); + Ok(()) } } -// Transaction payment module `OnTransactionPayment` distribution transaction fee +/// Transaction payment module `OnTransactionPayment` distribution transaction fee. +/// The `IncomeSource` is `TxFee`. impl OnUnbalanced> for Pallet { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(mut fees) = fees_then_tips.next() { diff --git a/modules/support/src/lib.rs b/modules/support/src/lib.rs index 260d6453d6..b4f3aa8978 100644 --- a/modules/support/src/lib.rs +++ b/modules/support/src/lib.rs @@ -22,7 +22,7 @@ use codec::FullCodec; use frame_support::pallet_prelude::{DispatchClass, Pays, Weight}; -use primitives::{task::TaskResult, CurrencyId, Multiplier, ReserveIdentifier}; +use primitives::{task::TaskResult, CurrencyId, IncomeSource, Multiplier, ReserveIdentifier}; use sp_runtime::{ traits::CheckedDiv, transaction_validity::TransactionValidityError, DispatchError, DispatchResult, FixedU128, }; @@ -106,7 +106,12 @@ pub trait TransactionPayment { } pub trait FeeToTreasuryPool { - fn on_fee_changed(account_id: &AccountId, currency_id: CurrencyId, amount: Balance) -> DispatchResult; + fn on_fee_changed( + income: IncomeSource, + account_id: Option<&AccountId>, + currency_id: CurrencyId, + amount: Balance, + ) -> DispatchResult; } /// Used to interface with the Compound's Cash module diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 9a53f56d8b..04715a5e27 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -33,7 +33,7 @@ use frame_support::{ }; use frame_system::{limits, EnsureRoot}; pub use module_support::{ExchangeRate, FeeToTreasuryPool, PrecompileCallerFilter, Price, Rate, Ratio}; -use primitives::{evm::is_system_contract, Balance, CurrencyId, Nonce}; +use primitives::{evm::is_system_contract, Balance, CurrencyId, IncomeSource, Nonce}; use scale_info::TypeInfo; use sp_core::{Bytes, H160}; use sp_runtime::{traits::Convert, transaction_validity::TransactionPriority, FixedPointNumber, Perbill}; @@ -363,7 +363,7 @@ where // Ensure given treasury account have ed requirement for native asset, but don't need // ed requirement for cross-chain asset because it's one of whitelist accounts. // Ignore the result. - let _ = F::on_fee_changed(&T::get(), currency_id, amount); + let _ = F::on_fee_changed(IncomeSource::XcmFee, Some(&T::get()), currency_id, amount); } } } From bac9f23331456f992d2ab366c21c823f37065c60 Mon Sep 17 00:00:00 2001 From: zqh Date: Wed, 25 May 2022 16:56:49 +0800 Subject: [PATCH 05/49] mandala tx fee to collator --- modules/fees/src/lib.rs | 27 +++++++++++++++++++++++++-- runtime/mandala/src/lib.rs | 6 +++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index df8deecce2..1628a23684 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -240,8 +240,31 @@ impl FeeToTreasuryPool(PhantomData<(T, TC, TP)>); + +/// Transaction fee distribution to treasury pool and selected collator. +impl OnUnbalanced> for DealWithTxFees +where + TC: Get, + TP: Get, +{ + fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { + if let Some(mut fees) = fees_then_tips.next() { + if let Some(tips) = fees_then_tips.next() { + tips.merge_into(&mut fees); + } + + let split = fees.ration(100 - TP::get(), TP::get()); + let _ = ::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), split.0); + let _ = ::Currency::resolve_creating(&TC::get(), split.1); + // TODO: deposit event + } + } +} + +/// Transaction fee all distribution to treasury pool account. impl OnUnbalanced> for Pallet { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(mut fees) = fees_then_tips.next() { diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index a5b1d98435..e068d42642 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1200,15 +1200,19 @@ parameter_types! { pub DefaultFeeTokens: Vec = vec![AUSD, DOT, LDOT, RENBTC]; pub const CustomFeeSurplus: Percent = Percent::from_percent(50); pub const AlternativeFeeSurplus: Percent = Percent::from_percent(25); + pub ToCollcator: AccountId = CollatorPotId::get().into_account(); + pub const ToCollatorPercent: u32 = 20; } +pub type DealWithFees = module_fees::DealWithTxFees; + impl module_transaction_payment::Config for Runtime { type Event = Event; type Call = Call; type NativeCurrencyId = GetNativeCurrencyId; type Currency = Balances; type MultiCurrency = Currencies; - type OnTransactionPayment = Fees; + type OnTransactionPayment = DealWithFees; type AlternativeFeeSwapDeposit = NativeTokenExistentialDeposit; type TransactionByteFee = TransactionByteFee; type OperationalFeeMultiplier = OperationalFeeMultiplier; From e93bde17c487ad81bb0d0ff7faa1a31d96970f10 Mon Sep 17 00:00:00 2001 From: zqh Date: Wed, 25 May 2022 22:47:02 +0800 Subject: [PATCH 06/49] mandala init genesis fees --- modules/fees/src/lib.rs | 34 +++++++++++--- node/service/Cargo.toml | 1 + node/service/src/chain_spec/karura.rs | 1 + node/service/src/chain_spec/mandala.rs | 58 ++++++++++++++++++++++-- runtime/common/src/lib.rs | 62 ++++++++++++++++---------- runtime/karura/src/lib.rs | 22 ++++++--- runtime/mandala/src/lib.rs | 26 ++++++++--- 7 files changed, 157 insertions(+), 47 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 1628a23684..0d2801e499 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -115,6 +115,27 @@ pub mod module { #[pallet::without_storage_info] pub struct Pallet(_); + #[pallet::genesis_config] + pub struct GenesisConfig { + pub incomes: Vec<(IncomeSource, Vec<(T::AccountId, u32)>)>, + pub treasuries: Vec<(T::AccountId, Vec<(T::AccountId, u32)>)>, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + GenesisConfig { + incomes: Default::default(), + treasuries: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) {} + } + #[pallet::hooks] impl Hooks for Pallet { fn on_initialize(_: T::BlockNumber) -> Weight { @@ -215,7 +236,6 @@ impl Pallet { } impl FeeToTreasuryPool for Pallet { - // TODO: maybe use `Happened<(AccountId,CurrencyId,Balance)>` instead of new trait? fn on_fee_changed( income: IncomeSource, account_id: Option<&T::AccountId>, @@ -256,10 +276,10 @@ where tips.merge_into(&mut fees); } - let split = fees.ration(100 - TP::get(), TP::get()); - let _ = ::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), split.0); - let _ = ::Currency::resolve_creating(&TC::get(), split.1); - // TODO: deposit event + let split = fees.ration(100_u32.saturating_sub(TP::get()), TP::get()); + ::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), split.0); + ::Currency::resolve_creating(&TC::get(), split.1); + // TODO: deposit event? } } } @@ -273,8 +293,8 @@ impl OnUnbalanced> for Pallet { } // Must resolve into existing but better to be safe. - let _ = T::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), fees); - // TODO: deposit event + T::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), fees); + // TODO: deposit event? } } } diff --git a/node/service/Cargo.toml b/node/service/Cargo.toml index 323c081d0b..7280a8e735 100644 --- a/node/service/Cargo.toml +++ b/node/service/Cargo.toml @@ -83,6 +83,7 @@ ecosystem-renvm-bridge = { path = "../../ecosystem-modules/ren/renvm-bridge" } module-collator-selection = { path = "../../modules/collator-selection" } module-evm = { path = "../../modules/evm" } module-nft = { path = "../../modules/nft" } +#fees = { path = "../../modules/fees" } orml-oracle-rpc = { path = "../../orml/oracle/rpc" } orml-tokens-rpc = { path = "../../orml/tokens/rpc" } acala-primitives = { path = "../../primitives" } diff --git a/node/service/src/chain_spec/karura.rs b/node/service/src/chain_spec/karura.rs index 720a53dbc8..0a3caf6b7f 100644 --- a/node/service/src/chain_spec/karura.rs +++ b/node/service/src/chain_spec/karura.rs @@ -194,5 +194,6 @@ fn karura_dev_genesis( polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(2), }, + fees: Default::default(), } } diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 946e0c98c7..74bf309db6 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use acala_primitives::{orml_traits::GetByKey, AccountId, Balance, TokenSymbol}; +use acala_primitives::{orml_traits::GetByKey, AccountId, Balance, IncomeSource, TokenSymbol}; use coins_bip39::{English, Mnemonic, Wordlist}; use elliptic_curve::sec1::ToEncodedPoint; use hex_literal::hex; @@ -24,14 +24,21 @@ use k256::{ ecdsa::{SigningKey, VerifyingKey}, EncodedPoint as K256PublicKey, }; -use runtime_common::evm_genesis; +use mandala_runtime::{FeesConfig, TreasuryPalletId}; +use runtime_common::{ + evm_genesis, CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, + HonzonLiquitationRewardPool, HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, +}; use sc_chain_spec::ChainType; use sc_telemetry::TelemetryEndpoints; use serde_json::map::Map; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::UncheckedInto, sr25519, H160}; use sp_finality_grandpa::AuthorityId as GrandpaId; -use sp_runtime::{traits::Zero, FixedPointNumber, FixedU128}; +use sp_runtime::{ + traits::{AccountIdConversion, Zero}, + FixedPointNumber, FixedU128, +}; use sp_std::{collections::btree_map::BTreeMap, str::FromStr}; use tiny_keccak::{Hasher, Keccak}; @@ -498,6 +505,7 @@ fn testnet_genesis( safe_xcm_version: Some(2), }, phragmen_election: Default::default(), + fees: fees_config(), } } @@ -680,5 +688,49 @@ fn mandala_genesis( safe_xcm_version: Some(2), }, phragmen_election: Default::default(), + fees: fees_config(), + } +} + +fn fees_config() -> FeesConfig { + FeesConfig { + incomes: vec![ + ( + IncomeSource::TxFee, + vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + ), + (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), + (IncomeSource::DexSwapFee, vec![(NetworkTreasuryPool::get(), 100)]), + ( + IncomeSource::HonzonStabilityFee, + vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)], + ), + ( + IncomeSource::HonzonLiquidationFee, + vec![(NetworkTreasuryPool::get(), 30), (HonzonTreasuryPool::get(), 70)], + ), + ( + IncomeSource::HomaStakingRewardFee, + vec![(NetworkTreasuryPool::get(), 70), (HomaTreasuryPool::get(), 30)], + ), + ], + treasuries: vec![ + ( + NetworkTreasuryPool::get(), + vec![ + (StakingRewardPool::get(), 70), + (CollatorsRewardPool::get(), 10), + (EcosystemRewardPool::get(), 10), + (TreasuryPalletId::get().into_account(), 10), + ], + ), + ( + HonzonTreasuryPool::get(), + vec![ + (HonzonInsuranceRewardPool::get(), 30), + (HonzonLiquitationRewardPool::get(), 70), + ], + ), + ], } } diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 04715a5e27..ab51603320 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -20,40 +20,20 @@ #![cfg_attr(not(feature = "std"), no_std)] +pub use check_nonce::CheckNonce; use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::traits::Get; use frame_support::{ parameter_types, - traits::{Contains, EnsureOneOf}, + traits::{Contains, EnsureOneOf, Get}, weights::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_MILLIS}, DispatchClass, Weight, }, - RuntimeDebug, + PalletId, RuntimeDebug, }; use frame_system::{limits, EnsureRoot}; -pub use module_support::{ExchangeRate, FeeToTreasuryPool, PrecompileCallerFilter, Price, Rate, Ratio}; -use primitives::{evm::is_system_contract, Balance, CurrencyId, IncomeSource, Nonce}; -use scale_info::TypeInfo; -use sp_core::{Bytes, H160}; -use sp_runtime::{traits::Convert, transaction_validity::TransactionPriority, FixedPointNumber, Perbill}; -use sp_std::collections::btree_map::BTreeMap; -use static_assertions::const_assert; - -#[cfg(feature = "std")] -use sp_core::bytes::from_hex; -#[cfg(feature = "std")] -use std::str::FromStr; - -pub mod bench; -pub mod check_nonce; -pub mod precompile; - -#[cfg(test)] -mod mock; - -pub use check_nonce::CheckNonce; use module_evm::GenesisAccount; +pub use module_support::{ExchangeRate, FeeToTreasuryPool, PrecompileCallerFilter, Price, Rate, Ratio}; use orml_traits::GetByKey; pub use precompile::{ AllPrecompiles, DEXPrecompile, EVMPrecompile, MultiCurrencyPrecompile, NFTPrecompile, OraclePrecompile, @@ -63,12 +43,32 @@ pub use primitives::{ currency::{TokenInfo, ACA, AUSD, BNC, DOT, KAR, KBTC, KINT, KSM, KUSD, LCDOT, LDOT, LKSM, PHA, RENBTC, VSKSM}, AccountId, }; +use primitives::{evm::is_system_contract, Balance, CurrencyId, IncomeSource, Nonce}; +use scale_info::TypeInfo; +use sp_core::{Bytes, H160}; +use sp_runtime::{ + traits::{AccountIdConversion, Convert}, + transaction_validity::TransactionPriority, + FixedPointNumber, Perbill, +}; +use sp_std::collections::btree_map::BTreeMap; use sp_std::{marker::PhantomData, prelude::*}; +use static_assertions::const_assert; pub use xcm::latest::prelude::*; pub use xcm_builder::TakeRevenue; pub use xcm_executor::{traits::DropAssets, Assets}; +#[cfg(feature = "std")] +use sp_core::bytes::from_hex; +#[cfg(feature = "std")] +use std::str::FromStr; + +pub mod bench; +pub mod check_nonce; mod gas_to_weight_ratio; +#[cfg(test)] +mod mock; +pub mod precompile; pub type TimeStampedPrice = orml_oracle::TimestampedValue; @@ -490,6 +490,20 @@ pub fn evm_genesis(evm_accounts: Vec) -> BTreeMap Vec { UnreleasedNativeVaultAccountId::get(), StableAssetPalletId::get().into_account(), HonzonBridgePalletId::get().into_account(), + // treasury pools and incentive pools + NetworkTreasuryPool::get(), + HonzonTreasuryPool::get(), + HomaTreasuryPool::get(), + HonzonInsuranceRewardPool::get(), + HonzonLiquitationRewardPool::get(), + StakingRewardPool::get(), + CollatorsRewardPool::get(), + EcosystemRewardPool::get(), ] } diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index e068d42642..5f89ac829c 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -103,16 +103,18 @@ pub use primitives::{ TradingPair, }; pub use runtime_common::{ - calculate_asset_ratio, cent, dollar, microcent, millicent, AcalaDropAssets, AllPrecompiles, - EnsureRootOrAllGeneralCouncil, EnsureRootOrAllTechnicalCommittee, EnsureRootOrHalfFinancialCouncil, - EnsureRootOrHalfGeneralCouncil, EnsureRootOrHalfHomaCouncil, EnsureRootOrOneGeneralCouncil, - EnsureRootOrOneThirdsTechnicalCommittee, EnsureRootOrThreeFourthsGeneralCouncil, + calculate_asset_ratio, cent, dollar, microcent, millicent, AcalaDropAssets, AllPrecompiles, CollatorsRewardPool, + EcosystemRewardPool, EnsureRootOrAllGeneralCouncil, EnsureRootOrAllTechnicalCommittee, + EnsureRootOrHalfFinancialCouncil, EnsureRootOrHalfGeneralCouncil, EnsureRootOrHalfHomaCouncil, + EnsureRootOrOneGeneralCouncil, EnsureRootOrOneThirdsTechnicalCommittee, EnsureRootOrThreeFourthsGeneralCouncil, EnsureRootOrTwoThirdsGeneralCouncil, EnsureRootOrTwoThirdsTechnicalCommittee, ExchangeRate, ExistentialDepositsTimesOneHundred, FinancialCouncilInstance, FinancialCouncilMembershipInstance, GasToWeight, GeneralCouncilInstance, GeneralCouncilMembershipInstance, HomaCouncilInstance, HomaCouncilMembershipInstance, - MaxTipsOfPriority, OffchainSolutionWeightLimit, OperationalFeeMultiplier, OperatorMembershipInstanceAcala, Price, - ProxyType, Rate, Ratio, RuntimeBlockLength, RuntimeBlockWeights, SystemContractsFilter, TechnicalCommitteeInstance, - TechnicalCommitteeMembershipInstance, TimeStampedPrice, TipPerWeightStep, ACA, AUSD, DOT, KSM, LDOT, RENBTC, + HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, HonzonTreasuryPool, MaxTipsOfPriority, + NetworkTreasuryPool, OffchainSolutionWeightLimit, OperationalFeeMultiplier, OperatorMembershipInstanceAcala, Price, + ProxyType, Rate, Ratio, RuntimeBlockLength, RuntimeBlockWeights, StakingRewardPool, SystemContractsFilter, + TechnicalCommitteeInstance, TechnicalCommitteeMembershipInstance, TimeStampedPrice, TipPerWeightStep, ACA, AUSD, + DOT, KSM, LDOT, RENBTC, }; pub use xcm::latest::prelude::*; @@ -196,6 +198,15 @@ pub fn get_all_module_accounts() -> Vec { StarportPalletId::get().into_account(), UnreleasedNativeVaultAccountId::get(), StableAssetPalletId::get().into_account(), + // treasury pools and incentive pools + NetworkTreasuryPool::get(), + HonzonTreasuryPool::get(), + HomaTreasuryPool::get(), + HonzonInsuranceRewardPool::get(), + HonzonLiquitationRewardPool::get(), + StakingRewardPool::get(), + CollatorsRewardPool::get(), + EcosystemRewardPool::get(), ] } @@ -1200,6 +1211,7 @@ parameter_types! { pub DefaultFeeTokens: Vec = vec![AUSD, DOT, LDOT, RENBTC]; pub const CustomFeeSurplus: Percent = Percent::from_percent(50); pub const AlternativeFeeSurplus: Percent = Percent::from_percent(25); + // 20% of tx fee deposit to collator, 80% to treasury. pub ToCollcator: AccountId = CollatorPotId::get().into_account(); pub const ToCollatorPercent: u32 = 20; } From 9d27a84598cfb2a4ff8555b1ddf38b109a0d453f Mon Sep 17 00:00:00 2001 From: zqh Date: Thu, 26 May 2022 14:41:17 +0800 Subject: [PATCH 07/49] fees mock test --- Cargo.lock | 2 + modules/fees/Cargo.toml | 2 + modules/fees/src/lib.rs | 4 +- modules/fees/src/mock.rs | 183 ++++++++++++++++++++++++++++++++++++++ modules/fees/src/tests.rs | 38 ++++++++ node/service/Cargo.toml | 1 - 6 files changed, 227 insertions(+), 3 deletions(-) create mode 100644 modules/fees/src/mock.rs create mode 100644 modules/fees/src/tests.rs diff --git a/Cargo.lock b/Cargo.lock index d190f6bb4f..300babc875 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6220,7 +6220,9 @@ dependencies = [ "acala-primitives", "frame-support", "frame-system", + "module-currencies", "module-support", + "orml-tokens", "orml-traits", "pallet-balances", "parity-scale-codec", diff --git a/modules/fees/Cargo.toml b/modules/fees/Cargo.toml index ddb50da713..9a67c54156 100644 --- a/modules/fees/Cargo.toml +++ b/modules/fees/Cargo.toml @@ -25,6 +25,8 @@ paste = "1.0" [dev-dependencies] sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19" } +orml-tokens = { path = "../../orml/tokens" } +module-currencies = { path = "../../modules/currencies" } [features] default = ["std"] diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 0d2801e499..ee2317625b 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -37,8 +37,8 @@ use support::{FeeToTreasuryPool, Rate}; pub use module::*; -// mod mock; -// mod tests; +mod mock; +mod tests; pub mod weights; pub use weights::WeightInfo; diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs new file mode 100644 index 0000000000..d519f24e56 --- /dev/null +++ b/modules/fees/src/mock.rs @@ -0,0 +1,183 @@ +// This file is part of Acala. + +// Copyright (C) 2020-2022 Acala Foundation. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Mocks for asset fee distribution module. + +#![cfg(test)] + +use crate as fees; +use frame_support::traits::Nothing; +use frame_support::{ + construct_runtime, ord_parameter_types, parameter_types, + traits::{ConstU128, ConstU32, ConstU64, Everything}, + PalletId, +}; +use frame_system::EnsureSignedBy; +use orml_traits::parameter_type_with_key; +use primitives::{AccountId, Amount, Balance, BlockNumber, CurrencyId, ReserveIdentifier, TokenSymbol}; +use sp_runtime::traits::AccountIdConversion; +use support::mocks::MockAddressMapping; + +pub const ALICE: AccountId = AccountId::new([1u8; 32]); +pub const ACA: CurrencyId = CurrencyId::Token(TokenSymbol::ACA); + +impl frame_system::Config for Runtime { + type BaseCallFilter = Everything; + type Origin = Origin; + type Index = u64; + type BlockNumber = u64; + type Call = Call; + type Hash = sp_runtime::testing::H256; + type Hashing = sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = sp_runtime::traits::IdentityLookup; + type Header = sp_runtime::testing::Header; + type Event = Event; + type BlockHashCount = ConstU64<250>; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +impl pallet_balances::Config for Runtime { + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = ConstU128<1>; + type AccountStore = System; + type MaxLocks = (); + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = ReserveIdentifier; + type WeightInfo = (); +} + +parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance { + Default::default() + }; +} + +impl orml_tokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = CurrencyId; + type ExistentialDeposits = ExistentialDeposits; + type OnDust = (); + type WeightInfo = (); + type MaxLocks = ConstU32<100>; + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type DustRemovalWhitelist = Nothing; +} + +pub type AdaptedBasicCurrency = module_currencies::BasicCurrencyAdapter; + +parameter_types! { + pub const GetNativeCurrencyId: CurrencyId = ACA; +} + +ord_parameter_types! { + pub const ListingOrigin: AccountId = ALICE; +} + +impl module_currencies::Config for Runtime { + type Event = Event; + type MultiCurrency = Tokens; + type NativeCurrency = AdaptedBasicCurrency; + type GetNativeCurrencyId = GetNativeCurrencyId; + type WeightInfo = (); + type AddressMapping = MockAddressMapping; + type EVMBridge = (); + type GasToWeight = (); + type SweepOrigin = EnsureSignedBy; + type OnDust = (); +} + +parameter_types! { + pub const TreasuryPalletId: PalletId = PalletId(*b"aca/trsy"); + pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account(); +} + +impl fees::Config for Runtime { + type Event = Event; + type UpdateOrigin = EnsureSignedBy; + type Currency = Balances; + type Currencies = Currencies; + type NetworkTreasuryPoolAccount = TreasuryAccount; + type WeightInfo = (); +} + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + System: frame_system::{Pallet, Call, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + Currencies: module_currencies::{Pallet, Call, Event}, + Fees: fees::{Pallet, Storage, Call, Event, Config}, + } +); + +pub struct ExtBuilder { + balances: Vec<(AccountId, Balance)>, +} + +impl Default for ExtBuilder { + fn default() -> Self { + Self { balances: vec![] } + } +} + +impl ExtBuilder { + // pub fn balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { + // self.balances = balances; + // self + // } + + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: self.balances.into_iter().collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } +} diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs new file mode 100644 index 0000000000..354676d350 --- /dev/null +++ b/modules/fees/src/tests.rs @@ -0,0 +1,38 @@ +// This file is part of Acala. + +// Copyright (C) 2020-2022 Acala Foundation. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Unit tests for fee distribution module. + +#![cfg(test)] + +use super::*; +use crate::mock::*; +use frame_support::assert_ok; +use mock::{Event, ExtBuilder, Origin, Runtime, System}; + +#[test] +fn set_income_fee_works() { + ExtBuilder::default().build().execute_with(|| { + assert_ok!(Fees::set_income_fee(Origin::signed(ALICE), IncomeSource::TxFee, vec![])); + + System::assert_last_event(Event::Fees(crate::Event::IncomeFeeSet { + income: IncomeSource::TxFee, + pools: vec![], + })); + }); +} diff --git a/node/service/Cargo.toml b/node/service/Cargo.toml index 7280a8e735..323c081d0b 100644 --- a/node/service/Cargo.toml +++ b/node/service/Cargo.toml @@ -83,7 +83,6 @@ ecosystem-renvm-bridge = { path = "../../ecosystem-modules/ren/renvm-bridge" } module-collator-selection = { path = "../../modules/collator-selection" } module-evm = { path = "../../modules/evm" } module-nft = { path = "../../modules/nft" } -#fees = { path = "../../modules/fees" } orml-oracle-rpc = { path = "../../orml/oracle/rpc" } orml-tokens-rpc = { path = "../../orml/tokens/rpc" } acala-primitives = { path = "../../primitives" } From 8538d0c6166d98c03b903a8f3bcbf46f76728838 Mon Sep 17 00:00:00 2001 From: zqh Date: Fri, 27 May 2022 16:32:43 +0800 Subject: [PATCH 08/49] dispatch call test --- modules/fees/src/lib.rs | 27 ++++++++++--- modules/fees/src/mock.rs | 37 +++++++++++++---- modules/fees/src/tests.rs | 83 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 131 insertions(+), 16 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index ee2317625b..1781c5468f 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -133,7 +133,14 @@ pub mod module { #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { - fn build(&self) {} + fn build(&self) { + self.incomes.iter().for_each(|(income, pools)| { + let _ = >::do_set_treasury_rate(*income, pools.clone()); + }); + self.treasuries.iter().for_each(|(treasury, pools)| { + let _ = >::do_set_incentive_rate(treasury.clone(), pools.clone()); + }); + } } #[pallet::hooks] @@ -192,6 +199,8 @@ impl Pallet { income_source: IncomeSource, treasury_pool_rates: Vec<(T::AccountId, u32)>, ) -> DispatchResult { + ensure!(!treasury_pool_rates.is_empty(), Error::::InvalidParams); + let pools: Vec> = treasury_pool_rates .into_iter() .map(|p| { @@ -215,6 +224,8 @@ impl Pallet { } fn do_set_incentive_rate(treasury: T::AccountId, incentive_pools: Vec<(T::AccountId, u32)>) -> DispatchResult { + ensure!(!incentive_pools.is_empty(), Error::::InvalidParams); + let pools: Vec> = incentive_pools .into_iter() .map(|p| { @@ -236,24 +247,28 @@ impl Pallet { } impl FeeToTreasuryPool for Pallet { + /// Params: + /// - income: Income source, normally means existing modules. + /// - account_id: If given account, then the whole fee amount directly deposit to it. + /// - currency_id: currency type. + /// - amount: fee amount. fn on_fee_changed( income: IncomeSource, account_id: Option<&T::AccountId>, currency_id: CurrencyId, amount: Balance, ) -> DispatchResult { - // TODO: remove manual account_id if let Some(account_id) = account_id { return T::Currencies::deposit(currency_id, account_id, amount); } - // use `IncomeSource` to determine destination + // use `IncomeSource` to distribution fee to different treasury pool based on percentage. let pools: BoundedVec, MaxSize> = IncomeToTreasuries::::get(income); + ensure!(!pools.is_empty(), Error::::InvalidParams); + pools.into_iter().for_each(|pool| { let pool_account = pool.pool; - let rate = pool.rate; - let amount_to_pool = rate.saturating_mul_int(amount); - // TODO: deal with result + let amount_to_pool = pool.rate.saturating_mul_int(amount); let _ = T::Currencies::deposit(currency_id, &pool_account, amount_to_pool); }); Ok(()) diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index d519f24e56..ea611730db 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -21,6 +21,7 @@ #![cfg(test)] use crate as fees; +use frame_support::pallet_prelude::*; use frame_support::traits::Nothing; use frame_support::{ construct_runtime, ord_parameter_types, parameter_types, @@ -29,7 +30,7 @@ use frame_support::{ }; use frame_system::EnsureSignedBy; use orml_traits::parameter_type_with_key; -use primitives::{AccountId, Amount, Balance, BlockNumber, CurrencyId, ReserveIdentifier, TokenSymbol}; +use primitives::{AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, ReserveIdentifier, TokenSymbol}; use sp_runtime::traits::AccountIdConversion; use support::mocks::MockAddressMapping; @@ -119,8 +120,17 @@ impl module_currencies::Config for Runtime { } parameter_types! { - pub const TreasuryPalletId: PalletId = PalletId(*b"aca/trsy"); - pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account(); + pub TreasuryAccount: AccountId = PalletId(*b"aca/trsy").into_account(); + // Treasury pools + pub NetworkTreasuryPool: AccountId = PalletId(*b"aca/nktp").into_account(); + pub HonzonTreasuryPool: AccountId = PalletId(*b"aca/hztp").into_account(); + pub HomaTreasuryPool: AccountId = PalletId(*b"aca/hmtp").into_account(); + // Incentive reward Pools + pub HonzonInsuranceRewardPool: AccountId = PalletId(*b"aca/hirp").into_account(); + pub HonzonLiquitationRewardPool: AccountId = PalletId(*b"aca/hlrp").into_account(); + pub StakingRewardPool: AccountId = PalletId(*b"aca/strp").into_account(); + pub CollatorsRewardPool: AccountId = PalletId(*b"aca/clrp").into_account(); + pub EcosystemRewardPool: AccountId = PalletId(*b"aca/esrp").into_account(); } impl fees::Config for Runtime { @@ -160,10 +170,10 @@ impl Default for ExtBuilder { } impl ExtBuilder { - // pub fn balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { - // self.balances = balances; - // self - // } + pub fn balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { + self.balances = balances; + self + } pub fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() @@ -176,6 +186,19 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); + fees::GenesisConfig:: { + incomes: vec![ + ( + IncomeSource::TxFee, + vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + ), + (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), + ], + treasuries: vec![], + } + .assimilate_storage(&mut t) + .unwrap(); + let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 354676d350..e500454d75 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -22,17 +22,94 @@ use super::*; use crate::mock::*; -use frame_support::assert_ok; +use frame_support::{assert_noop, assert_ok}; use mock::{Event, ExtBuilder, Origin, Runtime, System}; #[test] fn set_income_fee_works() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(Fees::set_income_fee(Origin::signed(ALICE), IncomeSource::TxFee, vec![])); + assert_noop!( + Fees::set_income_fee(Origin::signed(ALICE), IncomeSource::TxFee, vec![]), + Error::::InvalidParams, + ); + assert_ok!(Fees::set_income_fee( + Origin::signed(ALICE), + IncomeSource::TxFee, + vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)] + )); + let incomes = IncomeToTreasuries::::get(IncomeSource::TxFee); + assert_eq!(incomes.len(), 2); System::assert_last_event(Event::Fees(crate::Event::IncomeFeeSet { income: IncomeSource::TxFee, - pools: vec![], + pools: vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: Rate::saturating_from_rational(70, 100), + }, + PoolPercent { + pool: HonzonTreasuryPool::get(), + rate: Rate::saturating_from_rational(30, 100), + }, + ], })); }); } + +#[test] +fn set_treasury_pool_works() { + ExtBuilder::default() + .balances(vec![(ALICE, 10000)]) + .build() + .execute_with(|| { + let incentives = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); + assert_eq!(incentives.len(), 0); + + assert_noop!( + Fees::set_treasury_pool(Origin::signed(ALICE), NetworkTreasuryPool::get(), vec![]), + Error::::InvalidParams, + ); + + assert_ok!(Fees::set_treasury_pool( + Origin::signed(ALICE), + NetworkTreasuryPool::get(), + vec![(StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 30)] + )); + let incentives = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); + assert_eq!(incentives.len(), 2); + System::assert_last_event(Event::Fees(crate::Event::TreasuryPoolSet { + treasury: NetworkTreasuryPool::get(), + pools: vec![ + PoolPercent { + pool: StakingRewardPool::get(), + rate: Rate::saturating_from_rational(70, 100), + }, + PoolPercent { + pool: CollatorsRewardPool::get(), + rate: Rate::saturating_from_rational(30, 100), + }, + ], + })); + }); +} + +#[test] +fn on_fee_change_works() { + ExtBuilder::default() + .balances(vec![(ALICE, 10000)]) + .build() + .execute_with(|| { + assert_ok!(Pallet::::on_fee_changed(IncomeSource::TxFee, None, ACA, 10000)); + + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 8000); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 2000); + + assert_ok!(Pallet::::on_fee_changed( + IncomeSource::TxFee, + Some(&TreasuryAccount::get()), + ACA, + 10000 + )); + assert_eq!(Currencies::free_balance(ACA, &TreasuryAccount::get()), 10000); + }); +} From 149a2f5c0f124a1d2639958e77bd6a24701da02d Mon Sep 17 00:00:00 2001 From: zqh Date: Thu, 9 Jun 2022 13:26:16 +0800 Subject: [PATCH 09/49] use PoolPercent as parameters --- modules/fees/src/lib.rs | 86 +++++++++++------------- modules/fees/src/mock.rs | 24 ++++++- modules/fees/src/tests.rs | 23 ++++++- node/service/src/chain_spec/mandala.rs | 92 ++++++++++++++++++++++---- primitives/src/lib.rs | 7 ++ 5 files changed, 165 insertions(+), 67 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 1781c5468f..79f9a898a9 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -30,10 +30,10 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; -use primitives::{Balance, CurrencyId, IncomeSource}; +use primitives::{Balance, CurrencyId, IncomeSource, PoolPercent}; use sp_runtime::FixedPointNumber; use sp_std::vec::Vec; -use support::{FeeToTreasuryPool, Rate}; +use support::FeeToTreasuryPool; pub use module::*; @@ -42,12 +42,6 @@ mod tests; pub mod weights; pub use weights::WeightInfo; -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] -pub struct PoolPercent { - pool: AccountId, - rate: Rate, -} - pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; @@ -56,7 +50,7 @@ pub mod module { use super::*; parameter_types! { - pub const MaxSize: u8 = 10; + pub const MaxPoolSize: u8 = 10; } #[pallet::config] @@ -101,7 +95,7 @@ pub mod module { #[pallet::storage] #[pallet::getter(fn income_to_treasuries)] pub type IncomeToTreasuries = - StorageMap<_, Twox64Concat, IncomeSource, BoundedVec, MaxSize>, ValueQuery>; + StorageMap<_, Twox64Concat, IncomeSource, BoundedVec, MaxPoolSize>, ValueQuery>; /// Treasury pool allocation mapping to different income pools. /// @@ -109,7 +103,7 @@ pub mod module { #[pallet::storage] #[pallet::getter(fn treasury_to_incentives)] pub type TreasuryToIncentives = - StorageMap<_, Twox64Concat, T::AccountId, BoundedVec, MaxSize>, ValueQuery>; + StorageMap<_, Twox64Concat, T::AccountId, BoundedVec, MaxPoolSize>, ValueQuery>; #[pallet::pallet] #[pallet::without_storage_info] @@ -117,8 +111,8 @@ pub mod module { #[pallet::genesis_config] pub struct GenesisConfig { - pub incomes: Vec<(IncomeSource, Vec<(T::AccountId, u32)>)>, - pub treasuries: Vec<(T::AccountId, Vec<(T::AccountId, u32)>)>, + pub incomes: Vec<(IncomeSource, Vec>)>, + pub treasuries: Vec<(T::AccountId, Vec>)>, } #[cfg(feature = "std")] @@ -159,7 +153,7 @@ pub mod module { pub fn set_income_fee( origin: OriginFor, income_source: IncomeSource, - treasury_pool_rates: Vec<(T::AccountId, u32)>, + treasury_pool_rates: Vec>, ) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; @@ -172,7 +166,7 @@ pub mod module { pub fn set_treasury_pool( origin: OriginFor, treasury: T::AccountId, - incentive_pools: Vec<(T::AccountId, u32)>, + incentive_pools: Vec>, ) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; @@ -196,58 +190,52 @@ pub mod module { impl Pallet { fn do_set_treasury_rate( - income_source: IncomeSource, - treasury_pool_rates: Vec<(T::AccountId, u32)>, + income: IncomeSource, + treasury_pool_rates: Vec>, ) -> DispatchResult { ensure!(!treasury_pool_rates.is_empty(), Error::::InvalidParams); + let pool_rates: BoundedVec, MaxPoolSize> = treasury_pool_rates + .clone() + .try_into() + .map_err(|_| Error::::InvalidParams)?; - let pools: Vec> = treasury_pool_rates - .into_iter() - .map(|p| { - let rate = Rate::saturating_from_rational(p.1, 100); - PoolPercent { pool: p.0, rate } - }) - .collect(); - - IncomeToTreasuries::::try_mutate(income_source, |rates| -> DispatchResult { - let percents: BoundedVec, MaxSize> = - pools.clone().try_into().map_err(|_| Error::::InvalidParams)?; - *rates = percents; + IncomeToTreasuries::::try_mutate(income, |maybe_pool_rates| -> DispatchResult { + *maybe_pool_rates = pool_rates; Ok(()) })?; Self::deposit_event(Event::IncomeFeeSet { - income: income_source, - pools, + income, + pools: treasury_pool_rates, }); Ok(()) } - fn do_set_incentive_rate(treasury: T::AccountId, incentive_pools: Vec<(T::AccountId, u32)>) -> DispatchResult { - ensure!(!incentive_pools.is_empty(), Error::::InvalidParams); - - let pools: Vec> = incentive_pools - .into_iter() - .map(|p| { - let rate = Rate::saturating_from_rational(p.1, 100); - PoolPercent { pool: p.0, rate } - }) - .collect(); - - TreasuryToIncentives::::try_mutate(&treasury, |rates| -> DispatchResult { - let percents: BoundedVec, MaxSize> = - pools.clone().try_into().map_err(|_| Error::::InvalidParams)?; - *rates = percents; + fn do_set_incentive_rate( + treasury: T::AccountId, + incentive_pool_rates: Vec>, + ) -> DispatchResult { + ensure!(!incentive_pool_rates.is_empty(), Error::::InvalidParams); + let pool_rates: BoundedVec, MaxPoolSize> = incentive_pool_rates + .clone() + .try_into() + .map_err(|_| Error::::InvalidParams)?; + + TreasuryToIncentives::::try_mutate(&treasury, |maybe_pool_rates| -> DispatchResult { + *maybe_pool_rates = pool_rates; Ok(()) })?; - Self::deposit_event(Event::TreasuryPoolSet { treasury, pools }); + Self::deposit_event(Event::TreasuryPoolSet { + treasury, + pools: incentive_pool_rates, + }); Ok(()) } } impl FeeToTreasuryPool for Pallet { - /// Params: + /// Parameters: /// - income: Income source, normally means existing modules. /// - account_id: If given account, then the whole fee amount directly deposit to it. /// - currency_id: currency type. @@ -263,7 +251,7 @@ impl FeeToTreasuryPool, MaxSize> = IncomeToTreasuries::::get(income); + let pools: BoundedVec, MaxPoolSize> = IncomeToTreasuries::::get(income); ensure!(!pools.is_empty(), Error::::InvalidParams); pools.into_iter().for_each(|pool| { diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index ea611730db..b8fc544e6f 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -30,8 +30,11 @@ use frame_support::{ }; use frame_system::EnsureSignedBy; use orml_traits::parameter_type_with_key; -use primitives::{AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, ReserveIdentifier, TokenSymbol}; +use primitives::{ + AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, PoolPercent, ReserveIdentifier, TokenSymbol, +}; use sp_runtime::traits::AccountIdConversion; +use sp_runtime::{FixedPointNumber, FixedU128}; use support::mocks::MockAddressMapping; pub const ALICE: AccountId = AccountId::new([1u8; 32]); @@ -190,9 +193,24 @@ impl ExtBuilder { incomes: vec![ ( IncomeSource::TxFee, - vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(80, 100), + }, + PoolPercent { + pool: CollatorsRewardPool::get(), + rate: FixedU128::saturating_from_rational(20, 100), + }, + ], + ), + ( + IncomeSource::XcmFee, + vec![PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(100, 100), + }], ), - (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), ], treasuries: vec![], } diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index e500454d75..78c4ea8693 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -24,6 +24,7 @@ use super::*; use crate::mock::*; use frame_support::{assert_noop, assert_ok}; use mock::{Event, ExtBuilder, Origin, Runtime, System}; +use sp_runtime::FixedU128; #[test] fn set_income_fee_works() { @@ -36,7 +37,16 @@ fn set_income_fee_works() { assert_ok!(Fees::set_income_fee( Origin::signed(ALICE), IncomeSource::TxFee, - vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)] + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(70, 100) + }, + PoolPercent { + pool: HonzonTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(30, 100) + } + ] )); let incomes = IncomeToTreasuries::::get(IncomeSource::TxFee); assert_eq!(incomes.len(), 2); @@ -73,7 +83,16 @@ fn set_treasury_pool_works() { assert_ok!(Fees::set_treasury_pool( Origin::signed(ALICE), NetworkTreasuryPool::get(), - vec![(StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 30)] + vec![ + PoolPercent { + pool: StakingRewardPool::get(), + rate: FixedU128::saturating_from_rational(70, 100) + }, + PoolPercent { + pool: CollatorsRewardPool::get(), + rate: FixedU128::saturating_from_rational(30, 100) + } + ] )); let incentives = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); assert_eq!(incentives.len(), 2); diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 74bf309db6..41e8f92baf 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use acala_primitives::{orml_traits::GetByKey, AccountId, Balance, IncomeSource, TokenSymbol}; +use acala_primitives::{orml_traits::GetByKey, AccountId, Balance, IncomeSource, PoolPercent, TokenSymbol}; use coins_bip39::{English, Mnemonic, Wordlist}; use elliptic_curve::sec1::ToEncodedPoint; use hex_literal::hex; @@ -697,38 +697,104 @@ fn fees_config() -> FeesConfig { incomes: vec![ ( IncomeSource::TxFee, - vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(80, 100), + }, + PoolPercent { + pool: CollatorsRewardPool::get(), + rate: FixedU128::saturating_from_rational(20, 100), + }, + ], + ), + ( + IncomeSource::XcmFee, + vec![PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(100, 100), + }], + ), + ( + IncomeSource::DexSwapFee, + vec![PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(100, 100), + }], ), - (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), - (IncomeSource::DexSwapFee, vec![(NetworkTreasuryPool::get(), 100)]), ( IncomeSource::HonzonStabilityFee, - vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)], + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(70, 100), + }, + PoolPercent { + pool: HonzonTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(30, 100), + }, + ], ), ( IncomeSource::HonzonLiquidationFee, - vec![(NetworkTreasuryPool::get(), 30), (HonzonTreasuryPool::get(), 70)], + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(30, 100), + }, + PoolPercent { + pool: HonzonTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(70, 100), + }, + ], ), ( IncomeSource::HomaStakingRewardFee, - vec![(NetworkTreasuryPool::get(), 70), (HomaTreasuryPool::get(), 30)], + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(70, 100), + }, + PoolPercent { + pool: HomaTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(30, 100), + }, + ], ), ], treasuries: vec![ ( NetworkTreasuryPool::get(), vec![ - (StakingRewardPool::get(), 70), - (CollatorsRewardPool::get(), 10), - (EcosystemRewardPool::get(), 10), - (TreasuryPalletId::get().into_account(), 10), + PoolPercent { + pool: StakingRewardPool::get(), + rate: FixedU128::saturating_from_rational(70, 100), + }, + PoolPercent { + pool: CollatorsRewardPool::get(), + rate: FixedU128::saturating_from_rational(10, 100), + }, + PoolPercent { + pool: EcosystemRewardPool::get(), + rate: FixedU128::saturating_from_rational(10, 100), + }, + PoolPercent { + pool: TreasuryPalletId::get().into_account(), + rate: FixedU128::saturating_from_rational(10, 100), + }, ], ), ( HonzonTreasuryPool::get(), vec![ - (HonzonInsuranceRewardPool::get(), 30), - (HonzonLiquitationRewardPool::get(), 70), + PoolPercent { + pool: HonzonInsuranceRewardPool::get(), + rate: FixedU128::saturating_from_rational(30, 100), + }, + PoolPercent { + pool: HonzonLiquitationRewardPool::get(), + rate: FixedU128::saturating_from_rational(70, 100), + }, ], ), ], diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 395f0e0400..40073df226 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -195,6 +195,13 @@ pub enum IncomeSource { HomaStakingRewardFee, } +#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub struct PoolPercent { + pub pool: AccountId, + pub rate: FixedU128, +} + pub type CashYieldIndex = u128; /// Convert any type that implements Into into byte representation ([u8, 32]) From cede726329b9800be2aa627fc7d26c1ed32801a1 Mon Sep 17 00:00:00 2001 From: zqh Date: Thu, 9 Jun 2022 14:41:15 +0800 Subject: [PATCH 10/49] fix clippy --- modules/fees/src/lib.rs | 16 ++++++++++------ modules/fees/src/mock.rs | 11 +++++------ modules/fees/src/tests.rs | 8 ++++---- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 79f9a898a9..9771c781e7 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -21,11 +21,10 @@ #![cfg_attr(not(feature = "std"), no_std)] #![allow(clippy::unused_unit)] -use frame_support::traits::Imbalance; use frame_support::{ pallet_prelude::*, parameter_types, - traits::{Currency, OnUnbalanced}, + traits::{Currency, Imbalance, OnUnbalanced}, transactional, }; use frame_system::pallet_prelude::*; @@ -35,8 +34,6 @@ use sp_runtime::FixedPointNumber; use sp_std::vec::Vec; use support::FeeToTreasuryPool; -pub use module::*; - mod mock; mod tests; pub mod weights; @@ -44,6 +41,13 @@ pub use weights::WeightInfo; pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; +pub type Incomes = Vec<(IncomeSource, Vec::AccountId>>)>; +pub type Treasuries = Vec<( + ::AccountId, + Vec::AccountId>>, +)>; + +pub use module::*; #[frame_support::pallet] pub mod module { @@ -111,8 +115,8 @@ pub mod module { #[pallet::genesis_config] pub struct GenesisConfig { - pub incomes: Vec<(IncomeSource, Vec>)>, - pub treasuries: Vec<(T::AccountId, Vec>)>, + pub incomes: Incomes, + pub treasuries: Treasuries, } #[cfg(feature = "std")] diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index b8fc544e6f..c8822740b2 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -21,11 +21,11 @@ #![cfg(test)] use crate as fees; -use frame_support::pallet_prelude::*; -use frame_support::traits::Nothing; use frame_support::{ - construct_runtime, ord_parameter_types, parameter_types, - traits::{ConstU128, ConstU32, ConstU64, Everything}, + construct_runtime, ord_parameter_types, + pallet_prelude::*, + parameter_types, + traits::{ConstU128, ConstU32, ConstU64, Everything, Nothing}, PalletId, }; use frame_system::EnsureSignedBy; @@ -33,8 +33,7 @@ use orml_traits::parameter_type_with_key; use primitives::{ AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, PoolPercent, ReserveIdentifier, TokenSymbol, }; -use sp_runtime::traits::AccountIdConversion; -use sp_runtime::{FixedPointNumber, FixedU128}; +use sp_runtime::{traits::AccountIdConversion, FixedPointNumber, FixedU128}; use support::mocks::MockAddressMapping; pub const ALICE: AccountId = AccountId::new([1u8; 32]); diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 78c4ea8693..86167b2b2a 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -55,11 +55,11 @@ fn set_income_fee_works() { pools: vec![ PoolPercent { pool: NetworkTreasuryPool::get(), - rate: Rate::saturating_from_rational(70, 100), + rate: FixedU128::saturating_from_rational(70, 100), }, PoolPercent { pool: HonzonTreasuryPool::get(), - rate: Rate::saturating_from_rational(30, 100), + rate: FixedU128::saturating_from_rational(30, 100), }, ], })); @@ -101,11 +101,11 @@ fn set_treasury_pool_works() { pools: vec![ PoolPercent { pool: StakingRewardPool::get(), - rate: Rate::saturating_from_rational(70, 100), + rate: FixedU128::saturating_from_rational(70, 100), }, PoolPercent { pool: CollatorsRewardPool::get(), - rate: Rate::saturating_from_rational(30, 100), + rate: FixedU128::saturating_from_rational(30, 100), }, ], })); From 74c45c2a3381f842def43becb5831b34cf4d9e0b Mon Sep 17 00:00:00 2001 From: zqh Date: Thu, 9 Jun 2022 15:58:19 +0800 Subject: [PATCH 11/49] check rate --- modules/fees/src/lib.rs | 31 ++++++++++++++------ modules/fees/src/tests.rs | 59 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 9 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 9771c781e7..fceea33e59 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -30,7 +30,10 @@ use frame_support::{ use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; use primitives::{Balance, CurrencyId, IncomeSource, PoolPercent}; -use sp_runtime::FixedPointNumber; +use sp_runtime::{ + traits::{One, Saturating, Zero}, + FixedPointNumber, FixedU128, +}; use sp_std::vec::Vec; use support::FeeToTreasuryPool; @@ -198,11 +201,12 @@ impl Pallet { treasury_pool_rates: Vec>, ) -> DispatchResult { ensure!(!treasury_pool_rates.is_empty(), Error::::InvalidParams); + Self::check_rates(&treasury_pool_rates)?; + let pool_rates: BoundedVec, MaxPoolSize> = treasury_pool_rates .clone() .try_into() .map_err(|_| Error::::InvalidParams)?; - IncomeToTreasuries::::try_mutate(income, |maybe_pool_rates| -> DispatchResult { *maybe_pool_rates = pool_rates; Ok(()) @@ -220,11 +224,12 @@ impl Pallet { incentive_pool_rates: Vec>, ) -> DispatchResult { ensure!(!incentive_pool_rates.is_empty(), Error::::InvalidParams); + Self::check_rates(&incentive_pool_rates)?; + let pool_rates: BoundedVec, MaxPoolSize> = incentive_pool_rates .clone() .try_into() .map_err(|_| Error::::InvalidParams)?; - TreasuryToIncentives::::try_mutate(&treasury, |maybe_pool_rates| -> DispatchResult { *maybe_pool_rates = pool_rates; Ok(()) @@ -236,6 +241,15 @@ impl Pallet { }); Ok(()) } + + fn check_rates(pool_rates: &Vec>) -> DispatchResult { + let mut sum = FixedU128::zero(); + pool_rates.iter().for_each(|pool_rate| { + sum = sum.saturating_add(pool_rate.rate); + }); + ensure!(One::is_one(&sum), Error::::InvalidParams); + Ok(()) + } } impl FeeToTreasuryPool for Pallet { @@ -255,13 +269,12 @@ impl FeeToTreasuryPool, MaxPoolSize> = IncomeToTreasuries::::get(income); - ensure!(!pools.is_empty(), Error::::InvalidParams); + let pool_rates: BoundedVec, MaxPoolSize> = IncomeToTreasuries::::get(income); + ensure!(!pool_rates.is_empty(), Error::::InvalidParams); - pools.into_iter().for_each(|pool| { - let pool_account = pool.pool; - let amount_to_pool = pool.rate.saturating_mul_int(amount); - let _ = T::Currencies::deposit(currency_id, &pool_account, amount_to_pool); + pool_rates.into_iter().for_each(|pool_rate| { + let amount_to_pool = pool_rate.rate.saturating_mul_int(amount); + let _ = T::Currencies::deposit(currency_id, &pool_rate.pool, amount_to_pool); }); Ok(()) } diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 86167b2b2a..a7918e8641 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -112,6 +112,65 @@ fn set_treasury_pool_works() { }); } +#[test] +fn invalid_pool_rates_works() { + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + Fees::set_income_fee( + Origin::signed(ALICE), + IncomeSource::TxFee, + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(70, 100) + }, + PoolPercent { + pool: HonzonTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(20, 100) + } + ] + ), + Error::::InvalidParams + ); + + assert_noop!( + Fees::set_income_fee( + Origin::signed(ALICE), + IncomeSource::TxFee, + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(70, 100) + }, + PoolPercent { + pool: HonzonTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(40, 100) + } + ] + ), + Error::::InvalidParams + ); + + assert_noop!( + Fees::set_treasury_pool( + Origin::signed(ALICE), + NetworkTreasuryPool::get(), + vec![ + PoolPercent { + pool: StakingRewardPool::get(), + rate: FixedU128::saturating_from_rational(70, 100) + }, + PoolPercent { + pool: CollatorsRewardPool::get(), + rate: FixedU128::saturating_from_rational(40, 100) + } + ] + ), + Error::::InvalidParams + ); + }); +} + #[test] fn on_fee_change_works() { ExtBuilder::default() From cb228151e2ad976b96a587bd9336efe6ce65dbd2 Mon Sep 17 00:00:00 2001 From: zqh Date: Fri, 10 Jun 2022 01:19:29 +0800 Subject: [PATCH 12/49] tx fee allocation refactor --- modules/fees/src/lib.rs | 37 +++++--- modules/fees/src/mock.rs | 1 + modules/fees/src/tests.rs | 183 ++++++++++++++++++++----------------- runtime/karura/src/lib.rs | 1 + runtime/mandala/src/lib.rs | 4 +- 5 files changed, 128 insertions(+), 98 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index fceea33e59..1fbdcf29d0 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -35,7 +35,7 @@ use sp_runtime::{ FixedPointNumber, FixedU128, }; use sp_std::vec::Vec; -use support::FeeToTreasuryPool; +use support::{DEXManager, FeeToTreasuryPool}; mod mock; mod tests; @@ -73,6 +73,9 @@ pub mod module { #[pallet::constant] type NetworkTreasuryPoolAccount: Get; + /// DEX to exchange currencies. + type DEX: DEXManager; + // type OnUnbalanced: OnUnbalanced>; type WeightInfo: WeightInfo; @@ -282,29 +285,39 @@ impl FeeToTreasuryPool(PhantomData<(T, TC, TP)>); +pub struct DealWithTxFees(PhantomData); /// Transaction fee distribution to treasury pool and selected collator. -impl OnUnbalanced> for DealWithTxFees -where - TC: Get, - TP: Get, -{ +impl OnUnbalanced> for DealWithTxFees { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(mut fees) = fees_then_tips.next() { if let Some(tips) = fees_then_tips.next() { tips.merge_into(&mut fees); } - let split = fees.ration(100_u32.saturating_sub(TP::get()), TP::get()); - ::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), split.0); - ::Currency::resolve_creating(&TC::get(), split.1); - // TODO: deposit event? + let pool_rates: BoundedVec, MaxPoolSize> = + IncomeToTreasuries::::get(IncomeSource::TxFee); + let pool_rates = pool_rates.into_iter().collect::>(); + + if let Some(pool) = pool_rates.get(0) { + let pool_id: &T::AccountId = &pool.pool; + let pool_rate: FixedU128 = pool.rate; + let pool_amount = pool_rate.saturating_mul_int(100u32); + let amount_other = 100u32.saturating_sub(pool_amount); + let split = fees.ration(pool_amount, amount_other); + ::Currency::resolve_creating(&pool_id, split.0); + + // Current only support two treasury pool account for tx fee. + if let Some(pool) = pool_rates.get(1) { + let pool_id: &T::AccountId = &pool.pool; + ::Currency::resolve_creating(&pool_id, split.1); + } + } } } } -/// Transaction fee all distribution to treasury pool account. +/// All transaction fee distribute to treasury pool account. impl OnUnbalanced> for Pallet { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(mut fees) = fees_then_tips.next() { diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index c8822740b2..405fe8f1e0 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -140,6 +140,7 @@ impl fees::Config for Runtime { type UpdateOrigin = EnsureSignedBy; type Currency = Balances; type Currencies = Currencies; + type DEX = (); type NetworkTreasuryPoolAccount = TreasuryAccount; type WeightInfo = (); } diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index a7918e8641..55d3a51047 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -22,10 +22,21 @@ use super::*; use crate::mock::*; +use frame_support::traits::{ExistenceRequirement, WithdrawReasons}; use frame_support::{assert_noop, assert_ok}; use mock::{Event, ExtBuilder, Origin, Runtime, System}; +use primitives::AccountId; use sp_runtime::FixedU128; +fn build_pool_percents(list: Vec<(AccountId, u32)>) -> Vec> { + list.iter() + .map(|data| PoolPercent { + pool: data.clone().0, + rate: FixedU128::saturating_from_rational(data.clone().1, 100), + }) + .collect() +} + #[test] fn set_income_fee_works() { ExtBuilder::default().build().execute_with(|| { @@ -34,34 +45,17 @@ fn set_income_fee_works() { Error::::InvalidParams, ); + let pools = build_pool_percents(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)]); assert_ok!(Fees::set_income_fee( Origin::signed(ALICE), IncomeSource::TxFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(70, 100) - }, - PoolPercent { - pool: HonzonTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(30, 100) - } - ] + pools.clone() )); let incomes = IncomeToTreasuries::::get(IncomeSource::TxFee); assert_eq!(incomes.len(), 2); System::assert_last_event(Event::Fees(crate::Event::IncomeFeeSet { income: IncomeSource::TxFee, - pools: vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(70, 100), - }, - PoolPercent { - pool: HonzonTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(30, 100), - }, - ], + pools, })); }); } @@ -80,34 +74,17 @@ fn set_treasury_pool_works() { Error::::InvalidParams, ); + let pools = build_pool_percents(vec![(StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 30)]); assert_ok!(Fees::set_treasury_pool( Origin::signed(ALICE), NetworkTreasuryPool::get(), - vec![ - PoolPercent { - pool: StakingRewardPool::get(), - rate: FixedU128::saturating_from_rational(70, 100) - }, - PoolPercent { - pool: CollatorsRewardPool::get(), - rate: FixedU128::saturating_from_rational(30, 100) - } - ] + pools.clone() )); let incentives = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); assert_eq!(incentives.len(), 2); System::assert_last_event(Event::Fees(crate::Event::TreasuryPoolSet { treasury: NetworkTreasuryPool::get(), - pools: vec![ - PoolPercent { - pool: StakingRewardPool::get(), - rate: FixedU128::saturating_from_rational(70, 100), - }, - PoolPercent { - pool: CollatorsRewardPool::get(), - rate: FixedU128::saturating_from_rational(30, 100), - }, - ], + pools, })); }); } @@ -115,62 +92,100 @@ fn set_treasury_pool_works() { #[test] fn invalid_pool_rates_works() { ExtBuilder::default().build().execute_with(|| { + let pools1 = build_pool_percents(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 20)]); + let pools2 = build_pool_percents(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 40)]); + let pools3 = build_pool_percents(vec![(StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 20)]); + assert_noop!( - Fees::set_income_fee( - Origin::signed(ALICE), - IncomeSource::TxFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(70, 100) - }, - PoolPercent { - pool: HonzonTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(20, 100) - } - ] - ), + Fees::set_income_fee(Origin::signed(ALICE), IncomeSource::TxFee, pools1), Error::::InvalidParams ); - assert_noop!( - Fees::set_income_fee( - Origin::signed(ALICE), - IncomeSource::TxFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(70, 100) - }, - PoolPercent { - pool: HonzonTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(40, 100) - } - ] - ), + Fees::set_income_fee(Origin::signed(ALICE), IncomeSource::TxFee, pools2), Error::::InvalidParams ); - assert_noop!( - Fees::set_treasury_pool( - Origin::signed(ALICE), - NetworkTreasuryPool::get(), - vec![ - PoolPercent { - pool: StakingRewardPool::get(), - rate: FixedU128::saturating_from_rational(70, 100) - }, - PoolPercent { - pool: CollatorsRewardPool::get(), - rate: FixedU128::saturating_from_rational(40, 100) - } - ] - ), + Fees::set_treasury_pool(Origin::signed(ALICE), NetworkTreasuryPool::get(), pools3), Error::::InvalidParams ); }); } +#[test] +fn tx_fee_allocation_works() { + ExtBuilder::default() + .balances(vec![(ALICE, 10000)]) + .build() + .execute_with(|| { + let pool_rates: BoundedVec, MaxPoolSize> = + IncomeToTreasuries::::get(IncomeSource::TxFee); + assert_eq!(2, pool_rates.len()); + + assert_eq!(0, Balances::free_balance(&NetworkTreasuryPool::get())); + assert_eq!(0, Balances::free_balance(&CollatorsRewardPool::get())); + + // Tx fee has two configuration in mock.rs setup. + let negative_balance = Balances::withdraw( + &ALICE, + 1000, + WithdrawReasons::TRANSACTION_PAYMENT, + ExistenceRequirement::KeepAlive, + ); + match negative_balance { + Ok(imbalance) => { + DealWithTxFees::::on_unbalanceds(Some(imbalance).into_iter()); + assert_eq!(800, Balances::free_balance(&NetworkTreasuryPool::get())); + assert_eq!(200, Balances::free_balance(&CollatorsRewardPool::get())); + } + Err(_) => {} + } + + // Update tx fee only to NetworkTreasuryPool account. + let pools = build_pool_percents(vec![(NetworkTreasuryPool::get(), 100)]); + assert_ok!(Fees::set_income_fee( + Origin::signed(ALICE), + IncomeSource::TxFee, + pools.clone() + )); + let negative_balance = Balances::withdraw( + &ALICE, + 1000, + WithdrawReasons::TRANSACTION_PAYMENT, + ExistenceRequirement::KeepAlive, + ); + match negative_balance { + Ok(imbalance) => { + DealWithTxFees::::on_unbalanceds(Some(imbalance).into_iter()); + assert_eq!(1800, Balances::free_balance(&NetworkTreasuryPool::get())); + assert_eq!(200, Balances::free_balance(&CollatorsRewardPool::get())); + } + Err(_) => {} + } + + // Update tx fee to NetworkTreasuryPool and CollatorsRewardPool both 50%. + let pools = build_pool_percents(vec![(NetworkTreasuryPool::get(), 50), (CollatorsRewardPool::get(), 50)]); + assert_ok!(Fees::set_income_fee( + Origin::signed(ALICE), + IncomeSource::TxFee, + pools.clone() + )); + let negative_balance = Balances::withdraw( + &ALICE, + 1000, + WithdrawReasons::TRANSACTION_PAYMENT, + ExistenceRequirement::KeepAlive, + ); + match negative_balance { + Ok(imbalance) => { + DealWithTxFees::::on_unbalanceds(Some(imbalance).into_iter()); + assert_eq!(2300, Balances::free_balance(&NetworkTreasuryPool::get())); + assert_eq!(700, Balances::free_balance(&CollatorsRewardPool::get())); + } + Err(_) => {} + } + }); +} + #[test] fn on_fee_change_works() { ExtBuilder::default() diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 3110f821a4..9e522f3a2e 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1563,6 +1563,7 @@ impl module_fees::Config for Runtime { type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; type Currency = Balances; type Currencies = Currencies; + type DEX = Dex; type NetworkTreasuryPoolAccount = KaruraTreasuryAccount; } diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 6377dccca5..4b607c36a9 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1214,10 +1214,9 @@ parameter_types! { pub const AlternativeFeeSurplus: Percent = Percent::from_percent(25); // 20% of tx fee deposit to collator, 80% to treasury. pub ToCollcator: AccountId = CollatorPotId::get().into_account(); - pub const ToCollatorPercent: u32 = 20; } -pub type DealWithFees = module_fees::DealWithTxFees; +pub type DealWithFees = module_fees::DealWithTxFees; impl module_transaction_payment::Config for Runtime { type Event = Event; @@ -1758,6 +1757,7 @@ impl module_fees::Config for Runtime { type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; type Currency = Balances; type Currencies = Currencies; + type DEX = Dex; type NetworkTreasuryPoolAccount = TreasuryAccount; } From b03447220802d08abbf28854a682a282dcb26865 Mon Sep 17 00:00:00 2001 From: zqh Date: Fri, 10 Jun 2022 15:51:51 +0800 Subject: [PATCH 13/49] fix clippy and genesis use u32 tuple --- modules/fees/src/lib.rs | 45 +++++++++---- modules/fees/src/mock.rs | 50 +++++++------- modules/fees/src/tests.rs | 64 ++++++++++++++++-- node/service/src/chain_spec/mandala.rs | 90 ++++---------------------- primitives/src/lib.rs | 7 -- runtime/mandala/src/lib.rs | 4 +- 6 files changed, 133 insertions(+), 127 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 1fbdcf29d0..f94de73bf2 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -29,7 +29,7 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; -use primitives::{Balance, CurrencyId, IncomeSource, PoolPercent}; +use primitives::{Balance, CurrencyId, IncomeSource}; use sp_runtime::{ traits::{One, Saturating, Zero}, FixedPointNumber, FixedU128, @@ -42,14 +42,24 @@ mod tests; pub mod weights; pub use weights::WeightInfo; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; -pub type Incomes = Vec<(IncomeSource, Vec::AccountId>>)>; +pub type Incomes = Vec<(IncomeSource, Vec<(::AccountId, u32)>)>; pub type Treasuries = Vec<( ::AccountId, - Vec::AccountId>>, + Vec<(::AccountId, u32)>, )>; +#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub struct PoolPercent { + pub pool: AccountId, + pub rate: FixedU128, +} + pub use module::*; #[frame_support::pallet] @@ -139,10 +149,24 @@ pub mod module { impl GenesisBuild for GenesisConfig { fn build(&self) { self.incomes.iter().for_each(|(income, pools)| { - let _ = >::do_set_treasury_rate(*income, pools.clone()); + let pool_rates = pools + .iter() + .map(|pool_rate| PoolPercent { + pool: pool_rate.clone().0, + rate: FixedU128::saturating_from_rational(pool_rate.1, 100), + }) + .collect(); + let _ = >::do_set_treasury_rate(*income, pool_rates); }); self.treasuries.iter().for_each(|(treasury, pools)| { - let _ = >::do_set_incentive_rate(treasury.clone(), pools.clone()); + let pool_rates = pools + .iter() + .map(|pool_rate| PoolPercent { + pool: pool_rate.clone().0, + rate: FixedU128::saturating_from_rational(pool_rate.1, 100), + }) + .collect(); + let _ = >::do_set_incentive_rate(treasury.clone(), pool_rates); }); } } @@ -245,7 +269,7 @@ impl Pallet { Ok(()) } - fn check_rates(pool_rates: &Vec>) -> DispatchResult { + fn check_rates(pool_rates: &[PoolPercent]) -> DispatchResult { let mut sum = FixedU128::zero(); pool_rates.iter().for_each(|pool_rate| { sum = sum.saturating_add(pool_rate.rate); @@ -287,7 +311,7 @@ impl FeeToTreasuryPool(PhantomData); -/// Transaction fee distribution to treasury pool and selected collator. +/// Transaction payment fee distribution. impl OnUnbalanced> for DealWithTxFees { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(mut fees) = fees_then_tips.next() { @@ -305,12 +329,12 @@ impl OnUnbalanced> for DealWithT let pool_amount = pool_rate.saturating_mul_int(100u32); let amount_other = 100u32.saturating_sub(pool_amount); let split = fees.ration(pool_amount, amount_other); - ::Currency::resolve_creating(&pool_id, split.0); + ::Currency::resolve_creating(pool_id, split.0); - // Current only support two treasury pool account for tx fee. + // Current only support at least two treasury pool account for tx fee. if let Some(pool) = pool_rates.get(1) { let pool_id: &T::AccountId = &pool.pool; - ::Currency::resolve_creating(&pool_id, split.1); + ::Currency::resolve_creating(pool_id, split.1); } } } @@ -327,7 +351,6 @@ impl OnUnbalanced> for Pallet { // Must resolve into existing but better to be safe. T::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), fees); - // TODO: deposit event? } } } diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index 405fe8f1e0..4e23e8cca3 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -30,14 +30,13 @@ use frame_support::{ }; use frame_system::EnsureSignedBy; use orml_traits::parameter_type_with_key; -use primitives::{ - AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, PoolPercent, ReserveIdentifier, TokenSymbol, -}; -use sp_runtime::{traits::AccountIdConversion, FixedPointNumber, FixedU128}; +use primitives::{AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, ReserveIdentifier, TokenSymbol}; +use sp_runtime::traits::AccountIdConversion; use support::mocks::MockAddressMapping; pub const ALICE: AccountId = AccountId::new([1u8; 32]); pub const ACA: CurrencyId = CurrencyId::Token(TokenSymbol::ACA); +pub const DOT: CurrencyId = CurrencyId::Token(TokenSymbol::DOT); impl frame_system::Config for Runtime { type BaseCallFilter = Everything; @@ -163,7 +162,7 @@ construct_runtime!( ); pub struct ExtBuilder { - balances: Vec<(AccountId, Balance)>, + balances: Vec<(AccountId, CurrencyId, Balance)>, } impl Default for ExtBuilder { @@ -173,7 +172,7 @@ impl Default for ExtBuilder { } impl ExtBuilder { - pub fn balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { + pub fn balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { self.balances = balances; self } @@ -183,8 +182,26 @@ impl ExtBuilder { .build_storage::() .unwrap(); + let native_currency_id = ACA; + pallet_balances::GenesisConfig:: { - balances: self.balances.into_iter().collect::>(), + balances: self + .balances + .clone() + .into_iter() + .filter(|(_, currency_id, _)| *currency_id == native_currency_id) + .map(|(account_id, _, initial_balance)| (account_id, initial_balance)) + .collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_tokens::GenesisConfig:: { + balances: self + .balances + .into_iter() + .filter(|(_, currency_id, _)| *currency_id != native_currency_id) + .collect::>(), } .assimilate_storage(&mut t) .unwrap(); @@ -193,24 +210,9 @@ impl ExtBuilder { incomes: vec![ ( IncomeSource::TxFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(80, 100), - }, - PoolPercent { - pool: CollatorsRewardPool::get(), - rate: FixedU128::saturating_from_rational(20, 100), - }, - ], - ), - ( - IncomeSource::XcmFee, - vec![PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(100, 100), - }], + vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], ), + (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), ], treasuries: vec![], } diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 55d3a51047..806ca1369f 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -63,7 +63,7 @@ fn set_income_fee_works() { #[test] fn set_treasury_pool_works() { ExtBuilder::default() - .balances(vec![(ALICE, 10000)]) + .balances(vec![(ALICE, ACA, 10000)]) .build() .execute_with(|| { let incentives = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); @@ -114,7 +114,7 @@ fn invalid_pool_rates_works() { #[test] fn tx_fee_allocation_works() { ExtBuilder::default() - .balances(vec![(ALICE, 10000)]) + .balances(vec![(ALICE, ACA, 10000)]) .build() .execute_with(|| { let pool_rates: BoundedVec, MaxPoolSize> = @@ -183,20 +183,41 @@ fn tx_fee_allocation_works() { } Err(_) => {} } + + // emit deposit event, just validate for last on_unbalanced() action + System::assert_has_event(Event::Balances(pallet_balances::Event::Deposit { + who: NetworkTreasuryPool::get(), + amount: 500, + })); + System::assert_has_event(Event::Balances(pallet_balances::Event::Deposit { + who: CollatorsRewardPool::get(), + amount: 500, + })); }); } #[test] -fn on_fee_change_works() { +fn fee_to_treasury_pool_on_fee_changed_works() { ExtBuilder::default() - .balances(vec![(ALICE, 10000)]) + .balances(vec![(ALICE, ACA, 10000), (ALICE, DOT, 10000)]) .build() .execute_with(|| { + // Native token tests + // FeeToTreasuryPool based on pre-configured treasury pool percentage. assert_ok!(Pallet::::on_fee_changed(IncomeSource::TxFee, None, ACA, 10000)); assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 8000); assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 2000); + System::assert_has_event(Event::Balances(pallet_balances::Event::Deposit { + who: NetworkTreasuryPool::get(), + amount: 8000, + })); + System::assert_has_event(Event::Balances(pallet_balances::Event::Deposit { + who: CollatorsRewardPool::get(), + amount: 2000, + })); + // FeeToTreasuryPool direct to given account. assert_ok!(Pallet::::on_fee_changed( IncomeSource::TxFee, Some(&TreasuryAccount::get()), @@ -204,5 +225,40 @@ fn on_fee_change_works() { 10000 )); assert_eq!(Currencies::free_balance(ACA, &TreasuryAccount::get()), 10000); + System::assert_has_event(Event::Balances(pallet_balances::Event::Deposit { + who: TreasuryAccount::get(), + amount: 10000, + })); + + // Non native token tests + // FeeToTreasuryPool based on pre-configured treasury pool percentage. + assert_ok!(Pallet::::on_fee_changed(IncomeSource::TxFee, None, DOT, 10000)); + + assert_eq!(Currencies::free_balance(DOT, &NetworkTreasuryPool::get()), 8000); + assert_eq!(Currencies::free_balance(DOT, &CollatorsRewardPool::get()), 2000); + System::assert_has_event(Event::Tokens(orml_tokens::Event::Deposited { + currency_id: DOT, + who: NetworkTreasuryPool::get(), + amount: 8000, + })); + System::assert_has_event(Event::Tokens(orml_tokens::Event::Deposited { + currency_id: DOT, + who: CollatorsRewardPool::get(), + amount: 2000, + })); + + // FeeToTreasuryPool direct to given account. + assert_ok!(Pallet::::on_fee_changed( + IncomeSource::TxFee, + Some(&TreasuryAccount::get()), + DOT, + 10000 + )); + assert_eq!(Currencies::free_balance(DOT, &TreasuryAccount::get()), 10000); + System::assert_has_event(Event::Tokens(orml_tokens::Event::Deposited { + currency_id: DOT, + who: TreasuryAccount::get(), + amount: 10000, + })); }); } diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 41e8f92baf..68d7f183cf 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -697,104 +697,38 @@ fn fees_config() -> FeesConfig { incomes: vec![ ( IncomeSource::TxFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(80, 100), - }, - PoolPercent { - pool: CollatorsRewardPool::get(), - rate: FixedU128::saturating_from_rational(20, 100), - }, - ], - ), - ( - IncomeSource::XcmFee, - vec![PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(100, 100), - }], - ), - ( - IncomeSource::DexSwapFee, - vec![PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(100, 100), - }], + vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], ), + (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), + (IncomeSource::DexSwapFee, vec![(NetworkTreasuryPool::get(), 100)]), ( IncomeSource::HonzonStabilityFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(70, 100), - }, - PoolPercent { - pool: HonzonTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(30, 100), - }, - ], + vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)], ), ( IncomeSource::HonzonLiquidationFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(30, 100), - }, - PoolPercent { - pool: HonzonTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(70, 100), - }, - ], + vec![(NetworkTreasuryPool::get(), 30), (HonzonTreasuryPool::get(), 70)], ), ( IncomeSource::HomaStakingRewardFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(70, 100), - }, - PoolPercent { - pool: HomaTreasuryPool::get(), - rate: FixedU128::saturating_from_rational(30, 100), - }, - ], + vec![(NetworkTreasuryPool::get(), 70), (HomaTreasuryPool::get(), 30)], ), ], treasuries: vec![ ( NetworkTreasuryPool::get(), vec![ - PoolPercent { - pool: StakingRewardPool::get(), - rate: FixedU128::saturating_from_rational(70, 100), - }, - PoolPercent { - pool: CollatorsRewardPool::get(), - rate: FixedU128::saturating_from_rational(10, 100), - }, - PoolPercent { - pool: EcosystemRewardPool::get(), - rate: FixedU128::saturating_from_rational(10, 100), - }, - PoolPercent { - pool: TreasuryPalletId::get().into_account(), - rate: FixedU128::saturating_from_rational(10, 100), - }, + (StakingRewardPool::get(), 70), + (CollatorsRewardPool::get(), 10), + (EcosystemRewardPool::get(), 10), + (TreasuryPalletId::get().into_account(), 10), ], ), ( HonzonTreasuryPool::get(), vec![ - PoolPercent { - pool: HonzonInsuranceRewardPool::get(), - rate: FixedU128::saturating_from_rational(30, 100), - }, - PoolPercent { - pool: HonzonLiquitationRewardPool::get(), - rate: FixedU128::saturating_from_rational(70, 100), - }, + (HonzonInsuranceRewardPool::get(), 30), + (HonzonLiquitationRewardPool::get(), 70), ], ), ], diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 40073df226..395f0e0400 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -195,13 +195,6 @@ pub enum IncomeSource { HomaStakingRewardFee, } -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct PoolPercent { - pub pool: AccountId, - pub rate: FixedU128, -} - pub type CashYieldIndex = u128; /// Convert any type that implements Into into byte representation ([u8, 32]) diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 4b607c36a9..8f5874f034 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1216,15 +1216,13 @@ parameter_types! { pub ToCollcator: AccountId = CollatorPotId::get().into_account(); } -pub type DealWithFees = module_fees::DealWithTxFees; - impl module_transaction_payment::Config for Runtime { type Event = Event; type Call = Call; type NativeCurrencyId = GetNativeCurrencyId; type Currency = Balances; type MultiCurrency = Currencies; - type OnTransactionPayment = DealWithFees; + type OnTransactionPayment = module_fees::DealWithTxFees; type AlternativeFeeSwapDeposit = NativeTokenExistentialDeposit; type TransactionByteFee = TransactionByteFee; type OperationalFeeMultiplier = OperationalFeeMultiplier; From c98a4cf5424f6861729f74c96aa4823f6d2764c4 Mon Sep 17 00:00:00 2001 From: zqh Date: Fri, 10 Jun 2022 17:24:37 +0800 Subject: [PATCH 14/49] fix test --- Cargo.lock | 1 + modules/transaction-payment/src/tests.rs | 5 ++++ node/service/src/chain_spec/mandala.rs | 2 +- runtime/integration-tests/Cargo.toml | 1 + runtime/integration-tests/src/setup.rs | 30 ++++++++++++++++------- runtime/integration-tests/src/treasury.rs | 5 ++-- 6 files changed, 32 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1345f5a94c..ce7eb86e58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10833,6 +10833,7 @@ dependencies = [ "module-evm-accounts", "module-evm-bridge", "module-evm-rpc-runtime-api", + "module-fees", "module-homa", "module-homa-lite", "module-honzon", diff --git a/modules/transaction-payment/src/tests.rs b/modules/transaction-payment/src/tests.rs index c206aa0893..378bd63aa1 100644 --- a/modules/transaction-payment/src/tests.rs +++ b/modules/transaction-payment/src/tests.rs @@ -570,6 +570,9 @@ fn charges_fee_when_validate_with_fee_currency_call() { let surplus = fee_perc.mul_ceil(fee); let fee_amount = fee + surplus; + println!("{:?}", Currencies::free_balance(ACA, &ALICE)); + println!("{:?}", Currencies::free_balance(AUSD, &ALICE)); + assert_ok!(ChargeTransactionPayment::::from(0).validate( &ALICE, &with_fee_currency_call(AUSD), @@ -581,6 +584,8 @@ fn charges_fee_when_validate_with_fee_currency_call() { sub_ausd_usd + fee_amount * 10, Currencies::free_balance(AUSD, &ausd_acc) ); + println!("{:?}", Currencies::free_balance(ACA, &ALICE)); + println!("{:?}", Currencies::free_balance(AUSD, &ALICE)); let fee_perc = CustomFeeSurplus::get(); let surplus = fee_perc.mul_ceil(fee); diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 68d7f183cf..74bf309db6 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use acala_primitives::{orml_traits::GetByKey, AccountId, Balance, IncomeSource, PoolPercent, TokenSymbol}; +use acala_primitives::{orml_traits::GetByKey, AccountId, Balance, IncomeSource, TokenSymbol}; use coins_bip39::{English, Mnemonic, Wordlist}; use elliptic_curve::sec1::ToEncodedPoint; use hex_literal::hex; diff --git a/runtime/integration-tests/Cargo.toml b/runtime/integration-tests/Cargo.toml index bfc88a5790..2ee3151d56 100644 --- a/runtime/integration-tests/Cargo.toml +++ b/runtime/integration-tests/Cargo.toml @@ -115,6 +115,7 @@ module-xcm-interface = {path = "../../modules/xcm-interface" } module-homa = {path = "../../modules/homa" } module-session-manager = { path = "../../modules/session-manager" } module-relaychain = {path = "../../modules/relaychain" } +module-fees = {path = "../../modules/fees" } primitives = { package = "acala-primitives", path = "../../primitives" } runtime-common = { path = "../common" } diff --git a/runtime/integration-tests/src/setup.rs b/runtime/integration-tests/src/setup.rs index bf6993798e..9eb47b9b1c 100644 --- a/runtime/integration-tests/src/setup.rs +++ b/runtime/integration-tests/src/setup.rs @@ -21,7 +21,7 @@ use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder; use frame_support::traits::{GenesisBuild, OnFinalize, OnIdle, OnInitialize}; pub use frame_support::{assert_noop, assert_ok, traits::Currency}; pub use frame_system::RawOrigin; -use runtime_common::evm_genesis; +use runtime_common::{evm_genesis, CollatorsRewardPool, NetworkTreasuryPool}; pub use module_support::{ mocks::MockAddressMapping, AddressMapping, CDPTreasury, DEXManager, Price, Rate, Ratio, RiskManager, @@ -50,14 +50,14 @@ mod mandala_imports { create_x2_parachain_multilocation, get_all_module_accounts, AcalaOracle, AccountId, AssetRegistry, AuctionManager, Authority, AuthoritysOriginId, Authorship, Balance, Balances, BlockNumber, Call, CdpEngine, CdpTreasury, CollatorSelection, CreateClassDeposit, CreateTokenDeposit, Currencies, CurrencyId, - DataDepositPerByte, DealWithFees, DefaultExchangeRate, Dex, EmergencyShutdown, EnabledTradingPairs, Event, - EvmAccounts, ExistentialDeposits, FinancialCouncil, Get, GetNativeCurrencyId, Homa, Honzon, IdleScheduler, - Loans, MaxTipsOfPriority, MinRewardDistributeAmount, MinimumDebitValue, MultiLocation, - NativeTokenExistentialDeposit, NetworkId, NftPalletId, OneDay, Origin, OriginCaller, PalletCurrency, - ParachainInfo, ParachainSystem, Proxy, ProxyType, Ratio, Runtime, Scheduler, Session, SessionKeys, - SessionManager, SevenDays, StableAsset, StableAssetPalletId, System, Timestamp, TipPerWeightStep, TokenSymbol, - Tokens, TransactionPayment, TransactionPaymentPalletId, TreasuryAccount, TreasuryPalletId, UncheckedExtrinsic, - Utility, Vesting, XcmInterface, EVM, NFT, + DataDepositPerByte, DefaultExchangeRate, Dex, EmergencyShutdown, EnabledTradingPairs, Event, EvmAccounts, + ExistentialDeposits, FinancialCouncil, Get, GetNativeCurrencyId, Homa, Honzon, IdleScheduler, Loans, + MaxTipsOfPriority, MinRewardDistributeAmount, MinimumDebitValue, MultiLocation, NativeTokenExistentialDeposit, + NetworkId, NftPalletId, OneDay, Origin, OriginCaller, PalletCurrency, ParachainInfo, ParachainSystem, Proxy, + ProxyType, Ratio, Runtime, Scheduler, Session, SessionKeys, SessionManager, SevenDays, StableAsset, + StableAssetPalletId, System, Timestamp, TipPerWeightStep, TokenSymbol, Tokens, TransactionPayment, + TransactionPaymentPalletId, TreasuryAccount, TreasuryPalletId, UncheckedExtrinsic, Utility, Vesting, + XcmInterface, EVM, NFT, }; pub use runtime_common::{cent, dollar, millicent, ACA, AUSD, DOT, KSM, LDOT, LKSM}; pub use sp_runtime::traits::AccountIdConversion; @@ -131,6 +131,8 @@ mod karura_imports { #[cfg(feature = "with-acala-runtime")] pub use acala_imports::*; +use primitives::IncomeSource; + #[cfg(feature = "with-acala-runtime")] mod acala_imports { pub use acala_runtime::xcm_config::*; @@ -362,6 +364,16 @@ impl ExtBuilder { ) .unwrap(); + module_fees::GenesisConfig:: { + incomes: vec![( + IncomeSource::TxFee, + vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + )], + treasuries: vec![], + } + .assimilate_storage(&mut t) + .unwrap(); + let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/runtime/integration-tests/src/treasury.rs b/runtime/integration-tests/src/treasury.rs index 4faa772db4..4aaa377f6c 100644 --- a/runtime/integration-tests/src/treasury.rs +++ b/runtime/integration-tests/src/treasury.rs @@ -235,6 +235,7 @@ mod mandala_only_tests { use super::*; type NegativeImbalance = >::NegativeImbalance; use frame_support::{pallet_prelude::Decode, traits::OnUnbalanced}; + use module_fees::DealWithTxFees; use pallet_authorship::EventHandler; #[test] @@ -266,7 +267,7 @@ mod mandala_only_tests { // Only 20% of the fee went into the pot let tip = NegativeImbalance::new((min_reward - 1) * 10); let fee = NegativeImbalance::new(0); - DealWithFees::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); + DealWithTxFees::::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); // The amount above existential is below the `MinRewardDistributeAmount`. assert_eq!( @@ -285,7 +286,7 @@ mod mandala_only_tests { let tip = NegativeImbalance::new(10); let fee = NegativeImbalance::new(0); - DealWithFees::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); + DealWithTxFees::::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); // Now the above existential is above the `MinRewardDistributeAmount`. assert_eq!( From 7d81546f1d8513bbb8d345524bdbc4aad78c45bc Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 13 Jun 2022 09:47:19 +0800 Subject: [PATCH 15/49] rename on_fee_deposit --- modules/fees/src/lib.rs | 6 +++--- modules/fees/src/tests.rs | 10 +++++----- modules/support/src/lib.rs | 4 ++-- runtime/common/src/lib.rs | 6 +++--- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index f94de73bf2..2c1d8f0a63 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -35,7 +35,7 @@ use sp_runtime::{ FixedPointNumber, FixedU128, }; use sp_std::vec::Vec; -use support::{DEXManager, FeeToTreasuryPool}; +use support::{DEXManager, OnFeeDeposit}; mod mock; mod tests; @@ -279,13 +279,13 @@ impl Pallet { } } -impl FeeToTreasuryPool for Pallet { +impl OnFeeDeposit for Pallet { /// Parameters: /// - income: Income source, normally means existing modules. /// - account_id: If given account, then the whole fee amount directly deposit to it. /// - currency_id: currency type. /// - amount: fee amount. - fn on_fee_changed( + fn on_fee_deposit( income: IncomeSource, account_id: Option<&T::AccountId>, currency_id: CurrencyId, diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 806ca1369f..ed841729f6 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -197,14 +197,14 @@ fn tx_fee_allocation_works() { } #[test] -fn fee_to_treasury_pool_on_fee_changed_works() { +fn on_fee_deposit_works() { ExtBuilder::default() .balances(vec![(ALICE, ACA, 10000), (ALICE, DOT, 10000)]) .build() .execute_with(|| { // Native token tests // FeeToTreasuryPool based on pre-configured treasury pool percentage. - assert_ok!(Pallet::::on_fee_changed(IncomeSource::TxFee, None, ACA, 10000)); + assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, None, ACA, 10000)); assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 8000); assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 2000); @@ -218,7 +218,7 @@ fn fee_to_treasury_pool_on_fee_changed_works() { })); // FeeToTreasuryPool direct to given account. - assert_ok!(Pallet::::on_fee_changed( + assert_ok!(Pallet::::on_fee_deposit( IncomeSource::TxFee, Some(&TreasuryAccount::get()), ACA, @@ -232,7 +232,7 @@ fn fee_to_treasury_pool_on_fee_changed_works() { // Non native token tests // FeeToTreasuryPool based on pre-configured treasury pool percentage. - assert_ok!(Pallet::::on_fee_changed(IncomeSource::TxFee, None, DOT, 10000)); + assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, None, DOT, 10000)); assert_eq!(Currencies::free_balance(DOT, &NetworkTreasuryPool::get()), 8000); assert_eq!(Currencies::free_balance(DOT, &CollatorsRewardPool::get()), 2000); @@ -248,7 +248,7 @@ fn fee_to_treasury_pool_on_fee_changed_works() { })); // FeeToTreasuryPool direct to given account. - assert_ok!(Pallet::::on_fee_changed( + assert_ok!(Pallet::::on_fee_deposit( IncomeSource::TxFee, Some(&TreasuryAccount::get()), DOT, diff --git a/modules/support/src/lib.rs b/modules/support/src/lib.rs index b4f3aa8978..3a89e64e45 100644 --- a/modules/support/src/lib.rs +++ b/modules/support/src/lib.rs @@ -105,8 +105,8 @@ pub trait TransactionPayment { fn apply_multiplier_to_fee(fee: Balance, multiplier: Option) -> Balance; } -pub trait FeeToTreasuryPool { - fn on_fee_changed( +pub trait OnFeeDeposit { + fn on_fee_deposit( income: IncomeSource, account_id: Option<&AccountId>, currency_id: CurrencyId, diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index ab51603320..9600a0479d 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -33,7 +33,7 @@ use frame_support::{ }; use frame_system::{limits, EnsureRoot}; use module_evm::GenesisAccount; -pub use module_support::{ExchangeRate, FeeToTreasuryPool, PrecompileCallerFilter, Price, Rate, Ratio}; +pub use module_support::{ExchangeRate, OnFeeDeposit, PrecompileCallerFilter, Price, Rate, Ratio}; use orml_traits::GetByKey; pub use precompile::{ AllPrecompiles, DEXPrecompile, EVMPrecompile, MultiCurrencyPrecompile, NFTPrecompile, OraclePrecompile, @@ -351,7 +351,7 @@ impl TakeRevenue for XcmFeeToTreasury where T: Get, C: Convert>, - F: FeeToTreasuryPool, + F: OnFeeDeposit, { fn take_revenue(revenue: MultiAsset) { if let MultiAsset { @@ -363,7 +363,7 @@ where // Ensure given treasury account have ed requirement for native asset, but don't need // ed requirement for cross-chain asset because it's one of whitelist accounts. // Ignore the result. - let _ = F::on_fee_changed(IncomeSource::XcmFee, Some(&T::get()), currency_id, amount); + let _ = F::on_fee_deposit(IncomeSource::XcmFee, Some(&T::get()), currency_id, amount); } } } From e6eb9bd642887684b9e89903cfca9b0616d469dc Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 13 Jun 2022 10:53:56 +0800 Subject: [PATCH 16/49] add DealTxFeesWithAccount --- modules/fees/src/lib.rs | 17 ++++++++++------- modules/fees/src/mock.rs | 1 - modules/fees/src/tests.rs | 6 +++--- runtime/integration-tests/src/treasury.rs | 6 +++--- runtime/karura/src/lib.rs | 1 - runtime/mandala/src/lib.rs | 3 +-- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 2c1d8f0a63..161eb22be9 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -80,9 +80,6 @@ pub mod module { type Currencies: MultiCurrency; - #[pallet::constant] - type NetworkTreasuryPoolAccount: Get; - /// DEX to exchange currencies. type DEX: DEXManager; @@ -309,10 +306,10 @@ impl OnFeeDeposit fo #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] -pub struct DealWithTxFees(PhantomData); +pub struct DistributeTxFees(PhantomData); /// Transaction payment fee distribution. -impl OnUnbalanced> for DealWithTxFees { +impl OnUnbalanced> for DistributeTxFees { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(mut fees) = fees_then_tips.next() { if let Some(tips) = fees_then_tips.next() { @@ -341,8 +338,14 @@ impl OnUnbalanced> for DealWithT } } +#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] +#[scale_info(skip_type_params(T))] +pub struct DealTxFeesWithAccount(PhantomData<(T, A)>); + /// All transaction fee distribute to treasury pool account. -impl OnUnbalanced> for Pallet { +impl> OnUnbalanced> + for DealTxFeesWithAccount +{ fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(mut fees) = fees_then_tips.next() { if let Some(tips) = fees_then_tips.next() { @@ -350,7 +353,7 @@ impl OnUnbalanced> for Pallet { } // Must resolve into existing but better to be safe. - T::Currency::resolve_creating(&T::NetworkTreasuryPoolAccount::get(), fees); + T::Currency::resolve_creating(&A::get(), fees); } } } diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index 4e23e8cca3..4fc0e9742a 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -140,7 +140,6 @@ impl fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type DEX = (); - type NetworkTreasuryPoolAccount = TreasuryAccount; type WeightInfo = (); } diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index ed841729f6..d680fd6586 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -133,7 +133,7 @@ fn tx_fee_allocation_works() { ); match negative_balance { Ok(imbalance) => { - DealWithTxFees::::on_unbalanceds(Some(imbalance).into_iter()); + DistributeTxFees::::on_unbalanceds(Some(imbalance).into_iter()); assert_eq!(800, Balances::free_balance(&NetworkTreasuryPool::get())); assert_eq!(200, Balances::free_balance(&CollatorsRewardPool::get())); } @@ -155,7 +155,7 @@ fn tx_fee_allocation_works() { ); match negative_balance { Ok(imbalance) => { - DealWithTxFees::::on_unbalanceds(Some(imbalance).into_iter()); + DistributeTxFees::::on_unbalanceds(Some(imbalance).into_iter()); assert_eq!(1800, Balances::free_balance(&NetworkTreasuryPool::get())); assert_eq!(200, Balances::free_balance(&CollatorsRewardPool::get())); } @@ -177,7 +177,7 @@ fn tx_fee_allocation_works() { ); match negative_balance { Ok(imbalance) => { - DealWithTxFees::::on_unbalanceds(Some(imbalance).into_iter()); + DistributeTxFees::::on_unbalanceds(Some(imbalance).into_iter()); assert_eq!(2300, Balances::free_balance(&NetworkTreasuryPool::get())); assert_eq!(700, Balances::free_balance(&CollatorsRewardPool::get())); } diff --git a/runtime/integration-tests/src/treasury.rs b/runtime/integration-tests/src/treasury.rs index 4aaa377f6c..5ca92b53c7 100644 --- a/runtime/integration-tests/src/treasury.rs +++ b/runtime/integration-tests/src/treasury.rs @@ -235,7 +235,7 @@ mod mandala_only_tests { use super::*; type NegativeImbalance = >::NegativeImbalance; use frame_support::{pallet_prelude::Decode, traits::OnUnbalanced}; - use module_fees::DealWithTxFees; + use module_fees::DistributeTxFees; use pallet_authorship::EventHandler; #[test] @@ -267,7 +267,7 @@ mod mandala_only_tests { // Only 20% of the fee went into the pot let tip = NegativeImbalance::new((min_reward - 1) * 10); let fee = NegativeImbalance::new(0); - DealWithTxFees::::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); + DistributeTxFees::::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); // The amount above existential is below the `MinRewardDistributeAmount`. assert_eq!( @@ -286,7 +286,7 @@ mod mandala_only_tests { let tip = NegativeImbalance::new(10); let fee = NegativeImbalance::new(0); - DealWithTxFees::::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); + DistributeTxFees::::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); // Now the above existential is above the `MinRewardDistributeAmount`. assert_eq!( diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 9e522f3a2e..a1821e016d 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1564,7 +1564,6 @@ impl module_fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type DEX = Dex; - type NetworkTreasuryPoolAccount = KaruraTreasuryAccount; } parameter_types! { diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 8f5874f034..a80b6dcbf6 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1222,7 +1222,7 @@ impl module_transaction_payment::Config for Runtime { type NativeCurrencyId = GetNativeCurrencyId; type Currency = Balances; type MultiCurrency = Currencies; - type OnTransactionPayment = module_fees::DealWithTxFees; + type OnTransactionPayment = module_fees::DistributeTxFees; type AlternativeFeeSwapDeposit = NativeTokenExistentialDeposit; type TransactionByteFee = TransactionByteFee; type OperationalFeeMultiplier = OperationalFeeMultiplier; @@ -1756,7 +1756,6 @@ impl module_fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type DEX = Dex; - type NetworkTreasuryPoolAccount = TreasuryAccount; } impl cumulus_pallet_aura_ext::Config for Runtime {} From 6558c9e355588c4b678a00760ef3891bf7514c66 Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 13 Jun 2022 11:47:40 +0800 Subject: [PATCH 17/49] extract distribution_fees --- modules/fees/src/lib.rs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 161eb22be9..a2d7ffce75 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -274,6 +274,20 @@ impl Pallet { ensure!(One::is_one(&sum), Error::::InvalidParams); Ok(()) } + + fn distribution_fees( + pool_rates: BoundedVec, MaxPoolSize>, + currency_id: CurrencyId, + amount: Balance, + ) -> DispatchResult { + ensure!(!pool_rates.is_empty(), Error::::InvalidParams); + + pool_rates.into_iter().for_each(|pool_rate| { + let amount_to_pool = pool_rate.rate.saturating_mul_int(amount); + let _ = T::Currencies::deposit(currency_id, &pool_rate.pool, amount_to_pool); + }); + Ok(()) + } } impl OnFeeDeposit for Pallet { @@ -294,13 +308,7 @@ impl OnFeeDeposit fo // use `IncomeSource` to distribution fee to different treasury pool based on percentage. let pool_rates: BoundedVec, MaxPoolSize> = IncomeToTreasuries::::get(income); - ensure!(!pool_rates.is_empty(), Error::::InvalidParams); - - pool_rates.into_iter().for_each(|pool_rate| { - let amount_to_pool = pool_rate.rate.saturating_mul_int(amount); - let _ = T::Currencies::deposit(currency_id, &pool_rate.pool, amount_to_pool); - }); - Ok(()) + Pallet::::distribution_fees(pool_rates, currency_id, amount) } } From eec6dc91ab396e3f603c6a4662043bc49b3b006f Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 14 Jun 2022 08:01:00 +0800 Subject: [PATCH 18/49] add dex for distribution treasury to incentive --- modules/fees/Cargo.toml | 2 + modules/fees/src/lib.rs | 81 ++++++++++++++++++++++++++++++++------ modules/fees/src/mock.rs | 1 + runtime/karura/src/lib.rs | 1 + runtime/mandala/src/lib.rs | 1 + 5 files changed, 75 insertions(+), 11 deletions(-) diff --git a/modules/fees/Cargo.toml b/modules/fees/Cargo.toml index 9a67c54156..99feacd21c 100644 --- a/modules/fees/Cargo.toml +++ b/modules/fees/Cargo.toml @@ -16,6 +16,7 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkad sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } orml-traits = { package = "orml-traits", path = "../../orml/traits", default-features = false } +orml-tokens = { package = "orml-tokens", path = "../../orml/tokens", default-features = false } support = { package = "module-support", path = "../support", default-features = false } primitives = { package = "acala-primitives", path = "../../primitives", default-features = false } @@ -40,6 +41,7 @@ std = [ "sp-core/std", "sp-std/std", "orml-traits/std", + "orml-tokens/std", "support/std", "primitives/std", ] diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index a2d7ffce75..5b320460a1 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -35,7 +35,7 @@ use sp_runtime::{ FixedPointNumber, FixedU128, }; use sp_std::vec::Vec; -use support::{DEXManager, OnFeeDeposit}; +use support::{DEXManager, OnFeeDeposit, SwapLimit}; mod mock; mod tests; @@ -44,6 +44,7 @@ pub use weights::WeightInfo; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; +use sp_runtime::traits::UniqueSaturatedInto; pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; @@ -68,6 +69,7 @@ pub mod module { parameter_types! { pub const MaxPoolSize: u8 = 10; + pub const MaxTokenSize: u8 = 100; } #[pallet::config] @@ -80,11 +82,12 @@ pub mod module { type Currencies: MultiCurrency; + #[pallet::constant] + type NativeCurrencyId: Get; + /// DEX to exchange currencies. type DEX: DEXManager; - // type OnUnbalanced: OnUnbalanced>; - type WeightInfo: WeightInfo; } @@ -122,6 +125,14 @@ pub mod module { pub type TreasuryToIncentives = StorageMap<_, Twox64Concat, T::AccountId, BoundedVec, MaxPoolSize>, ValueQuery>; + /// Treasury pool tokens list. + /// + /// TreasuryTokens: map AccountId => Vec + #[pallet::storage] + #[pallet::getter(fn treasury_tokens)] + pub type TreasuryTokens = + StorageMap<_, Twox64Concat, T::AccountId, BoundedVec, ValueQuery>; + #[pallet::pallet] #[pallet::without_storage_info] pub struct Pallet(_); @@ -207,14 +218,10 @@ pub mod module { /// Force transfer token from treasury pool to incentive pool. #[pallet::weight(10_000)] #[transactional] - pub fn force_transfer_to_incentive( - origin: OriginFor, - _treasury: T::AccountId, - _incentive: T::AccountId, - ) -> DispatchResult { + pub fn force_transfer_to_incentive(origin: OriginFor, treasury: T::AccountId) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; - Ok(()) + Self::distribution_treasury(treasury) } } } @@ -279,15 +286,67 @@ impl Pallet { pool_rates: BoundedVec, MaxPoolSize>, currency_id: CurrencyId, amount: Balance, + store_tokens: bool, ) -> DispatchResult { ensure!(!pool_rates.is_empty(), Error::::InvalidParams); pool_rates.into_iter().for_each(|pool_rate| { + let treasury_account = pool_rate.pool; let amount_to_pool = pool_rate.rate.saturating_mul_int(amount); - let _ = T::Currencies::deposit(currency_id, &pool_rate.pool, amount_to_pool); + + let deposit = T::Currencies::deposit(currency_id, &treasury_account, amount_to_pool); + + if deposit.is_ok() && store_tokens { + // record token type for treasury account, used when distribute to incentive pools. + let _ = TreasuryTokens::::try_mutate(treasury_account, |maybe_tokens| -> DispatchResult { + if maybe_tokens.contains(¤cy_id) { + maybe_tokens + .try_push(currency_id) + .map_err(|_| Error::::InvalidParams)?; + } + Ok(()) + }); + } }); Ok(()) } + + fn distribution_treasury(treasury: T::AccountId) -> DispatchResult { + let native_token = T::NativeCurrencyId::get(); + let tokens = TreasuryTokens::::get(&treasury); + let pool_rates: BoundedVec, MaxPoolSize> = TreasuryToIncentives::::get(&treasury); + + let mut total_native: Balance = 0; + tokens.into_iter().for_each(|token| { + if let Some(native_amount) = Self::get_native_account(&treasury, native_token, token) { + total_native = total_native.saturating_add(native_amount); + } + }); + let _ = Self::distribution_fees( + pool_rates.clone(), + native_token, + total_native.unique_saturated_into(), + false, + ); + Ok(()) + } + + fn get_native_account(treasury: &T::AccountId, native_token: CurrencyId, token: CurrencyId) -> Option { + if native_token == token { + let amount = T::Currency::free_balance(treasury); + Some(amount.unique_saturated_into()) + } else { + let amount = T::Currencies::free_balance(token, treasury); + let limit = SwapLimit::ExactSupply(amount, 0); + let swap_path = T::DEX::get_best_price_swap_path(token, T::NativeCurrencyId::get(), limit, vec![]); + if let Some((swap_path, _, _)) = swap_path { + if let Ok((_, native_amount)) = T::DEX::swap_with_specific_path(treasury, &swap_path, limit) { + return Some(native_amount); + } + } + None + } + } } impl OnFeeDeposit for Pallet { @@ -308,7 +367,7 @@ impl OnFeeDeposit fo // use `IncomeSource` to distribution fee to different treasury pool based on percentage. let pool_rates: BoundedVec, MaxPoolSize> = IncomeToTreasuries::::get(income); - Pallet::::distribution_fees(pool_rates, currency_id, amount) + Pallet::::distribution_fees(pool_rates, currency_id, amount, true) } } diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index 4fc0e9742a..f2cbb1dbcb 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -139,6 +139,7 @@ impl fees::Config for Runtime { type UpdateOrigin = EnsureSignedBy; type Currency = Balances; type Currencies = Currencies; + type NativeCurrencyId = GetNativeCurrencyId; type DEX = (); type WeightInfo = (); } diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index a1821e016d..a7c8539529 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1563,6 +1563,7 @@ impl module_fees::Config for Runtime { type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; type Currency = Balances; type Currencies = Currencies; + type NativeCurrencyId = GetNativeCurrencyId; type DEX = Dex; } diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index a80b6dcbf6..8f05ed24d2 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1755,6 +1755,7 @@ impl module_fees::Config for Runtime { type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; type Currency = Balances; type Currencies = Currencies; + type NativeCurrencyId = GetNativeCurrencyId; type DEX = Dex; } From 2eb5e133ad92700f1ad830a79f6378b10c29364d Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 14 Jun 2022 10:21:48 +0800 Subject: [PATCH 19/49] distribution fee test --- Cargo.lock | 1 + modules/fees/Cargo.toml | 1 + modules/fees/src/lib.rs | 30 ++++++++++------- modules/fees/src/mock.rs | 53 ++++++++++++++++++++++++++++-- modules/fees/src/tests.rs | 67 ++++++++++++++++++++++++++++++++++++++ runtime/karura/src/lib.rs | 1 + runtime/mandala/src/lib.rs | 1 + 7 files changed, 140 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ce7eb86e58..af9cf10283 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6221,6 +6221,7 @@ dependencies = [ "frame-support", "frame-system", "module-currencies", + "module-dex", "module-support", "orml-tokens", "orml-traits", diff --git a/modules/fees/Cargo.toml b/modules/fees/Cargo.toml index 99feacd21c..a410ad1036 100644 --- a/modules/fees/Cargo.toml +++ b/modules/fees/Cargo.toml @@ -28,6 +28,7 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0 pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19" } orml-tokens = { path = "../../orml/tokens" } module-currencies = { path = "../../modules/currencies" } +module-dex = { path = "../../modules/dex" } [features] default = ["std"] diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 5b320460a1..578ce5a9dc 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -88,6 +88,9 @@ pub mod module { /// DEX to exchange currencies. type DEX: DEXManager; + #[pallet::constant] + type DexSwapJointList: Get>>; + type WeightInfo: WeightInfo; } @@ -107,6 +110,10 @@ pub mod module { treasury: T::AccountId, pools: Vec>, }, + IncentiveDistribution { + treasury: T::AccountId, + amount: Balance, + }, } /// Income fee source mapping to different treasury pools. @@ -221,7 +228,7 @@ pub mod module { pub fn force_transfer_to_incentive(origin: OriginFor, treasury: T::AccountId) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; - Self::distribution_treasury(treasury) + Self::distribution_incentive(treasury) } } } @@ -298,8 +305,8 @@ impl Pallet { if deposit.is_ok() && store_tokens { // record token type for treasury account, used when distribute to incentive pools. - let _ = TreasuryTokens::::try_mutate(treasury_account, |maybe_tokens| -> DispatchResult { - if maybe_tokens.contains(¤cy_id) { + let _ = TreasuryTokens::::try_mutate(&treasury_account, |maybe_tokens| -> DispatchResult { + if !maybe_tokens.contains(¤cy_id) { maybe_tokens .try_push(currency_id) .map_err(|_| Error::::InvalidParams)?; @@ -311,7 +318,7 @@ impl Pallet { Ok(()) } - fn distribution_treasury(treasury: T::AccountId) -> DispatchResult { + fn distribution_incentive(treasury: T::AccountId) -> DispatchResult { let native_token = T::NativeCurrencyId::get(); let tokens = TreasuryTokens::::get(&treasury); let pool_rates: BoundedVec, MaxPoolSize> = TreasuryToIncentives::::get(&treasury); @@ -322,12 +329,12 @@ impl Pallet { total_native = total_native.saturating_add(native_amount); } }); - let _ = Self::distribution_fees( - pool_rates.clone(), - native_token, - total_native.unique_saturated_into(), - false, - ); + let _ = Self::distribution_fees(pool_rates, native_token, total_native.unique_saturated_into(), false); + + Self::deposit_event(Event::IncentiveDistribution { + treasury, + amount: total_native, + }); Ok(()) } @@ -338,7 +345,8 @@ impl Pallet { } else { let amount = T::Currencies::free_balance(token, treasury); let limit = SwapLimit::ExactSupply(amount, 0); - let swap_path = T::DEX::get_best_price_swap_path(token, T::NativeCurrencyId::get(), limit, vec![]); + let swap_path = + T::DEX::get_best_price_swap_path(token, T::NativeCurrencyId::get(), limit, T::DexSwapJointList::get()); if let Some((swap_path, _, _)) = swap_path { if let Ok((_, native_amount)) = T::DEX::swap_with_specific_path(treasury, &swap_path, limit) { return Some(native_amount); diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index f2cbb1dbcb..bdb96a1f05 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -30,11 +30,14 @@ use frame_support::{ }; use frame_system::EnsureSignedBy; use orml_traits::parameter_type_with_key; -use primitives::{AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, ReserveIdentifier, TokenSymbol}; +use primitives::{ + AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, ReserveIdentifier, TokenSymbol, TradingPair, +}; use sp_runtime::traits::AccountIdConversion; use support::mocks::MockAddressMapping; pub const ALICE: AccountId = AccountId::new([1u8; 32]); +pub const AUSD: CurrencyId = CurrencyId::Token(TokenSymbol::AUSD); pub const ACA: CurrencyId = CurrencyId::Token(TokenSymbol::ACA); pub const DOT: CurrencyId = CurrencyId::Token(TokenSymbol::DOT); @@ -101,6 +104,7 @@ pub type AdaptedBasicCurrency = module_currencies::BasicCurrencyAdapter> = vec![vec![GetStakingCurrencyId::get()]]; } impl fees::Config for Runtime { @@ -140,10 +146,35 @@ impl fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; - type DEX = (); + type DEX = DEX; + type DexSwapJointList = AlternativeSwapPathJointList; type WeightInfo = (); } +parameter_types! { + pub const DEXPalletId: PalletId = PalletId(*b"aca/dexm"); + pub const GetExchangeFee: (u32, u32) = (0, 100); + pub EnabledTradingPairs: Vec = vec![ + TradingPair::from_currency_ids(AUSD, ACA).unwrap(), + TradingPair::from_currency_ids(AUSD, DOT).unwrap(), + ]; + pub const TradingPathLimit: u32 = 4; +} + +impl module_dex::Config for Runtime { + type Event = Event; + type Currency = Currencies; + type GetExchangeFee = GetExchangeFee; + type TradingPathLimit = TradingPathLimit; + type PalletId = DEXPalletId; + type Erc20InfoMapping = (); + type DEXIncentives = (); + type WeightInfo = (); + type ListingOrigin = EnsureSignedBy; + type ExtendedProvisioningBlocks = ConstU64<0>; + type OnLiquidityPoolUpdated = (); +} + type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -158,6 +189,7 @@ construct_runtime!( Tokens: orml_tokens::{Pallet, Storage, Event, Config}, Currencies: module_currencies::{Pallet, Call, Event}, Fees: fees::{Pallet, Storage, Call, Event, Config}, + DEX: module_dex::{Pallet, Storage, Call, Event, Config}, } ); @@ -214,7 +246,22 @@ impl ExtBuilder { ), (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), ], - treasuries: vec![], + treasuries: vec![( + NetworkTreasuryPool::get(), + vec![ + (StakingRewardPool::get(), 80), + (CollatorsRewardPool::get(), 10), + (EcosystemRewardPool::get(), 10), + ], + )], + } + .assimilate_storage(&mut t) + .unwrap(); + + module_dex::GenesisConfig:: { + initial_listing_trading_pairs: vec![], + initial_enabled_trading_pairs: EnabledTradingPairs::get(), + initial_added_liquidity_pools: vec![], } .assimilate_storage(&mut t) .unwrap(); diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index d680fd6586..b1abc5041b 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -216,6 +216,14 @@ fn on_fee_deposit_works() { who: CollatorsRewardPool::get(), amount: 2000, })); + assert_eq!( + crate::TreasuryTokens::::get(&NetworkTreasuryPool::get()).to_vec(), + vec![ACA] + ); + assert_eq!( + crate::TreasuryTokens::::get(&CollatorsRewardPool::get()).to_vec(), + vec![ACA] + ); // FeeToTreasuryPool direct to given account. assert_ok!(Pallet::::on_fee_deposit( @@ -246,6 +254,14 @@ fn on_fee_deposit_works() { who: CollatorsRewardPool::get(), amount: 2000, })); + assert_eq!( + crate::TreasuryTokens::::get(&NetworkTreasuryPool::get()).to_vec(), + vec![ACA, DOT] + ); + assert_eq!( + crate::TreasuryTokens::::get(&CollatorsRewardPool::get()).to_vec(), + vec![ACA, DOT] + ); // FeeToTreasuryPool direct to given account. assert_ok!(Pallet::::on_fee_deposit( @@ -262,3 +278,54 @@ fn on_fee_deposit_works() { })); }); } + +#[test] +fn distribution_incentive_works() { + ExtBuilder::default() + .balances(vec![(ALICE, ACA, 100000), (ALICE, AUSD, 10000), (ALICE, DOT, 10000)]) + .build() + .execute_with(|| { + let pool_rates = IncomeToTreasuries::::get(IncomeSource::TxFee); + + assert_ok!(Pallet::::distribution_fees( + pool_rates.clone(), + ACA, + 1000, + true + )); + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 800); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 200); + + assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + System::assert_has_event(Event::Fees(crate::Event::IncentiveDistribution { + treasury: NetworkTreasuryPool::get(), + amount: 800, + })); + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 640); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 280); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 80); + + assert_ok!(DEX::add_liquidity( + Origin::signed(ALICE), + ACA, + AUSD, + 10000, + 1000, + 0, + false + )); + assert_ok!(DEX::add_liquidity( + Origin::signed(ALICE), + DOT, + AUSD, + 100, + 1000, + 0, + false + )); + + assert_ok!(Pallet::::distribution_fees(pool_rates, DOT, 1000, true)); + assert_eq!(Currencies::free_balance(DOT, &NetworkTreasuryPool::get()), 800); + assert_eq!(Currencies::free_balance(DOT, &CollatorsRewardPool::get()), 200); + }); +} diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index a7c8539529..6ebd2d351b 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1565,6 +1565,7 @@ impl module_fees::Config for Runtime { type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; type DEX = Dex; + type DexSwapJointList = AlternativeSwapPathJointList; } parameter_types! { diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 8f05ed24d2..0693ec57b1 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1757,6 +1757,7 @@ impl module_fees::Config for Runtime { type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; type DEX = Dex; + type DexSwapJointList = AlternativeSwapPathJointList; } impl cumulus_pallet_aura_ext::Config for Runtime {} From 388a759772fc0206236de7840a549b2769119c88 Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 14 Jun 2022 10:58:17 +0800 Subject: [PATCH 20/49] distribut incentive dex test --- modules/fees/src/lib.rs | 17 ++++++++++------- modules/fees/src/tests.rs | 29 ++++++++++++++++++++--------- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 578ce5a9dc..146acef423 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -293,7 +293,6 @@ impl Pallet { pool_rates: BoundedVec, MaxPoolSize>, currency_id: CurrencyId, amount: Balance, - store_tokens: bool, ) -> DispatchResult { ensure!(!pool_rates.is_empty(), Error::::InvalidParams); @@ -302,8 +301,7 @@ impl Pallet { let amount_to_pool = pool_rate.rate.saturating_mul_int(amount); let deposit = T::Currencies::deposit(currency_id, &treasury_account, amount_to_pool); - - if deposit.is_ok() && store_tokens { + if deposit.is_ok() { // record token type for treasury account, used when distribute to incentive pools. let _ = TreasuryTokens::::try_mutate(&treasury_account, |maybe_tokens| -> DispatchResult { if !maybe_tokens.contains(¤cy_id) { @@ -329,7 +327,13 @@ impl Pallet { total_native = total_native.saturating_add(native_amount); } }); - let _ = Self::distribution_fees(pool_rates, native_token, total_native.unique_saturated_into(), false); + + pool_rates.into_iter().for_each(|pool_rate| { + let treasury_account = pool_rate.pool; + let amount_to_pool = pool_rate.rate.saturating_mul_int(total_native); + + let _ = T::Currencies::transfer(native_token, &treasury, &treasury_account, amount_to_pool); + }); Self::deposit_event(Event::IncentiveDistribution { treasury, @@ -345,8 +349,7 @@ impl Pallet { } else { let amount = T::Currencies::free_balance(token, treasury); let limit = SwapLimit::ExactSupply(amount, 0); - let swap_path = - T::DEX::get_best_price_swap_path(token, T::NativeCurrencyId::get(), limit, T::DexSwapJointList::get()); + let swap_path = T::DEX::get_best_price_swap_path(token, native_token, limit, T::DexSwapJointList::get()); if let Some((swap_path, _, _)) = swap_path { if let Ok((_, native_amount)) = T::DEX::swap_with_specific_path(treasury, &swap_path, limit) { return Some(native_amount); @@ -375,7 +378,7 @@ impl OnFeeDeposit fo // use `IncomeSource` to distribution fee to different treasury pool based on percentage. let pool_rates: BoundedVec, MaxPoolSize> = IncomeToTreasuries::::get(income); - Pallet::::distribution_fees(pool_rates, currency_id, amount, true) + Pallet::::distribution_fees(pool_rates, currency_id, amount) } } diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index b1abc5041b..3b2bec2ad3 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -287,12 +287,7 @@ fn distribution_incentive_works() { .execute_with(|| { let pool_rates = IncomeToTreasuries::::get(IncomeSource::TxFee); - assert_ok!(Pallet::::distribution_fees( - pool_rates.clone(), - ACA, - 1000, - true - )); + assert_ok!(Pallet::::distribution_fees(pool_rates.clone(), ACA, 1000,)); assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 800); assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 200); @@ -324,8 +319,24 @@ fn distribution_incentive_works() { false )); - assert_ok!(Pallet::::distribution_fees(pool_rates, DOT, 1000, true)); - assert_eq!(Currencies::free_balance(DOT, &NetworkTreasuryPool::get()), 800); - assert_eq!(Currencies::free_balance(DOT, &CollatorsRewardPool::get()), 200); + assert_ok!(Pallet::::distribution_fees(pool_rates, AUSD, 100)); + assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 80); + assert_eq!(Currencies::free_balance(AUSD, &CollatorsRewardPool::get()), 20); + + assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + System::assert_has_event(Event::DEX(module_dex::Event::Swap { + trader: NetworkTreasuryPool::get(), + path: vec![AUSD, ACA], + liquidity_changes: vec![80, 740], + })); + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 640 + 592); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 280 + 74); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 80 + 74); + System::assert_has_event(Event::Fees(crate::Event::IncentiveDistribution { + treasury: NetworkTreasuryPool::get(), + amount: 740, + })); + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); + assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 0); }); } From 92eef5952b8995f0637700cff1a2671238d46f15 Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 14 Jun 2022 13:54:06 +0800 Subject: [PATCH 21/49] add threshold and Period --- modules/fees/src/lib.rs | 52 +++++++++---- modules/fees/src/mock.rs | 2 + modules/fees/src/tests.rs | 102 +++++++++++++++++++++---- node/service/src/chain_spec/mandala.rs | 6 +- runtime/karura/src/lib.rs | 2 + runtime/mandala/src/lib.rs | 2 + 6 files changed, 136 insertions(+), 30 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 146acef423..5171e7876c 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -51,6 +51,7 @@ pub type NegativeImbalanceOf = pub type Incomes = Vec<(IncomeSource, Vec<(::AccountId, u32)>)>; pub type Treasuries = Vec<( ::AccountId, + Balance, Vec<(::AccountId, u32)>, )>; @@ -85,6 +86,9 @@ pub mod module { #[pallet::constant] type NativeCurrencyId: Get; + #[pallet::constant] + type AccumulatePeriod: Get; + /// DEX to exchange currencies. type DEX: DEXManager; @@ -129,8 +133,13 @@ pub mod module { /// TreasuryToIncentives: map AccountId => Vec #[pallet::storage] #[pallet::getter(fn treasury_to_incentives)] - pub type TreasuryToIncentives = - StorageMap<_, Twox64Concat, T::AccountId, BoundedVec, MaxPoolSize>, ValueQuery>; + pub type TreasuryToIncentives = StorageMap< + _, + Twox64Concat, + T::AccountId, + (Balance, BoundedVec, MaxPoolSize>), + ValueQuery, + >; /// Treasury pool tokens list. /// @@ -173,7 +182,7 @@ pub mod module { .collect(); let _ = >::do_set_treasury_rate(*income, pool_rates); }); - self.treasuries.iter().for_each(|(treasury, pools)| { + self.treasuries.iter().for_each(|(treasury, threshold, pools)| { let pool_rates = pools .iter() .map(|pool_rate| PoolPercent { @@ -181,23 +190,27 @@ pub mod module { rate: FixedU128::saturating_from_rational(pool_rate.1, 100), }) .collect(); - let _ = >::do_set_incentive_rate(treasury.clone(), pool_rates); + let _ = >::do_set_incentive_rate(treasury.clone(), threshold.clone(), pool_rates); }); } } #[pallet::hooks] impl Hooks for Pallet { - fn on_initialize(_: T::BlockNumber) -> Weight { - // TODO: trigger transfer from treasury pool to incentive pools - ::WeightInfo::on_initialize() + fn on_initialize(now: T::BlockNumber) -> Weight { + if now % T::AccumulatePeriod::get() == Zero::zero() { + Self::distribute_incentives(); + ::WeightInfo::force_transfer_to_incentive() + } else { + ::WeightInfo::on_initialize() + } } } #[pallet::call] impl Pallet { /// Set how much percentage of income fee go to different treasury pools - #[pallet::weight(10_000)] + #[pallet::weight(T::WeightInfo::set_income_fee())] #[transactional] pub fn set_income_fee( origin: OriginFor, @@ -210,20 +223,21 @@ pub mod module { } /// Set how much percentage of treasury pool go to different incentive pools - #[pallet::weight(10_000)] + #[pallet::weight(T::WeightInfo::set_treasury_pool())] #[transactional] pub fn set_treasury_pool( origin: OriginFor, treasury: T::AccountId, + threshold: Balance, incentive_pools: Vec>, ) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; - Self::do_set_incentive_rate(treasury, incentive_pools) + Self::do_set_incentive_rate(treasury, threshold, incentive_pools) } /// Force transfer token from treasury pool to incentive pool. - #[pallet::weight(10_000)] + #[pallet::weight(T::WeightInfo::force_transfer_to_incentive())] #[transactional] pub fn force_transfer_to_incentive(origin: OriginFor, treasury: T::AccountId) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; @@ -259,6 +273,7 @@ impl Pallet { fn do_set_incentive_rate( treasury: T::AccountId, + threshold: Balance, incentive_pool_rates: Vec>, ) -> DispatchResult { ensure!(!incentive_pool_rates.is_empty(), Error::::InvalidParams); @@ -268,8 +283,9 @@ impl Pallet { .clone() .try_into() .map_err(|_| Error::::InvalidParams)?; - TreasuryToIncentives::::try_mutate(&treasury, |maybe_pool_rates| -> DispatchResult { + TreasuryToIncentives::::try_mutate(&treasury, |(maybe_threshold, maybe_pool_rates)| -> DispatchResult { *maybe_pool_rates = pool_rates; + *maybe_threshold = threshold; Ok(()) })?; @@ -319,7 +335,7 @@ impl Pallet { fn distribution_incentive(treasury: T::AccountId) -> DispatchResult { let native_token = T::NativeCurrencyId::get(); let tokens = TreasuryTokens::::get(&treasury); - let pool_rates: BoundedVec, MaxPoolSize> = TreasuryToIncentives::::get(&treasury); + let (threshold, pool_rates) = TreasuryToIncentives::::get(&treasury); let mut total_native: Balance = 0; tokens.into_iter().for_each(|token| { @@ -328,6 +344,10 @@ impl Pallet { } }); + if total_native < threshold { + return Ok(()); + } + pool_rates.into_iter().for_each(|pool_rate| { let treasury_account = pool_rate.pool; let amount_to_pool = pool_rate.rate.saturating_mul_int(total_native); @@ -358,6 +378,12 @@ impl Pallet { None } } + + fn distribute_incentives() { + TreasuryToIncentives::::iter_keys().for_each(|treasury| { + let _ = Self::distribution_incentive(treasury); + }); + } } impl OnFeeDeposit for Pallet { diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index bdb96a1f05..df14525b67 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -146,6 +146,7 @@ impl fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; + type AccumulatePeriod = ConstU64<10>; type DEX = DEX; type DexSwapJointList = AlternativeSwapPathJointList; type WeightInfo = (); @@ -248,6 +249,7 @@ impl ExtBuilder { ], treasuries: vec![( NetworkTreasuryPool::get(), + 100, vec![ (StakingRewardPool::get(), 80), (CollatorsRewardPool::get(), 10), diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 3b2bec2ad3..0918ec9092 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -66,11 +66,8 @@ fn set_treasury_pool_works() { .balances(vec![(ALICE, ACA, 10000)]) .build() .execute_with(|| { - let incentives = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); - assert_eq!(incentives.len(), 0); - assert_noop!( - Fees::set_treasury_pool(Origin::signed(ALICE), NetworkTreasuryPool::get(), vec![]), + Fees::set_treasury_pool(Origin::signed(ALICE), NetworkTreasuryPool::get(), 100, vec![]), Error::::InvalidParams, ); @@ -78,9 +75,10 @@ fn set_treasury_pool_works() { assert_ok!(Fees::set_treasury_pool( Origin::signed(ALICE), NetworkTreasuryPool::get(), + 100, pools.clone() )); - let incentives = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); + let (_, incentives) = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); assert_eq!(incentives.len(), 2); System::assert_last_event(Event::Fees(crate::Event::TreasuryPoolSet { treasury: NetworkTreasuryPool::get(), @@ -105,7 +103,7 @@ fn invalid_pool_rates_works() { Error::::InvalidParams ); assert_noop!( - Fees::set_treasury_pool(Origin::signed(ALICE), NetworkTreasuryPool::get(), pools3), + Fees::set_treasury_pool(Origin::signed(ALICE), NetworkTreasuryPool::get(), 100, pools3), Error::::InvalidParams ); }); @@ -282,7 +280,7 @@ fn on_fee_deposit_works() { #[test] fn distribution_incentive_works() { ExtBuilder::default() - .balances(vec![(ALICE, ACA, 100000), (ALICE, AUSD, 10000), (ALICE, DOT, 10000)]) + .balances(vec![(ALICE, ACA, 100000), (ALICE, AUSD, 10000)]) .build() .execute_with(|| { let pool_rates = IncomeToTreasuries::::get(IncomeSource::TxFee); @@ -309,15 +307,6 @@ fn distribution_incentive_works() { 0, false )); - assert_ok!(DEX::add_liquidity( - Origin::signed(ALICE), - DOT, - AUSD, - 100, - 1000, - 0, - false - )); assert_ok!(Pallet::::distribution_fees(pool_rates, AUSD, 100)); assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 80); @@ -340,3 +329,84 @@ fn distribution_incentive_works() { assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 0); }); } + +#[test] +fn distribution_incentive_threshold_works() { + ExtBuilder::default() + .balances(vec![(ALICE, ACA, 100000), (ALICE, AUSD, 10000)]) + .build() + .execute_with(|| { + let pool_rates = IncomeToTreasuries::::get(IncomeSource::TxFee); + + assert_ok!(Pallet::::distribution_fees(pool_rates.clone(), ACA, 100)); + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 80); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 20); + + assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + // due to native token less than threshold, not distribute to incentive pools. + // but swap still happened, so treasury account got native token. + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 80); + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 0); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 0); + + assert_ok!(Pallet::::distribution_fees(pool_rates.clone(), ACA, 25)); + // now treasury account native token large than threshold + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 100); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 25); + + assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + // then distribution to incentive pools + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); + System::assert_has_event(Event::Fees(crate::Event::IncentiveDistribution { + treasury: NetworkTreasuryPool::get(), + amount: 100, + })); + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 80); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 10); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 25 + 10); + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); + + assert_ok!(DEX::add_liquidity( + Origin::signed(ALICE), + ACA, + AUSD, + 10000, + 1000, + 0, + false + )); + + // swapped out native token less then threshold + assert_ok!(Pallet::::distribution_fees(pool_rates.clone(), AUSD, 10)); + assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 8); + assert_eq!(Currencies::free_balance(AUSD, &CollatorsRewardPool::get()), 2); + assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 79); + System::assert_has_event(Event::DEX(module_dex::Event::Swap { + trader: NetworkTreasuryPool::get(), + path: vec![AUSD, ACA], + liquidity_changes: vec![8, 79], + })); + + assert_ok!(Pallet::::distribution_fees(pool_rates, AUSD, 10)); + assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 8); + assert_eq!(Currencies::free_balance(AUSD, &CollatorsRewardPool::get()), 2 + 2); + assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + System::assert_has_event(Event::DEX(module_dex::Event::Swap { + trader: NetworkTreasuryPool::get(), + path: vec![AUSD, ACA], + liquidity_changes: vec![8, 78], + })); + + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 80 + 125); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 35 + 15); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 10 + 15); + System::assert_has_event(Event::Fees(crate::Event::IncentiveDistribution { + treasury: NetworkTreasuryPool::get(), + amount: 79 + 78, + })); + // due to percent round, there are some native token left in treasury account. + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 2); + assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 0); + }); +} diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 74bf309db6..389ca75701 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -26,7 +26,7 @@ use k256::{ }; use mandala_runtime::{FeesConfig, TreasuryPalletId}; use runtime_common::{ - evm_genesis, CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, + dollar, evm_genesis, CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, }; use sc_chain_spec::ChainType; @@ -693,6 +693,8 @@ fn mandala_genesis( } fn fees_config() -> FeesConfig { + use mandala_runtime::ACA; + FeesConfig { incomes: vec![ ( @@ -717,6 +719,7 @@ fn fees_config() -> FeesConfig { treasuries: vec![ ( NetworkTreasuryPool::get(), + 1000 * dollar(ACA), vec![ (StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 10), @@ -726,6 +729,7 @@ fn fees_config() -> FeesConfig { ), ( HonzonTreasuryPool::get(), + 1000 * dollar(ACA), vec![ (HonzonInsuranceRewardPool::get(), 30), (HonzonLiquitationRewardPool::get(), 70), diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 6ebd2d351b..1fe2fa9bf6 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -66,6 +66,7 @@ use orml_traits::{ }; use pallet_transaction_payment::RuntimeDispatchInfo; +use frame_support::traits::ConstU64; pub use frame_support::{ construct_runtime, log, parameter_types, traits::{ @@ -1564,6 +1565,7 @@ impl module_fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; + type AccumulatePeriod = ConstU64<10>; type DEX = Dex; type DexSwapJointList = AlternativeSwapPathJointList; } diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 0693ec57b1..6d8a4453cd 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -33,6 +33,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use codec::{Decode, DecodeLimit, Encode}; use cumulus_pallet_parachain_system::RelaychainBlockNumberProvider; use frame_support::pallet_prelude::InvalidTransaction; +use frame_support::traits::ConstU64; pub use frame_support::{ construct_runtime, log, parameter_types, traits::{ @@ -1756,6 +1757,7 @@ impl module_fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; + type AccumulatePeriod = ConstU64<10>; type DEX = Dex; type DexSwapJointList = AlternativeSwapPathJointList; } From 9d9faa8690021d811f8bd95ac5983a7b00bd6248 Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 14 Jun 2022 14:27:30 +0800 Subject: [PATCH 22/49] rename to AllocationPeriod --- modules/fees/src/lib.rs | 11 +++++++---- modules/fees/src/mock.rs | 2 +- modules/fees/src/tests.rs | 17 ++++++++++++++++- runtime/karura/src/lib.rs | 6 +++++- runtime/mandala/src/lib.rs | 6 +++++- 5 files changed, 34 insertions(+), 8 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 5171e7876c..10e29515cb 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -86,10 +86,11 @@ pub mod module { #[pallet::constant] type NativeCurrencyId: Get; + /// Allocation period from treasury to incentive pools. #[pallet::constant] - type AccumulatePeriod: Get; + type AllocationPeriod: Get; - /// DEX to exchange currencies. + /// DEX to exchange currencies when allocation. type DEX: DEXManager; #[pallet::constant] @@ -129,8 +130,10 @@ pub mod module { StorageMap<_, Twox64Concat, IncomeSource, BoundedVec, MaxPoolSize>, ValueQuery>; /// Treasury pool allocation mapping to different income pools. + /// Only allocation token from treasury pool account to income pool accounts when native token + /// of treasury pool account is large than threshold. /// - /// TreasuryToIncentives: map AccountId => Vec + /// TreasuryToIncentives: map AccountId => (Balance, Vec) #[pallet::storage] #[pallet::getter(fn treasury_to_incentives)] pub type TreasuryToIncentives = StorageMap< @@ -198,7 +201,7 @@ pub mod module { #[pallet::hooks] impl Hooks for Pallet { fn on_initialize(now: T::BlockNumber) -> Weight { - if now % T::AccumulatePeriod::get() == Zero::zero() { + if now % T::AllocationPeriod::get() == Zero::zero() { Self::distribute_incentives(); ::WeightInfo::force_transfer_to_incentive() } else { diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index df14525b67..8a7da93b01 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -146,7 +146,7 @@ impl fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; - type AccumulatePeriod = ConstU64<10>; + type AllocationPeriod = ConstU64<10>; type DEX = DEX; type DexSwapJointList = AlternativeSwapPathJointList; type WeightInfo = (); diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 0918ec9092..db45aa8159 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -78,8 +78,23 @@ fn set_treasury_pool_works() { 100, pools.clone() )); - let (_, incentives) = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); + let (threshold, incentives) = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); assert_eq!(incentives.len(), 2); + assert_eq!(threshold, 100); + System::assert_last_event(Event::Fees(crate::Event::TreasuryPoolSet { + treasury: NetworkTreasuryPool::get(), + pools: pools.clone(), + })); + + assert_ok!(Fees::set_treasury_pool( + Origin::signed(ALICE), + NetworkTreasuryPool::get(), + 10, + pools.clone() + )); + let (threshold, incentives) = TreasuryToIncentives::::get(NetworkTreasuryPool::get()); + assert_eq!(incentives.len(), 2); + assert_eq!(threshold, 10); System::assert_last_event(Event::Fees(crate::Event::TreasuryPoolSet { treasury: NetworkTreasuryPool::get(), pools, diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 1fe2fa9bf6..0e28530839 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1558,6 +1558,10 @@ impl module_idle_scheduler::Config for Runtime { type DisableBlockThreshold = ConstU32<6>; } +parameter_types! { + pub const AllocationPeriod: BlockNumber = 7 * DAYS; +} + impl module_fees::Config for Runtime { type Event = Event; type WeightInfo = (); @@ -1565,7 +1569,7 @@ impl module_fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; - type AccumulatePeriod = ConstU64<10>; + type AllocationPeriod = AllocationPeriod; type DEX = Dex; type DexSwapJointList = AlternativeSwapPathJointList; } diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 6d8a4453cd..2b528f1fca 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1750,6 +1750,10 @@ impl module_idle_scheduler::Config for Runtime { type DisableBlockThreshold = ConstU32<6>; } +parameter_types! { + pub const AllocationPeriod: BlockNumber = DAYS; +} + impl module_fees::Config for Runtime { type Event = Event; type WeightInfo = (); @@ -1757,7 +1761,7 @@ impl module_fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; - type AccumulatePeriod = ConstU64<10>; + type AllocationPeriod = AllocationPeriod; type DEX = Dex; type DexSwapJointList = AlternativeSwapPathJointList; } From 0226b92cacd8aafea0125f25c2a40ba66c35958d Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Tue, 14 Jun 2022 19:11:44 +1200 Subject: [PATCH 23/49] Changed Homa momdule's staking reward to go to OnFeeDeposit configured by module_fees instead. Added a unit test in module homa to test this. Added module_fees to Acala runtime Updated tests accordingly. --- Cargo.lock | 11 ++- modules/fees/src/lib.rs | 2 +- modules/homa/Cargo.toml | 2 + modules/homa/src/lib.rs | 26 +++--- modules/homa/src/mock.rs | 29 ++++-- modules/homa/src/tests.rs | 107 +++++++++++++++++----- node/service/src/chain_spec/acala.rs | 1 + node/service/src/chain_spec/mandala.rs | 4 +- runtime/acala/Cargo.toml | 2 + runtime/acala/src/lib.rs | 17 +++- runtime/common/Cargo.toml | 2 + runtime/common/src/lib.rs | 3 +- runtime/common/src/precompile/mock.rs | 18 +++- runtime/integration-tests/src/treasury.rs | 22 ++++- runtime/karura/src/lib.rs | 3 +- runtime/mandala/src/lib.rs | 11 +-- 16 files changed, 198 insertions(+), 62 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index af9cf10283..a06e779936 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -151,6 +151,7 @@ dependencies = [ "module-evm-accounts", "module-evm-bridge", "module-evm-rpc-runtime-api", + "module-fees", "module-homa", "module-honzon", "module-idle-scheduler", @@ -5407,9 +5408,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.16" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ "cfg-if 1.0.0", "value-bag", @@ -6245,6 +6246,7 @@ dependencies = [ "frame-support", "frame-system", "module-currencies", + "module-fees", "module-support", "orml-tokens", "orml-traits", @@ -10755,6 +10757,7 @@ dependencies = [ "module-evm-accounts", "module-evm-bridge", "module-evm-utility-macro", + "module-fees", "module-homa", "module-idle-scheduler", "module-nft", @@ -14368,9 +14371,9 @@ checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" [[package]] name = "value-bag" -version = "1.0.0-alpha.8" +version = "1.0.0-alpha.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79923f7731dc61ebfba3633098bf3ac533bbd35ccd8c57e7088d9a5eebe0263f" +checksum = "2209b78d1249f7e6f3293657c9779fe31ced465df091bbd433a1cf88e916ec55" dependencies = [ "ctor", "version_check", diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 10e29515cb..4577588e4e 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -193,7 +193,7 @@ pub mod module { rate: FixedU128::saturating_from_rational(pool_rate.1, 100), }) .collect(); - let _ = >::do_set_incentive_rate(treasury.clone(), threshold.clone(), pool_rates); + let _ = >::do_set_incentive_rate(treasury.clone(), *threshold, pool_rates); }); } } diff --git a/modules/homa/Cargo.toml b/modules/homa/Cargo.toml index c347b8cb83..87eaba89ab 100644 --- a/modules/homa/Cargo.toml +++ b/modules/homa/Cargo.toml @@ -17,6 +17,7 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v primitives = { package = "acala-primitives", path = "../../primitives", default-features = false } orml-traits = { path = "../../orml/traits", default-features = false } module-support = { path = "../../modules/support", default-features = false } +module-fees = { path = "../fees", default-features = false } [dev-dependencies] sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19" } @@ -40,6 +41,7 @@ std = [ "primitives/std", "orml-traits/std", "module-support/std", + "module-fees/std", ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/modules/homa/src/lib.rs b/modules/homa/src/lib.rs index 0501b9ce00..5c2dd5f74b 100644 --- a/modules/homa/src/lib.rs +++ b/modules/homa/src/lib.rs @@ -23,9 +23,9 @@ use frame_support::{log, pallet_prelude::*, transactional, PalletId}; use frame_system::{ensure_signed, pallet_prelude::*}; -use module_support::{ExchangeRate, ExchangeRateProvider, HomaManager, HomaSubAccountXcm, Rate, Ratio}; +use module_support::{ExchangeRate, ExchangeRateProvider, HomaManager, HomaSubAccountXcm, OnFeeDeposit, Rate, Ratio}; use orml_traits::MultiCurrency; -use primitives::{Balance, CurrencyId, EraIndex}; +use primitives::{Balance, CurrencyId, EraIndex, IncomeSource}; use scale_info::TypeInfo; use sp_runtime::{ traits::{ @@ -122,10 +122,6 @@ pub mod module { #[pallet::constant] type DefaultExchangeRate: Get; - /// Vault reward of Homa protocol - #[pallet::constant] - type TreasuryAccount: Get; - /// The index list of active Homa subaccounts. /// `active` means these subaccounts can continue do bond/unbond operations by Homa. #[pallet::constant] @@ -151,6 +147,9 @@ pub mod module { /// Weight information for the extrinsics in this module. type WeightInfo: WeightInfo; + + /// Where the staking reward fee go to. + type OnFeeDeposit: OnFeeDeposit; } #[pallet::error] @@ -316,7 +315,7 @@ pub mod module { pub type SoftBondedCapPerSubAccount = StorageValue<_, Balance, ValueQuery>; /// The rate of Homa drawn from the staking reward as commission. - /// The draw will be transfer to TreasuryAccount of Homa in liquid currency. + /// The draw will be transfer to OnFeeDeposit in liquid currency. /// /// CommissionRate: value: Rate #[pallet::storage] @@ -464,8 +463,7 @@ pub mod module { /// on relaychain to obtain the best staking rewards. /// - `estimated_reward_rate_per_era`: the estimated staking yield of each era on the /// current relay chain. - /// - `commission_rate`: the rate to draw from estimated staking rewards as commission to - /// HomaTreasury + /// - `commission_rate`: the rate to draw from estimated staking rewards as commission /// - `fast_match_fee_rate`: the fixed fee rate when redeem request is been fast matched. #[pallet::weight(< T as Config >::WeightInfo::update_homa_params())] #[transactional] @@ -849,7 +847,7 @@ pub mod module { /// Accumulate staking rewards according to EstimatedRewardRatePerEra and era internally. /// And draw commission from estimated staking rewards by issuing liquid currency to - /// TreasuryAccount. Note: This will cause some losses to the minters in previous_era, + /// OnFeeDeposit. Note: This will cause some losses to the minters in previous_era, /// because they have been already deducted some liquid currency amount when mint in /// previous_era. Until there is a better way to calculate, this part of the loss can only /// be regarded as an implicit mint fee! @@ -890,7 +888,13 @@ pub mod module { .unwrap_or_else(Ratio::max_value); let inflate_liquid_amount = inflate_rate.saturating_mul_int(Self::get_total_liquid_currency()); - T::Currency::deposit(liquid_currency_id, &T::TreasuryAccount::get(), inflate_liquid_amount)?; + // Staking rewards goes to T::OnFeeDeposit + T::OnFeeDeposit::on_fee_deposit( + IncomeSource::HomaStakingRewardFee, + None, + liquid_currency_id, + inflate_liquid_amount, + )?; } } diff --git a/modules/homa/src/mock.rs b/modules/homa/src/mock.rs index 00f0a775eb..6f813855cc 100644 --- a/modules/homa/src/mock.rs +++ b/modules/homa/src/mock.rs @@ -167,11 +167,25 @@ ord_parameter_types! { pub const HomaAdmin: AccountId = DAVE; } +parameter_types! { + pub AlternativeSwapPathJointList: Vec> = vec![]; +} +impl module_fees::Config for Runtime { + type Event = Event; + type UpdateOrigin = EnsureRoot; + type Currency = Balances; + type Currencies = Currencies; + type DEX = (); + type WeightInfo = (); + type NativeCurrencyId = GetNativeCurrencyId; + type AllocationPeriod = ConstU64<10>; + type DexSwapJointList = AlternativeSwapPathJointList; +} + parameter_types! { pub const StakingCurrencyId: CurrencyId = STAKING_CURRENCY_ID; pub const LiquidCurrencyId: CurrencyId = LIQUID_CURRENCY_ID; pub const HomaPalletId: PalletId = PalletId(*b"aca/homa"); - pub const TreasuryAccount: AccountId = HOMA_TREASURY; pub DefaultExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10); pub ActiveSubAccountsIndexList: Vec = vec![0, 1, 2]; pub const BondingDuration: EraIndex = 28; @@ -187,7 +201,6 @@ impl Config for Runtime { type StakingCurrencyId = StakingCurrencyId; type LiquidCurrencyId = LiquidCurrencyId; type PalletId = HomaPalletId; - type TreasuryAccount = TreasuryAccount; type DefaultExchangeRate = DefaultExchangeRate; type ActiveSubAccountsIndexList = ActiveSubAccountsIndexList; type BondingDuration = BondingDuration; @@ -195,6 +208,7 @@ impl Config for Runtime { type RedeemThreshold = RedeemThreshold; type RelayChainBlockNumber = MockRelayBlockNumberProvider; type XcmInterface = MockHomaSubAccountXcm; + type OnFeeDeposit = Fees; type WeightInfo = (); } @@ -207,11 +221,12 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Homa: homa::{Pallet, Call, Storage, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Tokens: orml_tokens::{Pallet, Storage, Event, Config}, - Currencies: module_currencies::{Pallet, Call, Event}, + System: frame_system, + Homa: homa, + Balances: pallet_balances, + Tokens: orml_tokens, + Currencies: module_currencies, + Fees: module_fees, } ); diff --git a/modules/homa/src/tests.rs b/modules/homa/src/tests.rs index 4c7ab9b641..8e960a4be0 100644 --- a/modules/homa/src/tests.rs +++ b/modules/homa/src/tests.rs @@ -19,13 +19,24 @@ //! Unit tests for the Homa Module #![cfg(test)] - use super::*; use frame_support::{assert_noop, assert_ok}; use mock::{Event, *}; +use module_fees::PoolPercent; use orml_traits::MultiCurrency; use sp_runtime::{traits::BadOrigin, FixedPointNumber}; +fn setup_fees_distribution() { + assert_ok!(Fees::set_income_fee( + Origin::root(), + IncomeSource::HomaStakingRewardFee, + vec![PoolPercent { + pool: HOMA_TREASURY, + rate: Rate::one(), + }], + )); +} + #[test] fn mint_works() { ExtBuilder::default() @@ -699,6 +710,8 @@ fn process_staking_rewards_works() { .balances(vec![(ALICE, LIQUID_CURRENCY_ID, 40_000_000)]) .build() .execute_with(|| { + setup_fees_distribution(); + assert_ok!(Homa::reset_ledgers( Origin::signed(HomaAdmin::get()), vec![(0, Some(3_000_000), None), (1, Some(1_000_000), None),] @@ -726,7 +739,7 @@ fn process_staking_rewards_works() { ); assert_eq!(Homa::get_total_bonded(), 4_000_000); assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 40_000_000); - assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &TreasuryAccount::get()), 0); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 0); // accumulate staking rewards, no commission assert_ok!(Homa::process_staking_rewards(1, 0)); @@ -746,7 +759,7 @@ fn process_staking_rewards_works() { ); assert_eq!(Homa::get_total_bonded(), 4_800_000); assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 40_000_000); - assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &TreasuryAccount::get()), 0); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 0); assert_ok!(Homa::update_homa_params( Origin::signed(HomaAdmin::get()), @@ -774,10 +787,7 @@ fn process_staking_rewards_works() { ); assert_eq!(Homa::get_total_bonded(), 5_760_000); assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 40_677_966); - assert_eq!( - Currencies::free_balance(LIQUID_CURRENCY_ID, &TreasuryAccount::get()), - 677_966 - ); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 677_966); }); } @@ -1190,6 +1200,8 @@ fn bump_current_era_works() { .balances(vec![(ALICE, STAKING_CURRENCY_ID, 100_000_000)]) .build() .execute_with(|| { + setup_fees_distribution(); + assert_ok!(Homa::update_homa_params( Origin::signed(HomaAdmin::get()), Some(20_000_000), @@ -1212,7 +1224,7 @@ fn bump_current_era_works() { assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 0); assert_eq!(Currencies::free_balance(STAKING_CURRENCY_ID, &Homa::account_id()), 0); assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &Homa::account_id()), 0); - assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &TreasuryAccount::get()), 0); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 0); assert_ok!(Homa::mint(Origin::signed(ALICE), 30_000_000)); assert_eq!(Homa::to_bond_pool(), 30_000_000); @@ -1253,7 +1265,7 @@ fn bump_current_era_works() { assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 297_029_702); assert_eq!(Currencies::free_balance(STAKING_CURRENCY_ID, &Homa::account_id()), 0); assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &Homa::account_id()), 0); - assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &TreasuryAccount::get()), 0); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 0); // bump era to #2, // accumulate staking reward and draw commission @@ -1284,10 +1296,7 @@ fn bump_current_era_works() { assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 297_619_046); assert_eq!(Currencies::free_balance(STAKING_CURRENCY_ID, &Homa::account_id()), 0); assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &Homa::account_id()), 0); - assert_eq!( - Currencies::free_balance(LIQUID_CURRENCY_ID, &TreasuryAccount::get()), - 589_344 - ); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 589_344); // assuming now staking has no rewards any more. assert_ok!(Homa::update_homa_params( @@ -1346,10 +1355,7 @@ fn bump_current_era_works() { assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 17_619_046); assert_eq!(Currencies::free_balance(STAKING_CURRENCY_ID, &Homa::account_id()), 0); assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &Homa::account_id()), 0); - assert_eq!( - Currencies::free_balance(LIQUID_CURRENCY_ID, &TreasuryAccount::get()), - 589_344 - ); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 589_344); // bump era to #31, // will process scheduled unbonded @@ -1377,9 +1383,68 @@ fn bump_current_era_works() { 26_605_824 ); assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &Homa::account_id()), 0); - assert_eq!( - Currencies::free_balance(LIQUID_CURRENCY_ID, &TreasuryAccount::get()), - 589_344 - ); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 589_344); }); } + +#[test] +fn staking_reward_fee_distribution_works() { + ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); + // 100% sstaking reward and 100% commision rate + assert_ok!(Homa::update_homa_params( + Origin::signed(HomaAdmin::get()), + Some(1_000_000_000), + Some(Rate::one()), + Some(Rate::one()), + Some(Rate::saturating_from_rational(1, 100)), + )); + + assert_ok!(Homa::reset_ledgers( + Origin::signed(HomaAdmin::get()), + vec![(0, Some(50_000), None), (1, Some(50_000), None),] + )); + assert_ok!(Currencies::deposit(LIQUID_CURRENCY_ID, &ALICE, 100_000)); + + assert_eq!(Homa::get_total_bonded(), 100_000); + + // Forward 1 era + assert_ok!(Homa::process_staking_rewards(1, 0)); + + // as per setup, 100% of staking reward goes to HOMA_TREASURY + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &HOMA_TREASURY), 100_000); + + assert_ok!(Fees::set_income_fee( + Origin::root(), + IncomeSource::HomaStakingRewardFee, + vec![ + PoolPercent { + pool: BOB, + rate: Rate::saturating_from_rational(2, 10), + }, + PoolPercent { + pool: CHARLIE, + rate: Rate::saturating_from_rational(3, 10), + }, + PoolPercent { + pool: DAVE, + rate: Rate::saturating_from_rational(5, 10), + } + ], + )); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &BOB), 0); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &CHARLIE), 0); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &DAVE), 0); + + assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 200_000); + + // Forward 1 era + assert_ok!(Homa::process_staking_rewards(2, 1)); + assert_eq!(Currencies::total_issuance(LIQUID_CURRENCY_ID), 400_000); + + // Liquid reward is distributed into + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &BOB), 40_000); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &CHARLIE), 60_000); + assert_eq!(Currencies::free_balance(LIQUID_CURRENCY_ID, &DAVE), 100_000); + }); +} diff --git a/node/service/src/chain_spec/acala.rs b/node/service/src/chain_spec/acala.rs index 9ba10c2b8d..f5268c2501 100644 --- a/node/service/src/chain_spec/acala.rs +++ b/node/service/src/chain_spec/acala.rs @@ -194,5 +194,6 @@ fn acala_dev_genesis( polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(2), }, + fees: Default::default(), } } diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 389ca75701..53ffe83079 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -315,7 +315,7 @@ fn testnet_genesis( evm_accounts: Vec, ) -> mandala_runtime::GenesisConfig { use mandala_runtime::{ - dollar, get_all_module_accounts, AssetRegistryConfig, BalancesConfig, CdpEngineConfig, CdpTreasuryConfig, + get_all_module_accounts, AssetRegistryConfig, BalancesConfig, CdpEngineConfig, CdpTreasuryConfig, CollatorSelectionConfig, DexConfig, EVMConfig, EnabledTradingPairs, ExistentialDeposits, FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, IndicesConfig, NativeTokenExistentialDeposit, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, @@ -516,7 +516,7 @@ fn mandala_genesis( endowed_accounts: Vec, ) -> mandala_runtime::GenesisConfig { use mandala_runtime::{ - cent, dollar, get_all_module_accounts, AssetRegistryConfig, BalancesConfig, CdpEngineConfig, CdpTreasuryConfig, + cent, get_all_module_accounts, AssetRegistryConfig, BalancesConfig, CdpEngineConfig, CdpTreasuryConfig, CollatorSelectionConfig, DexConfig, EVMConfig, EnabledTradingPairs, ExistentialDeposits, FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, IndicesConfig, NativeTokenExistentialDeposit, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, diff --git a/runtime/acala/Cargo.toml b/runtime/acala/Cargo.toml index 88a070cbe1..6cee066ce6 100644 --- a/runtime/acala/Cargo.toml +++ b/runtime/acala/Cargo.toml @@ -107,6 +107,7 @@ module-evm = { path = "../../modules/evm", default-features = false } module-evm-accounts = { path = "../../modules/evm-accounts", default-features = false } module-evm-bridge = { path = "../../modules/evm-bridge", default-features = false } module-evm-rpc-runtime-api = { path = "../../modules/evm/rpc/runtime_api", default-features = false } +module-fees = { path = "../../modules/fees", default-features = false } module-honzon = { path = "../../modules/honzon", default-features = false } module-loans = { path = "../../modules/loans", default-features = false } module-nft = { path = "../../modules/nft", default-features = false } @@ -232,6 +233,7 @@ std = [ "module-evm/std", "module-evm-accounts/std", "module-evm-bridge/std", + "module-fees/std", "module-honzon/std", "module-loans/std", "module-nft/std", diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index 8bb90b760e..2a6085ac17 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -70,7 +70,7 @@ pub use frame_support::{ pallet_prelude::InvalidTransaction, parameter_types, traits::{ - ConstBool, ConstU128, ConstU16, ConstU32, Contains, ContainsLengthBound, Currency as PalletCurrency, + ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, Contains, ContainsLengthBound, Currency as PalletCurrency, EnsureOrigin, EqualPrivilegeOnly, Everything, Get, Imbalance, InstanceFilter, IsSubType, IsType, KeyOwnerProofSystem, LockIdentifier, Nothing, OnRuntimeUpgrade, OnUnbalanced, Randomness, SortedMembers, U128CurrencyToVote, @@ -1444,7 +1444,6 @@ impl module_homa::Config for Runtime { type StakingCurrencyId = GetStakingCurrencyId; type LiquidCurrencyId = GetLiquidCurrencyId; type PalletId = HomaPalletId; - type TreasuryAccount = HomaTreasuryAccount; type DefaultExchangeRate = DefaultExchangeRate; type ActiveSubAccountsIndexList = ActiveSubAccountsIndexList; type BondingDuration = ConstU32<28>; @@ -1452,9 +1451,22 @@ impl module_homa::Config for Runtime { type RedeemThreshold = RedeemThreshold; type RelayChainBlockNumber = RelaychainBlockNumberProvider; type XcmInterface = XcmInterface; + type OnFeeDeposit = Fees; type WeightInfo = weights::module_homa::WeightInfo; } +impl module_fees::Config for Runtime { + type Event = Event; + type WeightInfo = (); + type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; + type Currency = Balances; + type Currencies = Currencies; + type NativeCurrencyId = GetNativeCurrencyId; + type AllocationPeriod = ConstU32<10>; + type DEX = Dex; + type DexSwapJointList = AlternativeSwapPathJointList; +} + pub fn create_x2_parachain_multilocation(index: u16) -> MultiLocation { MultiLocation::new( 1, @@ -1605,6 +1617,7 @@ construct_runtime!( Currencies: module_currencies = 12, Vesting: orml_vesting = 13, TransactionPayment: module_transaction_payment = 14, + Fees: module_fees = 15, // Treasury Treasury: pallet_treasury = 20, diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index fa57a99d95..f60dcbb23a 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -53,6 +53,7 @@ module-prices = { path = "../../modules/prices", default-features = false } module-transaction-payment = { path = "../../modules/transaction-payment", default-features = false } module-nft = { path = "../../modules/nft", default-features = false } module-dex = { path = "../../modules/dex", default-features = false } +module-fees = { path = "../../modules/fees", default-features = false } module-evm-accounts = { path = "../../modules/evm-accounts", default-features = false } module-homa = {path = "../../modules/homa", default-features = false } module-asset-registry = { path = "../../modules/asset-registry", default-features = false, optional = true } @@ -114,6 +115,7 @@ std = [ "module-evm-accounts/std", "module-asset-registry/std", "module-evm-bridge/std", + "module-fees/std", "xcm/std", "xcm-executor/std", diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 9600a0479d..1bf84b098d 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -500,7 +500,8 @@ parameter_types! { pub HonzonInsuranceRewardPool: AccountId = PalletId(*b"aca/hirp").into_account(); pub HonzonLiquitationRewardPool: AccountId = PalletId(*b"aca/hlrp").into_account(); pub StakingRewardPool: AccountId = PalletId(*b"aca/strp").into_account(); - pub CollatorsRewardPool: AccountId = PalletId(*b"aca/clrp").into_account(); + pub CollatorsRewardPoolPalletId: PalletId = PalletId(*b"aca/clrp"); + pub CollatorsRewardPool: AccountId = CollatorsRewardPoolPalletId::get().into_account(); pub EcosystemRewardPool: AccountId = PalletId(*b"aca/esrp").into_account(); } diff --git a/runtime/common/src/precompile/mock.rs b/runtime/common/src/precompile/mock.rs index 7c835f6f79..99133b84e7 100644 --- a/runtime/common/src/precompile/mock.rs +++ b/runtime/common/src/precompile/mock.rs @@ -549,6 +549,21 @@ impl HomaSubAccountXcm for MockHomaSubAccountXcm { } } +parameter_types! { + pub AlternativeSwapPathJointList: Vec> = vec![]; +} +impl module_fees::Config for Test { + type Event = Event; + type UpdateOrigin = EnsureRoot; + type Currency = Balances; + type Currencies = Currencies; + type DEX = (); + type WeightInfo = (); + type NativeCurrencyId = GetNativeCurrencyId; + type AllocationPeriod = ConstU32<10>; + type DexSwapJointList = AlternativeSwapPathJointList; +} + ord_parameter_types! { pub const HomaAdmin: AccountId = ALICE; } @@ -572,7 +587,6 @@ impl module_homa::Config for Test { type StakingCurrencyId = StakingCurrencyId; type LiquidCurrencyId = LiquidCurrencyId; type PalletId = HomaPalletId; - type TreasuryAccount = HomaTreasuryAccount; type DefaultExchangeRate = DefaultExchangeRate; type ActiveSubAccountsIndexList = ActiveSubAccountsIndexList; type BondingDuration = BondingDuration; @@ -580,6 +594,7 @@ impl module_homa::Config for Test { type RedeemThreshold = RedeemThreshold; type RelayChainBlockNumber = MockRelayBlockNumberProvider; type XcmInterface = MockHomaSubAccountXcm; + type OnFeeDeposit = Fees; type WeightInfo = (); } @@ -652,6 +667,7 @@ frame_support::construct_runtime!( IdleScheduler: module_idle_scheduler, Homa: module_homa, StableAsset: nutsfinance_stable_asset, + Fees: module_fees, } ); diff --git a/runtime/integration-tests/src/treasury.rs b/runtime/integration-tests/src/treasury.rs index 5ca92b53c7..dec7260617 100644 --- a/runtime/integration-tests/src/treasury.rs +++ b/runtime/integration-tests/src/treasury.rs @@ -237,6 +237,7 @@ mod mandala_only_tests { use frame_support::{pallet_prelude::Decode, traits::OnUnbalanced}; use module_fees::DistributeTxFees; use pallet_authorship::EventHandler; + use runtime_common::{CollatorsRewardPool, NetworkTreasuryPool}; #[test] fn treasury_handles_collator_rewards_correctly() { @@ -251,7 +252,8 @@ mod mandala_only_tests { AccountId::from(ALICE) ))); - let pot_account_id = CollatorSelection::account_id(); + let pot_account_id = CollatorsRewardPool::get(); + let network_treasury = NetworkTreasuryPool::get(); // Currently pot has ExistentialDeposits assert_eq!( Currencies::free_balance(NATIVE_CURRENCY, &pot_account_id), @@ -274,12 +276,20 @@ mod mandala_only_tests { Currencies::free_balance(NATIVE_CURRENCY, &pot_account_id), 299_999_999_998 ); + assert_eq!( + Currencies::free_balance(NATIVE_CURRENCY, &network_treasury), + 899_999_999_992 + ); CollatorSelection::note_author(AccountId::from(BOB)); assert_eq!( Currencies::free_balance(NATIVE_CURRENCY, &pot_account_id), 299_999_999_998 ); + assert_eq!( + Currencies::free_balance(NATIVE_CURRENCY, &network_treasury), + 899_999_999_992 + ); assert_eq!(Currencies::free_balance(NATIVE_CURRENCY, &AccountId::from(BOB)), 0); // Put a little more money into the pot @@ -293,14 +303,22 @@ mod mandala_only_tests { Currencies::free_balance(NATIVE_CURRENCY, &pot_account_id), 300_000_000_000 ); + assert_eq!( + Currencies::free_balance(NATIVE_CURRENCY, &network_treasury), + 900_000_000_000 + ); - // Splits half of 300_000_000_000 to BOB + // Splits half of available pot to BOB: (pot - ED) / 2 = (30c - 10c) / 2 = 10c CollatorSelection::note_author(AccountId::from(BOB)); assert_eq!( Currencies::free_balance(NATIVE_CURRENCY, &pot_account_id), 200_000_000_000 ); + assert_eq!( + Currencies::free_balance(NATIVE_CURRENCY, &network_treasury), + 900_000_000_000 + ); assert_eq!( Currencies::free_balance(NATIVE_CURRENCY, &AccountId::from(BOB)), 100_000_000_000 diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 0e28530839..622a30092f 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -66,7 +66,6 @@ use orml_traits::{ }; use pallet_transaction_payment::RuntimeDispatchInfo; -use frame_support::traits::ConstU64; pub use frame_support::{ construct_runtime, log, parameter_types, traits::{ @@ -1483,7 +1482,6 @@ impl module_homa::Config for Runtime { type StakingCurrencyId = GetStakingCurrencyId; type LiquidCurrencyId = GetLiquidCurrencyId; type PalletId = HomaPalletId; - type TreasuryAccount = HomaTreasuryAccount; type DefaultExchangeRate = DefaultExchangeRate; type ActiveSubAccountsIndexList = ActiveSubAccountsIndexList; type BondingDuration = ConstU32<28>; @@ -1491,6 +1489,7 @@ impl module_homa::Config for Runtime { type RedeemThreshold = RedeemThreshold; type RelayChainBlockNumber = RelaychainBlockNumberProvider; type XcmInterface = XcmInterface; + type OnFeeDeposit = Fees; type WeightInfo = weights::module_homa::WeightInfo; } diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 2b528f1fca..9a78391aa4 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -33,7 +33,6 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use codec::{Decode, DecodeLimit, Encode}; use cumulus_pallet_parachain_system::RelaychainBlockNumberProvider; use frame_support::pallet_prelude::InvalidTransaction; -use frame_support::traits::ConstU64; pub use frame_support::{ construct_runtime, log, parameter_types, traits::{ @@ -105,7 +104,7 @@ pub use primitives::{ }; pub use runtime_common::{ calculate_asset_ratio, cent, dollar, microcent, millicent, AcalaDropAssets, AllPrecompiles, CollatorsRewardPool, - EcosystemRewardPool, EnsureRootOrAllGeneralCouncil, EnsureRootOrAllTechnicalCommittee, + CollatorsRewardPoolPalletId, EcosystemRewardPool, EnsureRootOrAllGeneralCouncil, EnsureRootOrAllTechnicalCommittee, EnsureRootOrHalfFinancialCouncil, EnsureRootOrHalfGeneralCouncil, EnsureRootOrHalfHomaCouncil, EnsureRootOrOneGeneralCouncil, EnsureRootOrOneThirdsTechnicalCommittee, EnsureRootOrThreeFourthsGeneralCouncil, EnsureRootOrTwoThirdsGeneralCouncil, EnsureRootOrTwoThirdsTechnicalCommittee, ExchangeRate, @@ -168,7 +167,6 @@ parameter_types! { pub const HomaPalletId: PalletId = PalletId(*b"aca/homa"); pub const HomaTreasuryPalletId: PalletId = PalletId(*b"aca/hmtr"); pub const IncentivesPalletId: PalletId = PalletId(*b"aca/inct"); - pub const CollatorPotId: PalletId = PalletId(*b"aca/cpot"); // Treasury reserve pub const TreasuryReservePalletId: PalletId = PalletId(*b"aca/reve"); pub const PhragmenElectionPalletId: LockIdentifier = *b"aca/phre"; @@ -195,7 +193,6 @@ pub fn get_all_module_accounts() -> Vec { HomaTreasuryPalletId::get().into_account(), IncentivesPalletId::get().into_account(), TreasuryReservePalletId::get().into_account(), - CollatorPotId::get().into_account(), StarportPalletId::get().into_account(), UnreleasedNativeVaultAccountId::get(), StableAssetPalletId::get().into_account(), @@ -298,7 +295,7 @@ impl module_collator_selection::Config for Runtime { type Currency = Balances; type ValidatorSet = Session; type UpdateOrigin = EnsureRootOrHalfGeneralCouncil; - type PotId = CollatorPotId; + type PotId = CollatorsRewardPoolPalletId; type MinCandidates = ConstU32<5>; type MaxCandidates = ConstU32<200>; type MaxInvulnerables = ConstU32<50>; @@ -1213,8 +1210,6 @@ parameter_types! { pub DefaultFeeTokens: Vec = vec![AUSD, DOT, LDOT, RENBTC]; pub const CustomFeeSurplus: Percent = Percent::from_percent(50); pub const AlternativeFeeSurplus: Percent = Percent::from_percent(25); - // 20% of tx fee deposit to collator, 80% to treasury. - pub ToCollcator: AccountId = CollatorPotId::get().into_account(); } impl module_transaction_payment::Config for Runtime { @@ -1341,7 +1336,6 @@ impl module_homa::Config for Runtime { type StakingCurrencyId = GetStakingCurrencyId; type LiquidCurrencyId = GetLiquidCurrencyId; type PalletId = HomaPalletId; - type TreasuryAccount = HomaTreasuryAccount; type DefaultExchangeRate = DefaultExchangeRate; type ActiveSubAccountsIndexList = ActiveSubAccountsIndexList; type BondingDuration = ConstU32<28>; @@ -1349,6 +1343,7 @@ impl module_homa::Config for Runtime { type RedeemThreshold = RedeemThreshold; type RelayChainBlockNumber = RelaychainBlockNumberProvider; type XcmInterface = XcmInterface; + type OnFeeDeposit = Fees; type WeightInfo = weights::module_homa::WeightInfo; } From 2c7211cb81c4562ab292f69ddae874d88432d4d1 Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 14 Jun 2022 21:36:37 +0800 Subject: [PATCH 24/49] update to v0.9.22 --- ecosystem-modules/stable-asset | 2 +- evm-tests | 2 +- modules/fees/Cargo.toml | 14 +++++++------- modules/fees/src/mock.rs | 3 +++ 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/ecosystem-modules/stable-asset b/ecosystem-modules/stable-asset index bc7a43e0c6..83dc2a7787 160000 --- a/ecosystem-modules/stable-asset +++ b/ecosystem-modules/stable-asset @@ -1 +1 @@ -Subproject commit bc7a43e0c620c89b1cd98597fe4b8de6646b9083 +Subproject commit 83dc2a7787c10fdcfc1af851792ce1bf54408354 diff --git a/evm-tests b/evm-tests index 49e31727de..3f18ead64d 160000 --- a/evm-tests +++ b/evm-tests @@ -1 +1 @@ -Subproject commit 49e31727de2db916f9f4b9d08b2f7d9aa1217be6 +Subproject commit 3f18ead64d0adbf35312a2bfabb00b02be7f7c9c diff --git a/modules/fees/Cargo.toml b/modules/fees/Cargo.toml index a410ad1036..013d48333f 100644 --- a/modules/fees/Cargo.toml +++ b/modules/fees/Cargo.toml @@ -9,11 +9,11 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = scale-info = { version = "2.1", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } orml-traits = { package = "orml-traits", path = "../../orml/traits", default-features = false } orml-tokens = { package = "orml-tokens", path = "../../orml/tokens", default-features = false } @@ -24,8 +24,8 @@ primitives = { package = "acala-primitives", path = "../../primitives", default- paste = "1.0" [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" } orml-tokens = { path = "../../orml/tokens" } module-currencies = { path = "../../modules/currencies" } module-dex = { path = "../../modules/dex" } diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index 8a7da93b01..840abaef3d 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -33,6 +33,7 @@ use orml_traits::parameter_type_with_key; use primitives::{ AccountId, Amount, Balance, BlockNumber, CurrencyId, IncomeSource, ReserveIdentifier, TokenSymbol, TradingPair, }; +use sp_core::H160; use sp_runtime::traits::AccountIdConversion; use support::mocks::MockAddressMapping; @@ -105,6 +106,7 @@ pub type AdaptedBasicCurrency = module_currencies::BasicCurrencyAdapter; From 94a393f9826090e1135f59387b61e0195a45986c Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 14 Jun 2022 23:11:47 +0800 Subject: [PATCH 25/49] benchmark --- modules/fees/src/mock.rs | 12 ++-- modules/transaction-payment/src/tests.rs | 2 - runtime/acala/src/benchmarking/mod.rs | 3 + runtime/acala/src/lib.rs | 7 ++- runtime/common/src/precompile/mock.rs | 3 - runtime/karura/src/benchmarking/mod.rs | 3 + runtime/karura/src/lib.rs | 1 + runtime/mandala/src/benchmarking/fees.rs | 72 ++++++++++++++++++++++++ runtime/mandala/src/benchmarking/mod.rs | 1 + runtime/mandala/src/lib.rs | 1 + 10 files changed, 93 insertions(+), 12 deletions(-) create mode 100644 runtime/mandala/src/benchmarking/fees.rs diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index 840abaef3d..e937a60769 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -188,12 +188,12 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Tokens: orml_tokens::{Pallet, Storage, Event, Config}, - Currencies: module_currencies::{Pallet, Call, Event}, - Fees: fees::{Pallet, Storage, Call, Event, Config}, - DEX: module_dex::{Pallet, Storage, Call, Event, Config}, + System: frame_system, + Balances: pallet_balances, + Tokens: orml_tokens, + Currencies: module_currencies, + Fees: fees, + DEX: module_dex, } ); diff --git a/modules/transaction-payment/src/tests.rs b/modules/transaction-payment/src/tests.rs index cf244b94e0..1137a296b6 100644 --- a/modules/transaction-payment/src/tests.rs +++ b/modules/transaction-payment/src/tests.rs @@ -605,8 +605,6 @@ fn charges_fee_when_validate_with_fee_currency_call() { sub_ausd_usd + fee_amount * 10, Currencies::free_balance(AUSD, &ausd_acc) ); - println!("{:?}", Currencies::free_balance(ACA, &ALICE)); - println!("{:?}", Currencies::free_balance(AUSD, &ALICE)); let fee: Balance = 50 * 2 + 100; let fee_perc = CustomFeeSurplus::get(); diff --git a/runtime/acala/src/benchmarking/mod.rs b/runtime/acala/src/benchmarking/mod.rs index ec81dd2ba0..ed4cba5aa1 100644 --- a/runtime/acala/src/benchmarking/mod.rs +++ b/runtime/acala/src/benchmarking/mod.rs @@ -59,6 +59,9 @@ pub mod evm { pub mod evm_accounts { include!("../../../mandala/src/benchmarking/evm_accounts.rs"); } +pub mod fees { + include!("../../../mandala/src/benchmarking/fees.rs"); +} pub mod homa { include!("../../../mandala/src/benchmarking/homa.rs"); } diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index fdffb51ef4..00d652319d 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -1464,6 +1464,10 @@ impl module_homa::Config for Runtime { type WeightInfo = weights::module_homa::WeightInfo; } +parameter_types! { + pub const AllocationPeriod: BlockNumber = 7 * DAYS; +} + impl module_fees::Config for Runtime { type Event = Event; type WeightInfo = (); @@ -1471,7 +1475,7 @@ impl module_fees::Config for Runtime { type Currency = Balances; type Currencies = Currencies; type NativeCurrencyId = GetNativeCurrencyId; - type AllocationPeriod = ConstU32<10>; + type AllocationPeriod = AllocationPeriod; type DEX = Dex; type DexSwapJointList = AlternativeSwapPathJointList; } @@ -1792,6 +1796,7 @@ mod benches { [module_cdp_engine, benchmarking::cdp_engine] [module_emergency_shutdown, benchmarking::emergency_shutdown] [module_evm, benchmarking::evm] + [module_fees, benchmarking::fees] [module_homa, benchmarking::homa] [module_honzon, benchmarking::honzon] [module_cdp_treasury, benchmarking::cdp_treasury] diff --git a/runtime/common/src/precompile/mock.rs b/runtime/common/src/precompile/mock.rs index 32668f3ef5..1e8ccee162 100644 --- a/runtime/common/src/precompile/mock.rs +++ b/runtime/common/src/precompile/mock.rs @@ -675,9 +675,6 @@ impl HomaSubAccountXcm for MockHomaSubAccountXcm { } } -parameter_types! { - pub AlternativeSwapPathJointList: Vec> = vec![]; -} impl module_fees::Config for Test { type Event = Event; type UpdateOrigin = EnsureRoot; diff --git a/runtime/karura/src/benchmarking/mod.rs b/runtime/karura/src/benchmarking/mod.rs index 1a3252be2c..6c9fc983e3 100644 --- a/runtime/karura/src/benchmarking/mod.rs +++ b/runtime/karura/src/benchmarking/mod.rs @@ -59,6 +59,9 @@ pub mod evm { pub mod evm_accounts { include!("../../../mandala/src/benchmarking/evm_accounts.rs"); } +pub mod fees { + include!("../../../mandala/src/benchmarking/fees.rs"); +} pub mod homa { include!("../../../mandala/src/benchmarking/homa.rs"); } diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 1504df2f20..d67c9e4497 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1844,6 +1844,7 @@ mod benches { [module_cdp_engine, benchmarking::cdp_engine] [module_emergency_shutdown, benchmarking::emergency_shutdown] [module_evm, benchmarking::evm] + [module_fees, benchmarking::fees] [module_homa, benchmarking::homa] [module_honzon, benchmarking::honzon] [module_cdp_treasury, benchmarking::cdp_treasury] diff --git a/runtime/mandala/src/benchmarking/fees.rs b/runtime/mandala/src/benchmarking/fees.rs new file mode 100644 index 0000000000..1290bf06f1 --- /dev/null +++ b/runtime/mandala/src/benchmarking/fees.rs @@ -0,0 +1,72 @@ +// This file is part of Acala. + +// Copyright (C) 2020-2022 Acala Foundation. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +use crate::{Event, Runtime, System}; +use frame_system::RawOrigin; +use module_fees::PoolPercent; +use orml_benchmarking::runtime_benchmarks; +use primitives::{AccountId, Balance, IncomeSource}; +use sp_runtime::{FixedPointNumber, FixedU128}; +use sp_std::prelude::*; + +fn assert_last_event(generic_event: Event) { + System::assert_last_event(generic_event.into()); +} + +runtime_benchmarks! { + { Runtime, module_fees } + + set_income_fee { + let pool = PoolPercent { + pool: runtime_common::NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(1, 1), + }; + let pools = vec![pool]; + }: _(RawOrigin::Root, IncomeSource::TxFee, pools.clone()) + verify { + assert_last_event(module_fees::Event::IncomeFeeSet { + income: IncomeSource::TxFee, + pools, + }.into()); + } + + set_treasury_pool { + let pool = PoolPercent { + pool: runtime_common::NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(1, 1), + }; + let threshold: Balance = 100; + let treasury: AccountId = runtime_common::NetworkTreasuryPool::get(); + let pools = vec![pool]; + }: _(RawOrigin::Root, treasury.clone(), threshold, pools.clone()) + verify { + assert_last_event(module_fees::Event::TreasuryPoolSet { + treasury, + pools, + }.into()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::benchmarking::utils::tests::new_test_ext; + use orml_benchmarking::impl_benchmark_test_suite; + + impl_benchmark_test_suite!(new_test_ext(),); +} diff --git a/runtime/mandala/src/benchmarking/mod.rs b/runtime/mandala/src/benchmarking/mod.rs index 0fcde88176..8f3ec750bb 100644 --- a/runtime/mandala/src/benchmarking/mod.rs +++ b/runtime/mandala/src/benchmarking/mod.rs @@ -38,6 +38,7 @@ pub mod earning; pub mod emergency_shutdown; pub mod evm; pub mod evm_accounts; +pub mod fees; pub mod homa; pub mod honzon; pub mod idle_scheduler; diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 4c71f700fc..69ff1bd02b 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -2062,6 +2062,7 @@ mod benches { [module_earning, benchmarking::earning] [module_emergency_shutdown, benchmarking::emergency_shutdown] [module_evm, benchmarking::evm] + [module_fees, benchmarking::fees] [module_homa, benchmarking::homa] [module_honzon, benchmarking::honzon] [module_cdp_treasury, benchmarking::cdp_treasury] From 7314463ea0a3c7500f2377a78724cde0e7f783fc Mon Sep 17 00:00:00 2001 From: zqh Date: Wed, 15 Jun 2022 09:40:32 +0800 Subject: [PATCH 26/49] build_pool_percents helper method --- modules/fees/src/lib.rs | 26 +++++++++--------- modules/fees/src/tests.rs | 33 ++++++++++++----------- modules/homa/src/tests.rs | 2 +- runtime/mandala/src/benchmarking/fees.rs | 34 ++++++++++++++++++++++-- 4 files changed, 62 insertions(+), 33 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 4577588e4e..07749028b9 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -62,6 +62,16 @@ pub struct PoolPercent { pub rate: FixedU128, } +/// helper method to create `PoolPercent` list by tuple. +pub fn build_pool_percents(list: Vec<(AccountId, u32)>) -> Vec> { + list.iter() + .map(|data| PoolPercent { + pool: data.clone().0, + rate: FixedU128::saturating_from_rational(data.1, 100), + }) + .collect() +} + pub use module::*; #[frame_support::pallet] @@ -176,23 +186,11 @@ pub mod module { impl GenesisBuild for GenesisConfig { fn build(&self) { self.incomes.iter().for_each(|(income, pools)| { - let pool_rates = pools - .iter() - .map(|pool_rate| PoolPercent { - pool: pool_rate.clone().0, - rate: FixedU128::saturating_from_rational(pool_rate.1, 100), - }) - .collect(); + let pool_rates = build_pool_percents::(pools.clone()); let _ = >::do_set_treasury_rate(*income, pool_rates); }); self.treasuries.iter().for_each(|(treasury, threshold, pools)| { - let pool_rates = pools - .iter() - .map(|pool_rate| PoolPercent { - pool: pool_rate.clone().0, - rate: FixedU128::saturating_from_rational(pool_rate.1, 100), - }) - .collect(); + let pool_rates = build_pool_percents::(pools.clone()); let _ = >::do_set_incentive_rate(treasury.clone(), *threshold, pool_rates); }); } diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index db45aa8159..7e02e1b2b2 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -28,15 +28,6 @@ use mock::{Event, ExtBuilder, Origin, Runtime, System}; use primitives::AccountId; use sp_runtime::FixedU128; -fn build_pool_percents(list: Vec<(AccountId, u32)>) -> Vec> { - list.iter() - .map(|data| PoolPercent { - pool: data.clone().0, - rate: FixedU128::saturating_from_rational(data.clone().1, 100), - }) - .collect() -} - #[test] fn set_income_fee_works() { ExtBuilder::default().build().execute_with(|| { @@ -45,7 +36,8 @@ fn set_income_fee_works() { Error::::InvalidParams, ); - let pools = build_pool_percents(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)]); + let pools = + build_pool_percents::(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)]); assert_ok!(Fees::set_income_fee( Origin::signed(ALICE), IncomeSource::TxFee, @@ -71,7 +63,10 @@ fn set_treasury_pool_works() { Error::::InvalidParams, ); - let pools = build_pool_percents(vec![(StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 30)]); + let pools = build_pool_percents::(vec![ + (StakingRewardPool::get(), 70), + (CollatorsRewardPool::get(), 30), + ]); assert_ok!(Fees::set_treasury_pool( Origin::signed(ALICE), NetworkTreasuryPool::get(), @@ -105,9 +100,12 @@ fn set_treasury_pool_works() { #[test] fn invalid_pool_rates_works() { ExtBuilder::default().build().execute_with(|| { - let pools1 = build_pool_percents(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 20)]); - let pools2 = build_pool_percents(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 40)]); - let pools3 = build_pool_percents(vec![(StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 20)]); + let pools1 = + build_pool_percents::(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 20)]); + let pools2 = + build_pool_percents::(vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 40)]); + let pools3 = + build_pool_percents::(vec![(StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 20)]); assert_noop!( Fees::set_income_fee(Origin::signed(ALICE), IncomeSource::TxFee, pools1), @@ -154,7 +152,7 @@ fn tx_fee_allocation_works() { } // Update tx fee only to NetworkTreasuryPool account. - let pools = build_pool_percents(vec![(NetworkTreasuryPool::get(), 100)]); + let pools = build_pool_percents::(vec![(NetworkTreasuryPool::get(), 100)]); assert_ok!(Fees::set_income_fee( Origin::signed(ALICE), IncomeSource::TxFee, @@ -176,7 +174,10 @@ fn tx_fee_allocation_works() { } // Update tx fee to NetworkTreasuryPool and CollatorsRewardPool both 50%. - let pools = build_pool_percents(vec![(NetworkTreasuryPool::get(), 50), (CollatorsRewardPool::get(), 50)]); + let pools = build_pool_percents::(vec![ + (NetworkTreasuryPool::get(), 50), + (CollatorsRewardPool::get(), 50), + ]); assert_ok!(Fees::set_income_fee( Origin::signed(ALICE), IncomeSource::TxFee, diff --git a/modules/homa/src/tests.rs b/modules/homa/src/tests.rs index 52ae27bd1f..e2a6c9b1b9 100644 --- a/modules/homa/src/tests.rs +++ b/modules/homa/src/tests.rs @@ -1367,7 +1367,7 @@ fn bump_current_era_works() { fn staking_reward_fee_distribution_works() { ExtBuilder::default().build().execute_with(|| { setup_fees_distribution(); - // 100% sstaking reward and 100% commision rate + // 100% staking reward and 100% commission rate assert_ok!(Homa::update_homa_params( Origin::signed(HomaAdmin::get()), Some(1_000_000_000), diff --git a/runtime/mandala/src/benchmarking/fees.rs b/runtime/mandala/src/benchmarking/fees.rs index 1290bf06f1..a971b34df1 100644 --- a/runtime/mandala/src/benchmarking/fees.rs +++ b/runtime/mandala/src/benchmarking/fees.rs @@ -16,11 +16,12 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::{Event, Runtime, System}; +use crate::{Event, Fees, Origin, Runtime, System}; use frame_system::RawOrigin; use module_fees::PoolPercent; +use module_support::OnFeeDeposit; use orml_benchmarking::runtime_benchmarks; -use primitives::{AccountId, Balance, IncomeSource}; +use primitives::{AccountId, Balance, CurrencyId, IncomeSource, TokenSymbol}; use sp_runtime::{FixedPointNumber, FixedU128}; use sp_std::prelude::*; @@ -60,6 +61,35 @@ runtime_benchmarks! { pools, }.into()); } + + force_transfer_to_incentive { + let treasury: AccountId = runtime_common::NetworkTreasuryPool::get(); + + // set_income_fee + let pool = PoolPercent { + pool: runtime_common::NetworkTreasuryPool::get(), + rate: FixedU128::saturating_from_rational(1, 1), + }; + let _ = Fees::set_income_fee(Origin::root(), IncomeSource::TxFee, vec![pool]); + + // set_treasury_pool + let pool = PoolPercent { + pool: runtime_common::CollatorsRewardPool::get(), + rate: FixedU128::saturating_from_rational(1, 1), + }; + let threshold: Balance = 100; + let pools = vec![pool]; + let _ = Fees::set_treasury_pool(Origin::root(), treasury.clone(), threshold, pools.clone()); + + let _ = >::on_fee_deposit( + IncomeSource::TxFee, None, CurrencyId::Token(TokenSymbol::ACA), 10000); + }: _(RawOrigin::Root, treasury.clone()) + verify { + assert_last_event(module_fees::Event::IncentiveDistribution { + treasury, + amount: 100000010000, + }.into()); + } } #[cfg(test)] From c76827046b6303e415d5a1dca6b48d6cc6def12d Mon Sep 17 00:00:00 2001 From: zqh Date: Wed, 15 Jun 2022 11:14:09 +0800 Subject: [PATCH 27/49] fix benchmark --- modules/fees/src/tests.rs | 53 ++++++++++++++---------- runtime/mandala/src/benchmarking/fees.rs | 31 ++++++++------ 2 files changed, 48 insertions(+), 36 deletions(-) diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 7e02e1b2b2..4e0ce5f1ba 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -26,7 +26,6 @@ use frame_support::traits::{ExistenceRequirement, WithdrawReasons}; use frame_support::{assert_noop, assert_ok}; use mock::{Event, ExtBuilder, Origin, Runtime, System}; use primitives::AccountId; -use sp_runtime::FixedU128; #[test] fn set_income_fee_works() { @@ -294,7 +293,7 @@ fn on_fee_deposit_works() { } #[test] -fn distribution_incentive_works() { +fn force_transfer_to_incentive_works() { ExtBuilder::default() .balances(vec![(ALICE, ACA, 100000), (ALICE, AUSD, 10000)]) .build() @@ -305,14 +304,18 @@ fn distribution_incentive_works() { assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 800); assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 200); - assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + assert_ok!(Pallet::::force_transfer_to_incentive( + Origin::signed(ALICE), + NetworkTreasuryPool::get() + )); + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 640); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 280); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 80); System::assert_has_event(Event::Fees(crate::Event::IncentiveDistribution { treasury: NetworkTreasuryPool::get(), amount: 800, })); - assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 640); - assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 280); - assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 80); assert_ok!(DEX::add_liquidity( Origin::signed(ALICE), @@ -328,21 +331,24 @@ fn distribution_incentive_works() { assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 80); assert_eq!(Currencies::free_balance(AUSD, &CollatorsRewardPool::get()), 20); - assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + assert_ok!(Pallet::::force_transfer_to_incentive( + Origin::signed(ALICE), + NetworkTreasuryPool::get() + )); + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); + assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 0); + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 640 + 592); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 280 + 74); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 80 + 74); System::assert_has_event(Event::DEX(module_dex::Event::Swap { trader: NetworkTreasuryPool::get(), path: vec![AUSD, ACA], liquidity_changes: vec![80, 740], })); - assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 640 + 592); - assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 280 + 74); - assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 80 + 74); System::assert_has_event(Event::Fees(crate::Event::IncentiveDistribution { treasury: NetworkTreasuryPool::get(), amount: 740, })); - assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); - assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 0); }); } @@ -372,15 +378,15 @@ fn distribution_incentive_threshold_works() { assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); // then distribution to incentive pools + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 80); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 10); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 25 + 10); + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); System::assert_has_event(Event::Fees(crate::Event::IncentiveDistribution { treasury: NetworkTreasuryPool::get(), amount: 100, })); - assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 80); - assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 10); - assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 25 + 10); - assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 0); assert_ok!(DEX::add_liquidity( Origin::signed(ALICE), @@ -396,6 +402,7 @@ fn distribution_incentive_threshold_works() { assert_ok!(Pallet::::distribution_fees(pool_rates.clone(), AUSD, 10)); assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 8); assert_eq!(Currencies::free_balance(AUSD, &CollatorsRewardPool::get()), 2); + assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 79); System::assert_has_event(Event::DEX(module_dex::Event::Swap { @@ -407,22 +414,22 @@ fn distribution_incentive_threshold_works() { assert_ok!(Pallet::::distribution_fees(pool_rates, AUSD, 10)); assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 8); assert_eq!(Currencies::free_balance(AUSD, &CollatorsRewardPool::get()), 2 + 2); + assert_ok!(Pallet::::distribution_incentive(NetworkTreasuryPool::get())); + assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 80 + 125); + assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 35 + 15); + assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 10 + 15); + // due to percent round, there are some native token left in treasury account. + assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 2); + assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 0); System::assert_has_event(Event::DEX(module_dex::Event::Swap { trader: NetworkTreasuryPool::get(), path: vec![AUSD, ACA], liquidity_changes: vec![8, 78], })); - - assert_eq!(Currencies::free_balance(ACA, &StakingRewardPool::get()), 80 + 125); - assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 35 + 15); - assert_eq!(Currencies::free_balance(ACA, &EcosystemRewardPool::get()), 10 + 15); System::assert_has_event(Event::Fees(crate::Event::IncentiveDistribution { treasury: NetworkTreasuryPool::get(), amount: 79 + 78, })); - // due to percent round, there are some native token left in treasury account. - assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 2); - assert_eq!(Currencies::free_balance(AUSD, &NetworkTreasuryPool::get()), 0); }); } diff --git a/runtime/mandala/src/benchmarking/fees.rs b/runtime/mandala/src/benchmarking/fees.rs index a971b34df1..83730403f2 100644 --- a/runtime/mandala/src/benchmarking/fees.rs +++ b/runtime/mandala/src/benchmarking/fees.rs @@ -16,15 +16,17 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::{Event, Fees, Origin, Runtime, System}; +use crate::{Event, Fees, GetNativeCurrencyId, Origin, Runtime, System}; use frame_system::RawOrigin; use module_fees::PoolPercent; use module_support::OnFeeDeposit; use orml_benchmarking::runtime_benchmarks; -use primitives::{AccountId, Balance, CurrencyId, IncomeSource, TokenSymbol}; +use primitives::{AccountId, Balance, CurrencyId, IncomeSource}; use sp_runtime::{FixedPointNumber, FixedU128}; use sp_std::prelude::*; +const NATIVECOIN: CurrencyId = GetNativeCurrencyId::get(); + fn assert_last_event(generic_event: Event) { System::assert_last_event(generic_event.into()); } @@ -64,32 +66,35 @@ runtime_benchmarks! { force_transfer_to_incentive { let treasury: AccountId = runtime_common::NetworkTreasuryPool::get(); + let incentive: AccountId = runtime_common::CollatorsRewardPool::get(); - // set_income_fee + // set_income_fee: TxFee -> NetworkTreasuryPool let pool = PoolPercent { - pool: runtime_common::NetworkTreasuryPool::get(), + pool: treasury.clone(), rate: FixedU128::saturating_from_rational(1, 1), }; let _ = Fees::set_income_fee(Origin::root(), IncomeSource::TxFee, vec![pool]); - // set_treasury_pool + let treasuries = Fees::income_to_treasuries(IncomeSource::TxFee); + assert_eq!(treasuries.len(), 1); + + // set_treasury_pool: NetworkTreasuryPool -> CollatorsRewardPool let pool = PoolPercent { - pool: runtime_common::CollatorsRewardPool::get(), + pool: incentive, rate: FixedU128::saturating_from_rational(1, 1), }; let threshold: Balance = 100; let pools = vec![pool]; let _ = Fees::set_treasury_pool(Origin::root(), treasury.clone(), threshold, pools.clone()); + let (store_threshod, incentives) = Fees::treasury_to_incentives(treasury.clone()); + assert_eq!(incentives.len(), 1); + assert_eq!(store_threshod, threshold); + + // distribution fee: TxFee let _ = >::on_fee_deposit( - IncomeSource::TxFee, None, CurrencyId::Token(TokenSymbol::ACA), 10000); + IncomeSource::TxFee, None, NATIVECOIN, 1_000_000_000); }: _(RawOrigin::Root, treasury.clone()) - verify { - assert_last_event(module_fees::Event::IncentiveDistribution { - treasury, - amount: 100000010000, - }.into()); - } } #[cfg(test)] From 2f575ef96ab7fdfc531be7085c76f97425b19109 Mon Sep 17 00:00:00 2001 From: zqh Date: Wed, 15 Jun 2022 13:46:30 +0800 Subject: [PATCH 28/49] move HomaTreasuryPalletId to common --- runtime/acala/src/authority.rs | 10 +++++----- runtime/acala/src/lib.rs | 3 --- runtime/common/src/lib.rs | 2 +- runtime/karura/src/authority.rs | 10 +++++----- runtime/karura/src/lib.rs | 3 --- runtime/mandala/src/authority.rs | 10 +++++----- runtime/mandala/src/lib.rs | 3 --- 7 files changed, 16 insertions(+), 25 deletions(-) diff --git a/runtime/acala/src/authority.rs b/runtime/acala/src/authority.rs index 997b84dd69..6aa92f59f5 100644 --- a/runtime/acala/src/authority.rs +++ b/runtime/acala/src/authority.rs @@ -22,8 +22,8 @@ use crate::{ AccountId, AccountIdConversion, AuthoritysOriginId, BadOrigin, BlockNumber, DispatchResult, EnsureRoot, EnsureRootOrHalfFinancialCouncil, EnsureRootOrHalfGeneralCouncil, EnsureRootOrHalfHomaCouncil, EnsureRootOrOneThirdsTechnicalCommittee, EnsureRootOrThreeFourthsGeneralCouncil, - EnsureRootOrTwoThirdsTechnicalCommittee, HomaTreasuryPalletId, HonzonTreasuryPalletId, OneDay, Origin, - OriginCaller, SevenDays, TreasuryPalletId, TreasuryReservePalletId, HOURS, + EnsureRootOrTwoThirdsTechnicalCommittee, HonzonTreasuryPalletId, OneDay, Origin, OriginCaller, SevenDays, + TreasuryPalletId, TreasuryReservePalletId, HOURS, }; pub use frame_support::traits::{schedule::Priority, EnsureOrigin, OriginTrait}; use frame_system::ensure_root; @@ -83,9 +83,9 @@ impl orml_authority::AsOriginId for AuthoritysOriginId { AuthoritysOriginId::HonzonTreasury => Origin::signed(HonzonTreasuryPalletId::get().into_account()) .caller() .clone(), - AuthoritysOriginId::HomaTreasury => Origin::signed(HomaTreasuryPalletId::get().into_account()) - .caller() - .clone(), + AuthoritysOriginId::HomaTreasury => { + Origin::signed(runtime_common::HomaTreasuryPool::get()).caller().clone() + } AuthoritysOriginId::TreasuryReserve => Origin::signed(TreasuryReservePalletId::get().into_account()) .caller() .clone(), diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index 00d652319d..f26f6ce35d 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -156,7 +156,6 @@ parameter_types! { pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub const HomaPalletId: PalletId = PalletId(*b"aca/homa"); pub const HonzonTreasuryPalletId: PalletId = PalletId(*b"aca/hztr"); - pub const HomaTreasuryPalletId: PalletId = PalletId(*b"aca/hmtr"); pub const IncentivesPalletId: PalletId = PalletId(*b"aca/inct"); pub const CollatorPotId: PalletId = PalletId(*b"aca/cpot"); // Treasury reserve @@ -177,7 +176,6 @@ pub fn get_all_module_accounts() -> Vec { CollatorPotId::get().into_account(), DEXPalletId::get().into_account(), HomaPalletId::get().into_account(), - HomaTreasuryPalletId::get().into_account(), HonzonTreasuryPalletId::get().into_account(), IncentivesPalletId::get().into_account(), TreasuryPalletId::get().into_account(), @@ -1438,7 +1436,6 @@ impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { pub DefaultExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10); - pub HomaTreasuryAccount: AccountId = HomaTreasuryPalletId::get().into_account(); pub ActiveSubAccountsIndexList: Vec = vec![ 0, // 15sr8Dvq3AT3Z2Z1y8FnQ4VipekAHhmQnrkgzegUr1tNgbcn ]; diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 8c36322c08..7cf52b3469 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -403,7 +403,7 @@ parameter_types! { // Treasury pools pub NetworkTreasuryPool: AccountId = PalletId(*b"aca/nktp").into_account(); pub HonzonTreasuryPool: AccountId = PalletId(*b"aca/hztp").into_account(); - pub HomaTreasuryPool: AccountId = PalletId(*b"aca/hmtp").into_account(); + pub HomaTreasuryPool: AccountId = PalletId(*b"aca/hmtr").into_account(); // Incentive reward Pools pub HonzonInsuranceRewardPool: AccountId = PalletId(*b"aca/hirp").into_account(); pub HonzonLiquitationRewardPool: AccountId = PalletId(*b"aca/hlrp").into_account(); diff --git a/runtime/karura/src/authority.rs b/runtime/karura/src/authority.rs index 997b84dd69..6aa92f59f5 100644 --- a/runtime/karura/src/authority.rs +++ b/runtime/karura/src/authority.rs @@ -22,8 +22,8 @@ use crate::{ AccountId, AccountIdConversion, AuthoritysOriginId, BadOrigin, BlockNumber, DispatchResult, EnsureRoot, EnsureRootOrHalfFinancialCouncil, EnsureRootOrHalfGeneralCouncil, EnsureRootOrHalfHomaCouncil, EnsureRootOrOneThirdsTechnicalCommittee, EnsureRootOrThreeFourthsGeneralCouncil, - EnsureRootOrTwoThirdsTechnicalCommittee, HomaTreasuryPalletId, HonzonTreasuryPalletId, OneDay, Origin, - OriginCaller, SevenDays, TreasuryPalletId, TreasuryReservePalletId, HOURS, + EnsureRootOrTwoThirdsTechnicalCommittee, HonzonTreasuryPalletId, OneDay, Origin, OriginCaller, SevenDays, + TreasuryPalletId, TreasuryReservePalletId, HOURS, }; pub use frame_support::traits::{schedule::Priority, EnsureOrigin, OriginTrait}; use frame_system::ensure_root; @@ -83,9 +83,9 @@ impl orml_authority::AsOriginId for AuthoritysOriginId { AuthoritysOriginId::HonzonTreasury => Origin::signed(HonzonTreasuryPalletId::get().into_account()) .caller() .clone(), - AuthoritysOriginId::HomaTreasury => Origin::signed(HomaTreasuryPalletId::get().into_account()) - .caller() - .clone(), + AuthoritysOriginId::HomaTreasury => { + Origin::signed(runtime_common::HomaTreasuryPool::get()).caller().clone() + } AuthoritysOriginId::TreasuryReserve => Origin::signed(TreasuryReservePalletId::get().into_account()) .caller() .clone(), diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index d67c9e4497..e0b018a785 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -157,7 +157,6 @@ parameter_types! { pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub const HonzonTreasuryPalletId: PalletId = PalletId(*b"aca/hztr"); pub const HomaPalletId: PalletId = PalletId(*b"aca/homa"); - pub const HomaTreasuryPalletId: PalletId = PalletId(*b"aca/hmtr"); pub const IncentivesPalletId: PalletId = PalletId(*b"aca/inct"); pub const CollatorPotId: PalletId = PalletId(*b"aca/cpot"); pub const HonzonBridgePalletId: PalletId = PalletId(*b"aca/hzbg"); @@ -180,7 +179,6 @@ pub fn get_all_module_accounts() -> Vec { CollatorPotId::get().into_account(), DEXPalletId::get().into_account(), HomaPalletId::get().into_account(), - HomaTreasuryPalletId::get().into_account(), HonzonTreasuryPalletId::get().into_account(), IncentivesPalletId::get().into_account(), TreasuryPalletId::get().into_account(), @@ -1469,7 +1467,6 @@ impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { pub DefaultExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10); - pub HomaTreasuryAccount: AccountId = HomaTreasuryPalletId::get().into_account(); pub ActiveSubAccountsIndexList: Vec = vec![ 0, // HTAeD1dokCVs9MwnC1q9s2a7d2kQ52TAjrxE1y5mj5MFLLA 1, // FDVu3RdH5WsE2yTdXN3QMq6v1XVDK8GKjhq5oFjXe8wZYpL diff --git a/runtime/mandala/src/authority.rs b/runtime/mandala/src/authority.rs index add8743756..e312cd4410 100644 --- a/runtime/mandala/src/authority.rs +++ b/runtime/mandala/src/authority.rs @@ -22,8 +22,8 @@ use crate::{ AccountId, AccountIdConversion, AuthoritysOriginId, BadOrigin, BlockNumber, DispatchResult, EnsureRoot, EnsureRootOrHalfFinancialCouncil, EnsureRootOrHalfGeneralCouncil, EnsureRootOrHalfHomaCouncil, EnsureRootOrOneThirdsTechnicalCommittee, EnsureRootOrThreeFourthsGeneralCouncil, - EnsureRootOrTwoThirdsTechnicalCommittee, HomaTreasuryPalletId, HonzonTreasuryPalletId, OneDay, Origin, - OriginCaller, SevenDays, TreasuryPalletId, TreasuryReservePalletId, ZeroDay, HOURS, + EnsureRootOrTwoThirdsTechnicalCommittee, HonzonTreasuryPalletId, OneDay, Origin, OriginCaller, SevenDays, + TreasuryPalletId, TreasuryReservePalletId, ZeroDay, HOURS, }; pub use frame_support::traits::{schedule::Priority, EnsureOrigin, OriginTrait}; use frame_system::ensure_root; @@ -83,9 +83,9 @@ impl orml_authority::AsOriginId for AuthoritysOriginId { AuthoritysOriginId::HonzonTreasury => Origin::signed(HonzonTreasuryPalletId::get().into_account()) .caller() .clone(), - AuthoritysOriginId::HomaTreasury => Origin::signed(HomaTreasuryPalletId::get().into_account()) - .caller() - .clone(), + AuthoritysOriginId::HomaTreasury => { + Origin::signed(runtime_common::HomaTreasuryPool::get()).caller().clone() + } AuthoritysOriginId::TreasuryReserve => Origin::signed(TreasuryReservePalletId::get().into_account()) .caller() .clone(), diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 69ff1bd02b..369889cc33 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -163,7 +163,6 @@ parameter_types! { pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub const HonzonTreasuryPalletId: PalletId = PalletId(*b"aca/hztr"); pub const HomaPalletId: PalletId = PalletId(*b"aca/homa"); - pub const HomaTreasuryPalletId: PalletId = PalletId(*b"aca/hmtr"); pub const IncentivesPalletId: PalletId = PalletId(*b"aca/inct"); // Treasury reserve pub const TreasuryReservePalletId: PalletId = PalletId(*b"aca/reve"); @@ -188,7 +187,6 @@ pub fn get_all_module_accounts() -> Vec { DEXPalletId::get().into_account(), CDPTreasuryPalletId::get().into_account(), HonzonTreasuryPalletId::get().into_account(), - HomaTreasuryPalletId::get().into_account(), IncentivesPalletId::get().into_account(), TreasuryReservePalletId::get().into_account(), StarportPalletId::get().into_account(), @@ -1323,7 +1321,6 @@ pub fn create_x2_parachain_multilocation(index: u16) -> MultiLocation { } parameter_types! { - pub HomaTreasuryAccount: AccountId = HomaTreasuryPalletId::get().into_account(); pub ActiveSubAccountsIndexList: Vec = vec![ 0, // 15sr8Dvq3AT3Z2Z1y8FnQ4VipekAHhmQnrkgzegUr1tNgbcn ]; From d11281637eb28d90f5d2aaf19e05af438329c12c Mon Sep 17 00:00:00 2001 From: zqh Date: Wed, 15 Jun 2022 17:35:12 +0800 Subject: [PATCH 29/49] Acala XcmFeeToTreasury --- runtime/acala/src/xcm_config.rs | 46 ++++++++++++--------------------- 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/runtime/acala/src/xcm_config.rs b/runtime/acala/src/xcm_config.rs index 22820f35c8..1a1d06699a 100644 --- a/runtime/acala/src/xcm_config.rs +++ b/runtime/acala/src/xcm_config.rs @@ -18,8 +18,8 @@ use super::{ constants::fee::*, AcalaTreasuryAccount, AccountId, AssetIdMapping, AssetIdMaps, Balance, Call, Convert, - Currencies, CurrencyId, Event, ExistentialDeposits, GetNativeCurrencyId, NativeTokenExistentialDeposit, Origin, - ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, UnknownTokens, XcmpQueue, ACA, AUSD, + Currencies, CurrencyId, Event, ExistentialDeposits, Fees, GetNativeCurrencyId, NativeTokenExistentialDeposit, + Origin, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, UnknownTokens, XcmpQueue, ACA, AUSD, }; use codec::{Decode, Encode}; pub use cumulus_primitives_core::ParaId; @@ -30,19 +30,21 @@ pub use frame_support::{ }; use module_asset_registry::{BuyWeightRateOfErc20, BuyWeightRateOfForeignAsset}; use module_transaction_payment::BuyWeightRateOfTransactionFeePool; -use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key, MultiCurrency}; +use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key}; use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use primitives::evm::is_system_contract; -use runtime_common::{native_currency_location, AcalaDropAssets, EnsureRootOrHalfGeneralCouncil, FixedRateOfAsset}; +use runtime_common::{ + native_currency_location, AcalaDropAssets, EnsureRootOrHalfGeneralCouncil, FixedRateOfAsset, XcmFeeToTreasury, +}; use xcm::latest::prelude::*; pub use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, - TakeRevenue, TakeWeightCredit, + TakeWeightCredit, }; use xcm_executor::XcmExecutor; @@ -95,24 +97,6 @@ pub type Barrier = ( AllowSubscriptionsFrom, ); -pub struct ToTreasury; -impl TakeRevenue for ToTreasury { - fn take_revenue(revenue: MultiAsset) { - if let MultiAsset { - id: Concrete(location), - fun: Fungible(amount), - } = revenue - { - if let Some(currency_id) = CurrencyIdConvert::convert(location) { - // Ensure AcalaTreasuryAccount have ed requirement for native asset, but don't need - // ed requirement for cross-chain asset because it's one of whitelist accounts. - // Ignore the result. - let _ = Currencies::deposit(currency_id, &AcalaTreasuryAccount::get(), amount); - } - } - } -} - parameter_types! { // One XCM operation is 200_000_000 weight, cross-chain transfer ~= 2x of transfer. pub const UnitWeightCost: Weight = 200_000_000; @@ -136,13 +120,15 @@ parameter_types! { pub BaseRate: u128 = aca_per_second(); } +type XcmToTreasury = XcmFeeToTreasury; + pub type Trader = ( - FixedRateOfAsset>, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfAsset>, - FixedRateOfAsset>, + FixedRateOfAsset>, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfAsset>, + FixedRateOfAsset>, ); pub struct XcmConfig; @@ -162,7 +148,7 @@ impl xcm_executor::Config for XcmConfig { type ResponseHandler = PolkadotXcm; type AssetTrap = AcalaDropAssets< PolkadotXcm, - ToTreasury, + XcmToTreasury, CurrencyIdConvert, GetNativeCurrencyId, NativeTokenExistentialDeposit, From 74e59091b53540eafec2c36ddb45924d31926bc3 Mon Sep 17 00:00:00 2001 From: zqh Date: Thu, 16 Jun 2022 09:50:03 +0800 Subject: [PATCH 30/49] remove AccountId from XcmFeeToTreasury --- modules/fees/src/lib.rs | 11 +-------- modules/fees/src/tests.rs | 31 ++---------------------- modules/homa/src/lib.rs | 1 - modules/support/src/lib.rs | 7 +----- runtime/acala/src/xcm_config.rs | 2 +- runtime/common/src/xcm_impl.rs | 7 +++--- runtime/integration-tests/src/setup.rs | 11 ++++++--- runtime/karura/src/xcm_config.rs | 2 +- runtime/mandala/src/benchmarking/fees.rs | 2 +- runtime/mandala/src/xcm_config.rs | 2 +- 10 files changed, 18 insertions(+), 58 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 07749028b9..d453716a43 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -393,16 +393,7 @@ impl OnFeeDeposit fo /// - account_id: If given account, then the whole fee amount directly deposit to it. /// - currency_id: currency type. /// - amount: fee amount. - fn on_fee_deposit( - income: IncomeSource, - account_id: Option<&T::AccountId>, - currency_id: CurrencyId, - amount: Balance, - ) -> DispatchResult { - if let Some(account_id) = account_id { - return T::Currencies::deposit(currency_id, account_id, amount); - } - + fn on_fee_deposit(income: IncomeSource, currency_id: CurrencyId, amount: Balance) -> DispatchResult { // use `IncomeSource` to distribution fee to different treasury pool based on percentage. let pool_rates: BoundedVec, MaxPoolSize> = IncomeToTreasuries::::get(income); Pallet::::distribution_fees(pool_rates, currency_id, amount) diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 4e0ce5f1ba..6833924abb 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -217,7 +217,7 @@ fn on_fee_deposit_works() { .execute_with(|| { // Native token tests // FeeToTreasuryPool based on pre-configured treasury pool percentage. - assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, None, ACA, 10000)); + assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, ACA, 10000)); assert_eq!(Currencies::free_balance(ACA, &NetworkTreasuryPool::get()), 8000); assert_eq!(Currencies::free_balance(ACA, &CollatorsRewardPool::get()), 2000); @@ -238,22 +238,9 @@ fn on_fee_deposit_works() { vec![ACA] ); - // FeeToTreasuryPool direct to given account. - assert_ok!(Pallet::::on_fee_deposit( - IncomeSource::TxFee, - Some(&TreasuryAccount::get()), - ACA, - 10000 - )); - assert_eq!(Currencies::free_balance(ACA, &TreasuryAccount::get()), 10000); - System::assert_has_event(Event::Balances(pallet_balances::Event::Deposit { - who: TreasuryAccount::get(), - amount: 10000, - })); - // Non native token tests // FeeToTreasuryPool based on pre-configured treasury pool percentage. - assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, None, DOT, 10000)); + assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, DOT, 10000)); assert_eq!(Currencies::free_balance(DOT, &NetworkTreasuryPool::get()), 8000); assert_eq!(Currencies::free_balance(DOT, &CollatorsRewardPool::get()), 2000); @@ -275,20 +262,6 @@ fn on_fee_deposit_works() { crate::TreasuryTokens::::get(&CollatorsRewardPool::get()).to_vec(), vec![ACA, DOT] ); - - // FeeToTreasuryPool direct to given account. - assert_ok!(Pallet::::on_fee_deposit( - IncomeSource::TxFee, - Some(&TreasuryAccount::get()), - DOT, - 10000 - )); - assert_eq!(Currencies::free_balance(DOT, &TreasuryAccount::get()), 10000); - System::assert_has_event(Event::Tokens(orml_tokens::Event::Deposited { - currency_id: DOT, - who: TreasuryAccount::get(), - amount: 10000, - })); }); } diff --git a/modules/homa/src/lib.rs b/modules/homa/src/lib.rs index c79a811b97..3ccd670588 100644 --- a/modules/homa/src/lib.rs +++ b/modules/homa/src/lib.rs @@ -902,7 +902,6 @@ pub mod module { // Staking rewards goes to T::OnFeeDeposit T::OnFeeDeposit::on_fee_deposit( IncomeSource::HomaStakingRewardFee, - None, liquid_currency_id, inflate_liquid_amount, )?; diff --git a/modules/support/src/lib.rs b/modules/support/src/lib.rs index 114b140f71..bccc6d1e25 100644 --- a/modules/support/src/lib.rs +++ b/modules/support/src/lib.rs @@ -106,12 +106,7 @@ pub trait TransactionPayment { } pub trait OnFeeDeposit { - fn on_fee_deposit( - income: IncomeSource, - account_id: Option<&AccountId>, - currency_id: CurrencyId, - amount: Balance, - ) -> DispatchResult; + fn on_fee_deposit(income: IncomeSource, currency_id: CurrencyId, amount: Balance) -> DispatchResult; } /// Used to interface with the Compound's Cash module diff --git a/runtime/acala/src/xcm_config.rs b/runtime/acala/src/xcm_config.rs index 1a1d06699a..314162bd38 100644 --- a/runtime/acala/src/xcm_config.rs +++ b/runtime/acala/src/xcm_config.rs @@ -120,7 +120,7 @@ parameter_types! { pub BaseRate: u128 = aca_per_second(); } -type XcmToTreasury = XcmFeeToTreasury; +type XcmToTreasury = XcmFeeToTreasury; pub type Trader = ( FixedRateOfAsset>, diff --git a/runtime/common/src/xcm_impl.rs b/runtime/common/src/xcm_impl.rs index 91d8b395a0..b9a819a09e 100644 --- a/runtime/common/src/xcm_impl.rs +++ b/runtime/common/src/xcm_impl.rs @@ -106,10 +106,9 @@ where } } -pub struct XcmFeeToTreasury(PhantomData<(T, C, F)>); -impl TakeRevenue for XcmFeeToTreasury +pub struct XcmFeeToTreasury(PhantomData<(C, F)>); +impl TakeRevenue for XcmFeeToTreasury where - T: Get, C: Convert>, F: OnFeeDeposit, { @@ -123,7 +122,7 @@ where // Ensure given treasury account have ed requirement for native asset, but don't need // ed requirement for cross-chain asset because it's one of whitelist accounts. // Ignore the result. - let _ = F::on_fee_deposit(IncomeSource::XcmFee, Some(&T::get()), currency_id, amount); + let _ = F::on_fee_deposit(IncomeSource::XcmFee, currency_id, amount); } } } diff --git a/runtime/integration-tests/src/setup.rs b/runtime/integration-tests/src/setup.rs index 5091a0789b..c56cdaa638 100644 --- a/runtime/integration-tests/src/setup.rs +++ b/runtime/integration-tests/src/setup.rs @@ -368,10 +368,13 @@ impl ExtBuilder { .unwrap(); module_fees::GenesisConfig:: { - incomes: vec![( - IncomeSource::TxFee, - vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], - )], + incomes: vec![ + ( + IncomeSource::TxFee, + vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + ), + (IncomeSource::XcmFee, vec![(TreasuryAccount::get(), 100)]), + ], treasuries: vec![], } .assimilate_storage(&mut t) diff --git a/runtime/karura/src/xcm_config.rs b/runtime/karura/src/xcm_config.rs index d20492d570..66b0e65bbc 100644 --- a/runtime/karura/src/xcm_config.rs +++ b/runtime/karura/src/xcm_config.rs @@ -171,7 +171,7 @@ parameter_types! { pub BaseRate: u128 = kar_per_second(); } -pub type XcmToTreasury = XcmFeeToTreasury; +pub type XcmToTreasury = XcmFeeToTreasury; pub type Trader = ( FixedRateOfAsset>, diff --git a/runtime/mandala/src/benchmarking/fees.rs b/runtime/mandala/src/benchmarking/fees.rs index 83730403f2..b98491dd83 100644 --- a/runtime/mandala/src/benchmarking/fees.rs +++ b/runtime/mandala/src/benchmarking/fees.rs @@ -93,7 +93,7 @@ runtime_benchmarks! { // distribution fee: TxFee let _ = >::on_fee_deposit( - IncomeSource::TxFee, None, NATIVECOIN, 1_000_000_000); + IncomeSource::TxFee, NATIVECOIN, 1_000_000_000); }: _(RawOrigin::Root, treasury.clone()) } diff --git a/runtime/mandala/src/xcm_config.rs b/runtime/mandala/src/xcm_config.rs index 87286c0f5b..97df5989c8 100644 --- a/runtime/mandala/src/xcm_config.rs +++ b/runtime/mandala/src/xcm_config.rs @@ -112,7 +112,7 @@ parameter_types! { pub BaseRate: u128 = aca_per_second(); } -type XcmToTreasury = XcmFeeToTreasury; +type XcmToTreasury = XcmFeeToTreasury; pub type Trader = ( FixedRateOfAsset>, From f6099400c553852a2d48bd14c688659ee84e373e Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Thu, 16 Jun 2022 17:13:49 +1200 Subject: [PATCH 31/49] Changed the interest accumulation so the generated stable currencies goes to OnFeeDeposit instead of the CDPtreasury Updated mocks and tests accordingly --- Cargo.lock | 2 + modules/cdp-engine/Cargo.toml | 2 + modules/cdp-engine/src/lib.rs | 18 +++-- modules/cdp-engine/src/mock.rs | 35 +++++++--- modules/cdp-engine/src/tests.rs | 90 +++++++++++++++++++++++++ modules/fees/src/mock.rs | 12 ++-- modules/honzon/Cargo.toml | 2 + modules/honzon/src/mock.rs | 34 +++++++--- runtime/acala/src/lib.rs | 1 + runtime/integration-tests/src/honzon.rs | 15 +++++ runtime/integration-tests/src/setup.rs | 19 +++--- runtime/karura/src/lib.rs | 1 + runtime/mandala/src/lib.rs | 1 + 13 files changed, 192 insertions(+), 40 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a06e779936..a9cde50ca1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5900,6 +5900,7 @@ dependencies = [ "frame-system", "module-cdp-treasury", "module-dex", + "module-fees", "module-loans", "module-support", "nutsfinance-stable-asset", @@ -6319,6 +6320,7 @@ dependencies = [ "frame-system", "module-cdp-engine", "module-cdp-treasury", + "module-fees", "module-loans", "module-support", "orml-currencies", diff --git a/modules/cdp-engine/Cargo.toml b/modules/cdp-engine/Cargo.toml index 9d5a390dc4..814061ea7c 100644 --- a/modules/cdp-engine/Cargo.toml +++ b/modules/cdp-engine/Cargo.toml @@ -18,6 +18,7 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkad sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.19", default-features = false } support = { package = "module-support", path = "../support", default-features = false } loans = { package = "module-loans", path = "../loans", default-features = false } +module-fees = { path = "../fees", default-features = false } primitives = { package = "acala-primitives", path = "../../primitives", default-features = false } rand_chacha = { version = "0.2", default-features = false } nutsfinance-stable-asset = { version = "0.1.0", default-features = false, path = "../../ecosystem-modules/stable-asset/lib/stable-asset", package = "nutsfinance-stable-asset" } @@ -46,6 +47,7 @@ std = [ "sp-std/std", "support/std", "loans/std", + "module-fees/std", "primitives/std", "orml-utilities/std", ] diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 6602afb2d4..273962c3bf 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -37,7 +37,7 @@ use frame_system::{ use loans::Position; use orml_traits::{Change, GetByKey, MultiCurrency}; use orml_utilities::OffchainErr; -use primitives::{Amount, Balance, CurrencyId}; +use primitives::{Amount, Balance, CurrencyId, IncomeSource}; use rand_chacha::{ rand_core::{RngCore, SeedableRng}, ChaChaRng, @@ -57,8 +57,8 @@ use sp_runtime::{ }; use sp_std::prelude::*; use support::{ - CDPTreasury, CDPTreasuryExtended, DEXManager, EmergencyShutdown, ExchangeRate, Price, PriceProvider, Rate, Ratio, - RiskManager, Swap, SwapLimit, + CDPTreasury, CDPTreasuryExtended, DEXManager, EmergencyShutdown, ExchangeRate, OnFeeDeposit, Price, PriceProvider, + Rate, Ratio, RiskManager, Swap, SwapLimit, }; mod mock; @@ -187,6 +187,9 @@ pub mod module { /// Swap type Swap: Swap; + /// Where the fees are go to. + type OnFeeDeposit: OnFeeDeposit; + /// Weight information for the extrinsics in this module. type WeightInfo: WeightInfo; } @@ -554,8 +557,13 @@ impl Pallet { let debit_exchange_rate_increment = debit_exchange_rate.saturating_mul(rate_to_accumulate); let issued_stable_coin_balance = debit_exchange_rate_increment.saturating_mul_int(total_debits); - // issue stablecoin to surplus pool - let res = ::CDPTreasury::on_system_surplus(issued_stable_coin_balance); + // Staking rewards goes to T::OnFeeDeposit + let res = T::OnFeeDeposit::on_fee_deposit( + IncomeSource::HonzonStabilityFee, + None, + T::GetStableCurrencyId::get(), + issued_stable_coin_balance, + ); match res { Ok(_) => { // update exchange rate when issue success diff --git a/modules/cdp-engine/src/mock.rs b/modules/cdp-engine/src/mock.rs index b3d4254e7d..04f79b0424 100644 --- a/modules/cdp-engine/src/mock.rs +++ b/modules/cdp-engine/src/mock.rs @@ -26,7 +26,7 @@ use frame_support::{ traits::{ConstU128, ConstU32, ConstU64, Everything, Nothing}, PalletId, }; -use frame_system::EnsureSignedBy; +use frame_system::{EnsureRoot, EnsureSignedBy}; use orml_traits::parameter_type_with_key; use primitives::{DexShare, Moment, TokenSymbol, TradingPair}; use sp_core::H256; @@ -120,6 +120,7 @@ pub type AdaptedBasicCurrency = orml_currencies::BasicCurrencyAdapter; + type Currency = PalletBalances; + type Currencies = Currencies; + type NativeCurrencyId = GetNativeCurrencyId; + type AllocationPeriod = ConstU64<10>; + type DEX = (); + type DexSwapJointList = AlternativeSwapPathJointList; + type WeightInfo = (); +} + impl Config for Runtime { type Event = Event; type PriceSource = MockPriceSource; @@ -321,6 +334,7 @@ impl Config for Runtime { type Currency = Currencies; type DEX = DEXModule; type Swap = SpecificJointsSwap; + type OnFeeDeposit = Fees; type WeightInfo = (); } @@ -333,15 +347,16 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - CDPEngineModule: cdp_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned}, - CDPTreasuryModule: cdp_treasury::{Pallet, Storage, Call, Config, Event}, - Currencies: orml_currencies::{Pallet, Call}, - Tokens: orml_tokens::{Pallet, Storage, Event, Config}, - LoansModule: loans::{Pallet, Storage, Call, Event}, - PalletBalances: pallet_balances::{Pallet, Call, Storage, Event}, - DEXModule: dex::{Pallet, Storage, Call, Event, Config}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, + System: frame_system, + CDPEngineModule: cdp_engine, + CDPTreasuryModule: cdp_treasury, + Currencies: orml_currencies, + Tokens: orml_tokens, + LoansModule: loans, + PalletBalances: pallet_balances, + DEXModule: dex, + Timestamp: pallet_timestamp, + Fees: module_fees, } ); diff --git a/modules/cdp-engine/src/tests.rs b/modules/cdp-engine/src/tests.rs index 280b5fd02b..0c2adcac13 100644 --- a/modules/cdp-engine/src/tests.rs +++ b/modules/cdp-engine/src/tests.rs @@ -23,6 +23,7 @@ use super::*; use frame_support::{assert_noop, assert_ok}; use mock::{Call as MockCall, Event, *}; +use module_fees::PoolPercent; use orml_traits::MultiCurrency; use sp_core::offchain::{testing, OffchainDbExt, OffchainWorkerExt, TransactionPoolExt}; use sp_io::offchain; @@ -58,6 +59,17 @@ fn setup_default_collateral(currency_id: CurrencyId) { )); } +fn setup_fees_distribution() { + assert_ok!(Fees::set_income_fee( + Origin::root(), + IncomeSource::HonzonStabilityFee, + vec![PoolPercent { + pool: TreasuryAccount::get(), + rate: Rate::one(), + }], + )); +} + #[test] fn check_cdp_status_work() { ExtBuilder::default().build().execute_with(|| { @@ -1347,6 +1359,8 @@ fn compound_interest_rate_work() { #[test] fn accumulate_interest_work() { ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); + assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), BTC, @@ -1862,3 +1876,79 @@ fn minimal_collateral_works() { assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 0, 0)); }); } + +#[test] +fn accumulated_interest_goes_to_on_fee_deposit() { + ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); + + assert_ok!(CDPEngineModule::set_collateral_params( + Origin::signed(1), + BTC, + Change::NewValue(Some(Rate::saturating_from_rational(1, 100))), + Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), + Change::NewValue(Some(Rate::zero())), + Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), + Change::NewValue(10000), + )); + assert_ok!(CDPEngineModule::set_collateral_params( + Origin::signed(1), + DOT, + Change::NewValue(Some(Rate::one())), + Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), + Change::NewValue(Some(Rate::zero())), + Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), + Change::NewValue(10000), + )); + assert_eq!( + CDPEngineModule::get_interest_rate_per_sec(BTC), + Ok(Rate::saturating_from_rational(1, 100)) + ); + assert_eq!(CDPEngineModule::get_interest_rate_per_sec(DOT), Ok(Rate::one())); + + // Treasury starts off empty. + assert_eq!(Currencies::free_balance(BTC, &TreasuryAccount::get()), 0); + assert_eq!(Currencies::free_balance(DOT, &TreasuryAccount::get()), 0); + + CDPEngineModule::accumulate_interest(1, 0); + + // No debit generates no interest. + assert_eq!(Currencies::free_balance(BTC, &TreasuryAccount::get()), 0); + assert_eq!(Currencies::free_balance(DOT, &TreasuryAccount::get()), 0); + + assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 1000, 1000)); + assert_ok!(CDPEngineModule::adjust_position(&ALICE, DOT, 1000, 1000)); + + CDPEngineModule::accumulate_interest(2, 1); + assert_eq!(CDPEngineModule::last_accumulation_secs(), 2); + + // Generated interest = debit * debit_exchange_rate * interest_rate + // = 1000 * 0.1 * 0.01 + 1000 * 0.1 * 1 = 101 + assert_eq!(Currencies::free_balance(AUSD, &TreasuryAccount::get()), 101); + + assert_eq!( + CDPEngineModule::get_debit_exchange_rate(BTC), + ExchangeRate::saturating_from_rational(101, 1000) + ); + assert_eq!( + CDPEngineModule::get_debit_exchange_rate(DOT), + ExchangeRate::saturating_from_rational(2, 10) + ); + + CDPEngineModule::accumulate_interest(3, 2); + assert_eq!(CDPEngineModule::last_accumulation_secs(), 3); + + // Generated interest = debit * debit_exchange_rate * interest_rate + // = 1000 * 0.101 * 0.01 + 1000 * 0.2 * 1 = 201 + assert_eq!(Currencies::free_balance(AUSD, &TreasuryAccount::get()), 302); + + assert_eq!( + CDPEngineModule::get_debit_exchange_rate(BTC), + ExchangeRate::saturating_from_rational(10201, 100000) + ); + assert_eq!( + CDPEngineModule::get_debit_exchange_rate(DOT), + ExchangeRate::saturating_from_rational(4, 10) + ); + }); +} diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index 8a7da93b01..ad32f4d9e7 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -185,12 +185,12 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Tokens: orml_tokens::{Pallet, Storage, Event, Config}, - Currencies: module_currencies::{Pallet, Call, Event}, - Fees: fees::{Pallet, Storage, Call, Event, Config}, - DEX: module_dex::{Pallet, Storage, Call, Event, Config}, + System: frame_system, + Balances: pallet_balances, + Tokens: orml_tokens, + Currencies: module_currencies, + Fees: fees, + DEX: module_dex, } ); diff --git a/modules/honzon/Cargo.toml b/modules/honzon/Cargo.toml index fc91d7e9cc..f9cf8c72c0 100644 --- a/modules/honzon/Cargo.toml +++ b/modules/honzon/Cargo.toml @@ -15,6 +15,7 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v cdp-engine = { package = "module-cdp-engine", path = "../cdp-engine", default-features = false } loans = { package = "module-loans", path = "../loans", default-features = false } support = { package = "module-support", path = "../support", default-features = false } +module-fees = {path = "../fees", default-features = false } primitives = { package = "acala-primitives", path = "../../primitives", default-features = false } [dev-dependencies] @@ -39,6 +40,7 @@ std = [ "sp-std/std", "loans/std", "cdp-engine/std", + "module-fees/std", "support/std", "primitives/std", ] diff --git a/modules/honzon/src/mock.rs b/modules/honzon/src/mock.rs index f4730f8ad7..75e3bc2e86 100644 --- a/modules/honzon/src/mock.rs +++ b/modules/honzon/src/mock.rs @@ -27,7 +27,7 @@ use frame_support::{ traits::{ConstU128, ConstU32, ConstU64, Everything, Nothing}, PalletId, }; -use frame_system::{offchain::SendTransactionTypes, EnsureSignedBy}; +use frame_system::{offchain::SendTransactionTypes, EnsureRoot, EnsureSignedBy}; use orml_traits::parameter_type_with_key; use primitives::{Balance, Moment, ReserveIdentifier, TokenSymbol}; use sp_core::H256; @@ -260,6 +260,19 @@ impl cdp_engine::Config for Runtime { type Currency = Currencies; type DEX = (); type Swap = SpecificJointsSwap<(), AlternativeSwapPathJointList>; + type OnFeeDeposit = Fees; + type WeightInfo = (); +} + +impl module_fees::Config for Runtime { + type Event = Event; + type UpdateOrigin = EnsureRoot; + type Currency = PalletBalances; + type Currencies = Currencies; + type NativeCurrencyId = GetNativeCurrencyId; + type AllocationPeriod = ConstU64<10>; + type DEX = (); + type DexSwapJointList = AlternativeSwapPathJointList; type WeightInfo = (); } @@ -280,15 +293,16 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - HonzonModule: honzon::{Pallet, Storage, Call, Event}, - Tokens: orml_tokens::{Pallet, Storage, Event, Config}, - PalletBalances: pallet_balances::{Pallet, Call, Storage, Event}, - Currencies: orml_currencies::{Pallet, Call}, - LoansModule: loans::{Pallet, Storage, Call, Event}, - CDPTreasuryModule: cdp_treasury::{Pallet, Storage, Call, Event}, - CDPEngineModule: cdp_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, + System: frame_system, + HonzonModule: honzon, + Tokens: orml_tokens, + PalletBalances: pallet_balances, + Currencies: orml_currencies, + LoansModule: loans, + CDPTreasuryModule: cdp_treasury, + CDPEngineModule: cdp_engine, + Timestamp: pallet_timestamp, + Fees: module_fees, } ); diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index 2a6085ac17..ac6f4f9682 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -1051,6 +1051,7 @@ impl module_cdp_engine::Config for Runtime { type Currency = Currencies; type DEX = Dex; type Swap = AcalaSwap; + type OnFeeDeposit = Fees; type WeightInfo = weights::module_cdp_engine::WeightInfo; } diff --git a/runtime/integration-tests/src/honzon.rs b/runtime/integration-tests/src/honzon.rs index 581b7340ca..71942319bc 100644 --- a/runtime/integration-tests/src/honzon.rs +++ b/runtime/integration-tests/src/honzon.rs @@ -17,6 +17,9 @@ // along with this program. If not, see . use crate::setup::*; +use module_fees::PoolPercent; +use primitives::IncomeSource; +use sp_runtime::traits::One; fn setup_default_collateral(currency_id: CurrencyId) { assert_ok!(CdpEngine::set_collateral_params( @@ -30,6 +33,17 @@ fn setup_default_collateral(currency_id: CurrencyId) { )); } +fn setup_fees_distribution() { + assert_ok!(Fees::set_income_fee( + Origin::root(), + IncomeSource::HonzonStabilityFee, + vec![PoolPercent { + pool: CdpTreasury::account_id(), + rate: Rate::one(), + }], + )); +} + #[test] fn emergency_shutdown_and_cdp_treasury() { ExtBuilder::default() @@ -476,6 +490,7 @@ fn cdp_treasury_handles_honzon_surplus_correctly() { ]) .build() .execute_with(|| { + setup_fees_distribution(); System::set_block_number(1); set_oracle_price(vec![(RELAY_CHAIN_CURRENCY, Price::saturating_from_rational(100, 1))]); assert_ok!(CdpEngine::set_collateral_params( diff --git a/runtime/integration-tests/src/setup.rs b/runtime/integration-tests/src/setup.rs index 9eb47b9b1c..7c0d16c2d2 100644 --- a/runtime/integration-tests/src/setup.rs +++ b/runtime/integration-tests/src/setup.rs @@ -51,7 +51,7 @@ mod mandala_imports { AuctionManager, Authority, AuthoritysOriginId, Authorship, Balance, Balances, BlockNumber, Call, CdpEngine, CdpTreasury, CollatorSelection, CreateClassDeposit, CreateTokenDeposit, Currencies, CurrencyId, DataDepositPerByte, DefaultExchangeRate, Dex, EmergencyShutdown, EnabledTradingPairs, Event, EvmAccounts, - ExistentialDeposits, FinancialCouncil, Get, GetNativeCurrencyId, Homa, Honzon, IdleScheduler, Loans, + ExistentialDeposits, Fees, FinancialCouncil, Get, GetNativeCurrencyId, Homa, Honzon, IdleScheduler, Loans, MaxTipsOfPriority, MinRewardDistributeAmount, MinimumDebitValue, MultiLocation, NativeTokenExistentialDeposit, NetworkId, NftPalletId, OneDay, Origin, OriginCaller, PalletCurrency, ParachainInfo, ParachainSystem, Proxy, ProxyType, Ratio, Runtime, Scheduler, Session, SessionKeys, SessionManager, SevenDays, StableAsset, @@ -90,8 +90,8 @@ mod karura_imports { constants::parachains, create_x2_parachain_multilocation, get_all_module_accounts, AcalaOracle, AccountId, AssetRegistry, AuctionManager, Authority, AuthoritysOriginId, Balance, Balances, BlockNumber, Call, CdpEngine, CdpTreasury, CreateClassDeposit, CreateTokenDeposit, Currencies, CurrencyId, DataDepositPerByte, - DefaultExchangeRate, Dex, EmergencyShutdown, Event, EvmAccounts, ExistentialDeposits, FinancialCouncil, Get, - GetNativeCurrencyId, Homa, Honzon, IdleScheduler, KaruraFoundationAccounts, Loans, MaxTipsOfPriority, + DefaultExchangeRate, Dex, EmergencyShutdown, Event, EvmAccounts, ExistentialDeposits, Fees, FinancialCouncil, + Get, GetNativeCurrencyId, Homa, Honzon, IdleScheduler, KaruraFoundationAccounts, Loans, MaxTipsOfPriority, MinimumDebitValue, MultiLocation, NativeTokenExistentialDeposit, NetworkId, NftPalletId, OneDay, Origin, OriginCaller, ParachainAccount, ParachainInfo, ParachainSystem, PolkadotXcm, Proxy, ProxyType, Ratio, Runtime, Scheduler, Session, SessionManager, SevenDays, System, Timestamp, TipPerWeightStep, TokenSymbol, Tokens, @@ -141,12 +141,13 @@ mod acala_imports { create_x2_parachain_multilocation, get_all_module_accounts, AcalaFoundationAccounts, AcalaOracle, AccountId, AssetRegistry, AuctionManager, Authority, AuthoritysOriginId, Balance, Balances, BlockNumber, Call, CdpEngine, CdpTreasury, CreateClassDeposit, CreateTokenDeposit, Currencies, CurrencyId, DataDepositPerByte, - DefaultExchangeRate, Dex, EmergencyShutdown, Event, EvmAccounts, ExistentialDeposits, FinancialCouncil, Get, - GetNativeCurrencyId, Homa, Honzon, IdleScheduler, Loans, MaxTipsOfPriority, MinimumDebitValue, MultiLocation, - NativeTokenExistentialDeposit, NetworkId, NftPalletId, OneDay, Origin, OriginCaller, ParachainAccount, - ParachainInfo, ParachainSystem, PolkadotXcm, Proxy, ProxyType, Ratio, Runtime, Scheduler, Session, - SessionManager, SevenDays, System, Timestamp, TipPerWeightStep, TokenSymbol, Tokens, TransactionPayment, - TransactionPaymentPalletId, TreasuryPalletId, Utility, Vesting, XTokens, XcmInterface, EVM, LCDOT, NFT, + DefaultExchangeRate, Dex, EmergencyShutdown, Event, EvmAccounts, ExistentialDeposits, Fees, FinancialCouncil, + Get, GetNativeCurrencyId, Homa, Honzon, IdleScheduler, Loans, MaxTipsOfPriority, MinimumDebitValue, + MultiLocation, NativeTokenExistentialDeposit, NetworkId, NftPalletId, OneDay, Origin, OriginCaller, + ParachainAccount, ParachainInfo, ParachainSystem, PolkadotXcm, Proxy, ProxyType, Ratio, Runtime, Scheduler, + Session, SessionManager, SevenDays, System, Timestamp, TipPerWeightStep, TokenSymbol, Tokens, + TransactionPayment, TransactionPaymentPalletId, TreasuryPalletId, Utility, Vesting, XTokens, XcmInterface, EVM, + LCDOT, NFT, }; pub use frame_support::parameter_types; pub use primitives::TradingPair; diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 622a30092f..c623209c30 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1077,6 +1077,7 @@ impl module_cdp_engine::Config for Runtime { type Currency = Currencies; type DEX = Dex; type Swap = AcalaSwap; + type OnFeeDeposit = Fees; type WeightInfo = weights::module_cdp_engine::WeightInfo; } diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 9a78391aa4..bcb59741e0 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1110,6 +1110,7 @@ impl module_cdp_engine::Config for Runtime { type Currency = Currencies; type DEX = Dex; type Swap = AcalaSwap; + type OnFeeDeposit = Fees; type WeightInfo = weights::module_cdp_engine::WeightInfo; } From cec2f7494c7461f3808df500e8dd632c3467d8cf Mon Sep 17 00:00:00 2001 From: zqh Date: Thu, 16 Jun 2022 14:02:37 +0800 Subject: [PATCH 32/49] xcm fee go to NetworkTreasuryPool instead TreasuryAccount --- runtime/integration-tests/src/authority.rs | 2 +- .../integration-tests/src/relaychain/erc20.rs | 13 +++---- .../relaychain/kusama_cross_chain_transfer.rs | 34 ++++++++++--------- .../src/relaychain/kusama_test_net.rs | 2 ++ runtime/integration-tests/src/setup.rs | 13 +++---- runtime/integration-tests/src/treasury.rs | 3 +- runtime/integration-tests/src/vesting.rs | 2 +- 7 files changed, 38 insertions(+), 31 deletions(-) diff --git a/runtime/integration-tests/src/authority.rs b/runtime/integration-tests/src/authority.rs index b82147728d..351c98e453 100644 --- a/runtime/integration-tests/src/authority.rs +++ b/runtime/integration-tests/src/authority.rs @@ -115,7 +115,7 @@ fn test_authority_module() { run_to_block(one_day_later); assert_eq!( - Currencies::free_balance(USD_CURRENCY, &TreasuryPalletId::get().into_account_truncating()), + Currencies::free_balance(USD_CURRENCY, &TreasuryAccount::get()), 500 * dollar(USD_CURRENCY) ); assert_eq!( diff --git a/runtime/integration-tests/src/relaychain/erc20.rs b/runtime/integration-tests/src/relaychain/erc20.rs index cbc773d2cb..921e4e8154 100644 --- a/runtime/integration-tests/src/relaychain/erc20.rs +++ b/runtime/integration-tests/src/relaychain/erc20.rs @@ -22,11 +22,12 @@ use crate::relaychain::kusama_test_net::*; use crate::setup::*; use frame_support::assert_ok; -use karura_runtime::{AssetRegistry, Erc20HoldingAccount, KaruraTreasuryAccount}; +use karura_runtime::{AssetRegistry, Erc20HoldingAccount}; use module_evm_accounts::EvmAddressMapping; use module_support::EVM as EVMTrait; use orml_traits::MultiCurrency; use primitives::evm::EvmAddress; +use runtime_common::NetworkTreasuryPool; use sp_core::{H256, U256}; use std::str::FromStr; use xcm_emulator::TestExt; @@ -140,7 +141,7 @@ fn erc20_transfer_between_sibling() { // charge storage. assert_ok!(Currencies::deposit( NATIVE_CURRENCY, - &KaruraTreasuryAccount::get(), + &NetworkTreasuryPool::get(), initial_native_amount )); @@ -194,7 +195,7 @@ fn erc20_transfer_between_sibling() { // initial_native_amount + ed assert_eq!( 1_100_000_000_000, - Currencies::free_balance(NATIVE_CURRENCY, &KaruraTreasuryAccount::get()) + Currencies::free_balance(NATIVE_CURRENCY, &NetworkTreasuryPool::get()) ); System::reset_events(); @@ -247,7 +248,7 @@ fn erc20_transfer_between_sibling() { ); assert_eq!( 9_324_000_000, - Currencies::free_balance(CurrencyId::Erc20(erc20_address_0()), &KaruraTreasuryAccount::get()) + Currencies::free_balance(CurrencyId::Erc20(erc20_address_0()), &NetworkTreasuryPool::get()) ); assert_eq!( 0, @@ -266,7 +267,7 @@ fn erc20_transfer_between_sibling() { // deposit reserve and unreserve storage fee, so the native token not changed. assert_eq!( 1_100_000_000_000, - Currencies::free_balance(NATIVE_CURRENCY, &KaruraTreasuryAccount::get()) + Currencies::free_balance(NATIVE_CURRENCY, &NetworkTreasuryPool::get()) ); // withdraw operation transfer from sibling parachain account to erc20 holding account @@ -284,7 +285,7 @@ fn erc20_transfer_between_sibling() { // TakeRevenue deposit from erc20 holding account to treasury account System::assert_has_event(Event::Currencies(module_currencies::Event::Deposited { currency_id: CurrencyId::Erc20(erc20_address_0()), - who: KaruraTreasuryAccount::get(), + who: NetworkTreasuryPool::get(), amount: 9_324_000_000, })); }); diff --git a/runtime/integration-tests/src/relaychain/kusama_cross_chain_transfer.rs b/runtime/integration-tests/src/relaychain/kusama_cross_chain_transfer.rs index f2454d0dd0..ce1ac31da8 100644 --- a/runtime/integration-tests/src/relaychain/kusama_cross_chain_transfer.rs +++ b/runtime/integration-tests/src/relaychain/kusama_cross_chain_transfer.rs @@ -22,15 +22,17 @@ use crate::relaychain::kusama_test_net::*; use crate::setup::*; use frame_support::assert_ok; -use sp_runtime::traits::AccountIdConversion; -use xcm_builder::ParentIsPreset; - -use karura_runtime::parachains::bifrost::{BNC_KEY, ID as BIFROST_ID}; -use karura_runtime::{AssetRegistry, KaruraTreasuryAccount}; +use karura_runtime::{ + parachains::bifrost::{BNC_KEY, ID as BIFROST_ID}, + AssetRegistry, +}; use module_relaychain::RelayChainCallBuilder; use module_support::CallBuilder; use orml_traits::MultiCurrency; use primitives::currency::{AssetMetadata, BNC}; +use runtime_common::NetworkTreasuryPool; +use sp_runtime::traits::AccountIdConversion; +use xcm_builder::ParentIsPreset; use xcm_emulator::TestExt; use xcm_executor::traits::Convert; @@ -236,8 +238,8 @@ fn transfer_from_relay_chain_deposit_to_treasury_if_below_ed() { Karura::execute_with(|| { assert_eq!(Tokens::free_balance(KSM, &AccountId::from(BOB)), 0); assert_eq!( - Tokens::free_balance(KSM, &karura_runtime::KaruraTreasuryAccount::get()), - 1_000_186_480_111 + Tokens::free_balance(KSM, &NetworkTreasuryPool::get()), + 1_000_186_480_000 ); }); } @@ -689,7 +691,7 @@ fn trap_assets_larger_than_ed_works() { assert_ok!(Tokens::deposit(KSM, &parent_account, 100 * dollar(KSM))); let _ = pallet_balances::Pallet::::deposit_creating(&parent_account, 100 * dollar(KAR)); - kar_treasury_amount = Currencies::free_balance(KAR, &KaruraTreasuryAccount::get()); + kar_treasury_amount = Currencies::free_balance(KAR, &NetworkTreasuryPool::get()); }); let assets: MultiAsset = (Parent, ksm_asset_amount).into(); @@ -715,11 +717,11 @@ fn trap_assets_larger_than_ed_works() { assert_eq!( trader_weight_to_treasury + dollar(KSM), - Currencies::free_balance(KSM, &KaruraTreasuryAccount::get()) + Currencies::free_balance(KSM, &NetworkTreasuryPool::get()) ); assert_eq!( kar_treasury_amount, - Currencies::free_balance(KAR, &KaruraTreasuryAccount::get()) + Currencies::free_balance(KAR, &NetworkTreasuryPool::get()) ); }); } @@ -740,7 +742,7 @@ fn trap_assets_lower_than_ed_works() { Karura::execute_with(|| { assert_ok!(Tokens::deposit(KSM, &parent_account, dollar(KSM))); let _ = pallet_balances::Pallet::::deposit_creating(&parent_account, dollar(KAR)); - kar_treasury_amount = Currencies::free_balance(KAR, &KaruraTreasuryAccount::get()); + kar_treasury_amount = Currencies::free_balance(KAR, &NetworkTreasuryPool::get()); }); let assets: MultiAsset = (Parent, ksm_asset_amount).into(); @@ -771,11 +773,11 @@ fn trap_assets_lower_than_ed_works() { assert_eq!( ksm_asset_amount + dollar(KSM), - Currencies::free_balance(KSM, &KaruraTreasuryAccount::get()) + Currencies::free_balance(KSM, &NetworkTreasuryPool::get()) ); assert_eq!( kar_asset_amount, - Currencies::free_balance(KAR, &KaruraTreasuryAccount::get()) - kar_treasury_amount + Currencies::free_balance(KAR, &NetworkTreasuryPool::get()) - kar_treasury_amount ); }); } @@ -790,7 +792,7 @@ fn sibling_trap_assets_works() { Karura::execute_with(|| { assert_ok!(Tokens::deposit(BNC, &sibling_reserve_account(), dollar(BNC))); let _ = pallet_balances::Pallet::::deposit_creating(&sibling_reserve_account(), dollar(KAR)); - kar_treasury_amount = Currencies::free_balance(KAR, &KaruraTreasuryAccount::get()); + kar_treasury_amount = Currencies::free_balance(KAR, &NetworkTreasuryPool::get()); }); Sibling::execute_with(|| { @@ -824,11 +826,11 @@ fn sibling_trap_assets_works() { None ); assert_eq!( - Currencies::free_balance(KAR, &KaruraTreasuryAccount::get()) - kar_treasury_amount, + Currencies::free_balance(KAR, &NetworkTreasuryPool::get()) - kar_treasury_amount, kar_asset_amount ); assert_eq!( - Currencies::free_balance(BNC, &KaruraTreasuryAccount::get()), + Currencies::free_balance(BNC, &NetworkTreasuryPool::get()), bnc_asset_amount ); }); diff --git a/runtime/integration-tests/src/relaychain/kusama_test_net.rs b/runtime/integration-tests/src/relaychain/kusama_test_net.rs index c28a3f5c32..ff41ee1bfc 100644 --- a/runtime/integration-tests/src/relaychain/kusama_test_net.rs +++ b/runtime/integration-tests/src/relaychain/kusama_test_net.rs @@ -26,6 +26,7 @@ use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; use polkadot_runtime_parachains::configuration::HostConfiguration; use sp_runtime::traits::AccountIdConversion; +use runtime_common::NetworkTreasuryPool; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; decl_test_relay_chain! { @@ -166,6 +167,7 @@ pub fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { .balances(vec![ (AccountId::from(ALICE), KSM, 10 * dollar(KSM)), (karura_runtime::KaruraTreasuryAccount::get(), KSM, dollar(KSM)), + (NetworkTreasuryPool::get(), KSM, dollar(KSM)), ]) .parachain_id(parachain_id) .build() diff --git a/runtime/integration-tests/src/setup.rs b/runtime/integration-tests/src/setup.rs index 243e2ce09c..98e49e95d0 100644 --- a/runtime/integration-tests/src/setup.rs +++ b/runtime/integration-tests/src/setup.rs @@ -86,7 +86,6 @@ pub use karura_imports::*; mod karura_imports { pub use frame_support::parameter_types; pub use karura_runtime::xcm_config::*; - use karura_runtime::AlternativeFeeSurplus; pub use karura_runtime::{ constants::parachains, create_x2_parachain_multilocation, get_all_module_accounts, AcalaOracle, AccountId, AssetRegistry, AuctionManager, Authority, AuthoritysOriginId, Balance, Balances, BlockNumber, Call, CdpEngine, @@ -99,6 +98,7 @@ mod karura_imports { TransactionPayment, TransactionPaymentPalletId, TreasuryPalletId, Utility, Vesting, XTokens, XcmInterface, EVM, NFT, }; + use karura_runtime::{AlternativeFeeSurplus, KaruraTreasuryAccount}; use module_transaction_payment::BuyWeightRateOfTransactionFeePool; pub use primitives::TradingPair; pub use runtime_common::{cent, dollar, millicent, FixedRateOfAsset, KAR, KSM, KUSD, LKSM}; @@ -113,7 +113,7 @@ mod karura_imports { TradingPair::from_currency_ids(USD_CURRENCY, LIQUID_CURRENCY).unwrap(), TradingPair::from_currency_ids(RELAY_CHAIN_CURRENCY, NATIVE_CURRENCY).unwrap(), ]; - pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); + pub TreasuryAccount: AccountId = KaruraTreasuryAccount::get(); } pub const NATIVE_CURRENCY: CurrencyId = KAR; @@ -138,7 +138,6 @@ use primitives::IncomeSource; #[cfg(feature = "with-acala-runtime")] mod acala_imports { pub use acala_runtime::xcm_config::*; - use acala_runtime::AlternativeFeeSurplus; pub use acala_runtime::{ create_x2_parachain_multilocation, get_all_module_accounts, AcalaFoundationAccounts, AcalaOracle, AccountId, AssetRegistry, AuctionManager, Authority, AuthoritysOriginId, Balance, Balances, BlockNumber, Call, CdpEngine, @@ -148,8 +147,9 @@ mod acala_imports { NativeTokenExistentialDeposit, NetworkId, NftPalletId, OneDay, Origin, OriginCaller, ParachainAccount, ParachainInfo, ParachainSystem, PolkadotXcm, Proxy, ProxyType, Ratio, Runtime, Scheduler, Session, SessionManager, SevenDays, System, Timestamp, TipPerWeightStep, TokenSymbol, Tokens, TransactionPayment, - TransactionPaymentPalletId, TreasuryPalletId, Utility, Vesting, XTokens, XcmInterface, EVM, LCDOT, NFT, + TransactionPaymentPalletId, Utility, Vesting, XTokens, XcmInterface, EVM, LCDOT, NFT, }; + use acala_runtime::{AcalaTreasuryAccount, AlternativeFeeSurplus}; pub use frame_support::parameter_types; use module_transaction_payment::BuyWeightRateOfTransactionFeePool; pub use primitives::TradingPair; @@ -167,7 +167,7 @@ mod acala_imports { TradingPair::from_currency_ids(RELAY_CHAIN_CURRENCY, NATIVE_CURRENCY).unwrap(), TradingPair::from_currency_ids(RELAY_CHAIN_CURRENCY, LCDOT).unwrap(), ]; - pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); + pub TreasuryAccount: AccountId = AcalaTreasuryAccount::get(); } pub const NATIVE_CURRENCY: CurrencyId = ACA; @@ -373,7 +373,8 @@ impl ExtBuilder { IncomeSource::TxFee, vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], ), - (IncomeSource::XcmFee, vec![(TreasuryAccount::get(), 100)]), + // xcm buy weight revenue deposit to NetworkTreasuryPool account + (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), ], treasuries: vec![], } diff --git a/runtime/integration-tests/src/treasury.rs b/runtime/integration-tests/src/treasury.rs index 97dd257996..5ca64ec31f 100644 --- a/runtime/integration-tests/src/treasury.rs +++ b/runtime/integration-tests/src/treasury.rs @@ -17,6 +17,7 @@ // along with this program. If not, see . use crate::setup::*; +use runtime_common::NetworkTreasuryPool; #[test] fn treasury_should_take_xcm_execution_revenue() { @@ -70,7 +71,7 @@ fn treasury_should_take_xcm_execution_revenue() { assert_eq!(Tokens::free_balance(RELAY_CHAIN_CURRENCY, &ALICE.into()), actual_amount); assert_eq!( - Tokens::free_balance(RELAY_CHAIN_CURRENCY, &TreasuryAccount::get()), + Tokens::free_balance(RELAY_CHAIN_CURRENCY, &NetworkTreasuryPool::get()), dot_amount - actual_amount ); }); diff --git a/runtime/integration-tests/src/vesting.rs b/runtime/integration-tests/src/vesting.rs index e9192f5970..cd6531dac2 100644 --- a/runtime/integration-tests/src/vesting.rs +++ b/runtime/integration-tests/src/vesting.rs @@ -23,7 +23,7 @@ use orml_vesting::VestingSchedule; fn test_vesting_use_relaychain_block_number() { ExtBuilder::default().build().execute_with(|| { #[cfg(feature = "with-mandala-runtime")] - let signer: AccountId = TreasuryPalletId::get().into_account_truncating(); + let signer: AccountId = TreasuryAccount::get(); #[cfg(feature = "with-karura-runtime")] let signer: AccountId = KaruraFoundationAccounts::get()[0].clone(); #[cfg(feature = "with-acala-runtime")] From a45260c7695de60b1da57b37ba8f0769f4646cc6 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Thu, 16 Jun 2022 19:00:29 +1200 Subject: [PATCH 33/49] Fixed acala integration test build problem --- runtime/integration-tests/src/setup.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/runtime/integration-tests/src/setup.rs b/runtime/integration-tests/src/setup.rs index 83d8fe7aa1..2419e6ba05 100644 --- a/runtime/integration-tests/src/setup.rs +++ b/runtime/integration-tests/src/setup.rs @@ -142,12 +142,13 @@ mod acala_imports { create_x2_parachain_multilocation, get_all_module_accounts, AcalaFoundationAccounts, AcalaOracle, AccountId, AssetRegistry, AuctionManager, Authority, AuthoritysOriginId, Balance, Balances, BlockNumber, Call, CdpEngine, CdpTreasury, CreateClassDeposit, CreateTokenDeposit, Currencies, CurrencyId, DataDepositPerByte, - DefaultExchangeRate, Dex, EmergencyShutdown, Event, EvmAccounts, ExistentialDeposits, FinancialCouncil, Get, - GetNativeCurrencyId, Homa, Honzon, IdleScheduler, Loans, MaxTipsOfPriority, MinimumDebitValue, MultiLocation, - NativeTokenExistentialDeposit, NetworkId, NftPalletId, OneDay, Origin, OriginCaller, ParachainAccount, - ParachainInfo, ParachainSystem, PolkadotXcm, Proxy, ProxyType, Ratio, Runtime, Scheduler, Session, - SessionManager, SevenDays, System, Timestamp, TipPerWeightStep, TokenSymbol, Tokens, TransactionPayment, - TransactionPaymentPalletId, TreasuryPalletId, Utility, Vesting, XTokens, XcmInterface, EVM, LCDOT, NFT, + DefaultExchangeRate, Dex, EmergencyShutdown, Event, EvmAccounts, ExistentialDeposits, Fees, FinancialCouncil, + Get, GetNativeCurrencyId, Homa, Honzon, IdleScheduler, Loans, MaxTipsOfPriority, MinimumDebitValue, + MultiLocation, NativeTokenExistentialDeposit, NetworkId, NftPalletId, OneDay, Origin, OriginCaller, + ParachainAccount, ParachainInfo, ParachainSystem, PolkadotXcm, Proxy, ProxyType, Ratio, Runtime, Scheduler, + Session, SessionManager, SevenDays, System, Timestamp, TipPerWeightStep, TokenSymbol, Tokens, + TransactionPayment, TransactionPaymentPalletId, TreasuryPalletId, Utility, Vesting, XTokens, XcmInterface, EVM, + LCDOT, NFT, }; use acala_runtime::{AcalaTreasuryAccount, AlternativeFeeSurplus}; pub use frame_support::parameter_types; From 679a97b60673acf1e0224ceed29541bc29ffefec Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Fri, 17 Jun 2022 17:08:12 +1200 Subject: [PATCH 34/49] Updated a unit test --- modules/cdp-engine/src/tests.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/modules/cdp-engine/src/tests.rs b/modules/cdp-engine/src/tests.rs index 0c2adcac13..cc2d3d5f6f 100644 --- a/modules/cdp-engine/src/tests.rs +++ b/modules/cdp-engine/src/tests.rs @@ -64,7 +64,7 @@ fn setup_fees_distribution() { Origin::root(), IncomeSource::HonzonStabilityFee, vec![PoolPercent { - pool: TreasuryAccount::get(), + pool: BOB, rate: Rate::one(), }], )); @@ -1907,14 +1907,12 @@ fn accumulated_interest_goes_to_on_fee_deposit() { assert_eq!(CDPEngineModule::get_interest_rate_per_sec(DOT), Ok(Rate::one())); // Treasury starts off empty. - assert_eq!(Currencies::free_balance(BTC, &TreasuryAccount::get()), 0); - assert_eq!(Currencies::free_balance(DOT, &TreasuryAccount::get()), 0); + assert_eq!(Currencies::free_balance(AUSD, &BOB), 0); CDPEngineModule::accumulate_interest(1, 0); // No debit generates no interest. - assert_eq!(Currencies::free_balance(BTC, &TreasuryAccount::get()), 0); - assert_eq!(Currencies::free_balance(DOT, &TreasuryAccount::get()), 0); + assert_eq!(Currencies::free_balance(AUSD, &BOB), 0); assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 1000, 1000)); assert_ok!(CDPEngineModule::adjust_position(&ALICE, DOT, 1000, 1000)); @@ -1924,7 +1922,7 @@ fn accumulated_interest_goes_to_on_fee_deposit() { // Generated interest = debit * debit_exchange_rate * interest_rate // = 1000 * 0.1 * 0.01 + 1000 * 0.1 * 1 = 101 - assert_eq!(Currencies::free_balance(AUSD, &TreasuryAccount::get()), 101); + assert_eq!(Currencies::free_balance(AUSD, &BOB), 101); assert_eq!( CDPEngineModule::get_debit_exchange_rate(BTC), @@ -1940,7 +1938,7 @@ fn accumulated_interest_goes_to_on_fee_deposit() { // Generated interest = debit * debit_exchange_rate * interest_rate // = 1000 * 0.101 * 0.01 + 1000 * 0.2 * 1 = 201 - assert_eq!(Currencies::free_balance(AUSD, &TreasuryAccount::get()), 302); + assert_eq!(Currencies::free_balance(AUSD, &BOB), 302); assert_eq!( CDPEngineModule::get_debit_exchange_rate(BTC), From ca5f62cca70c33ddc2b1f0685cc3e5e32cd637c5 Mon Sep 17 00:00:00 2001 From: zqh Date: Fri, 17 Jun 2022 15:36:23 +0800 Subject: [PATCH 35/49] add some comments --- modules/fees/src/lib.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index d453716a43..c76b1dcdbe 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -306,6 +306,7 @@ impl Pallet { Ok(()) } + /// Distribute/Deposit income to treasury pool account. fn distribution_fees( pool_rates: BoundedVec, MaxPoolSize>, currency_id: CurrencyId, @@ -333,6 +334,7 @@ impl Pallet { Ok(()) } + /// Transfer balance from treasury pool account to incentive pool account. fn distribution_incentive(treasury: T::AccountId) -> DispatchResult { let native_token = T::NativeCurrencyId::get(); let tokens = TreasuryTokens::::get(&treasury); @@ -363,6 +365,7 @@ impl Pallet { Ok(()) } + // Use dex swap foreign token to native token, then treasury pool account only has native token. fn get_native_account(treasury: &T::AccountId, native_token: CurrencyId, token: CurrencyId) -> Option { if native_token == token { let amount = T::Currency::free_balance(treasury); From 19877f18469a355ff44a8720aa0a8332a8aa217e Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 20 Jun 2022 09:02:52 +0800 Subject: [PATCH 36/49] dev genesis config to Karura/Acala --- modules/fees/src/lib.rs | 4 +- node/service/src/chain_spec/acala.rs | 60 +++++++++++++++++++++++--- node/service/src/chain_spec/karura.rs | 59 +++++++++++++++++++++---- node/service/src/chain_spec/mandala.rs | 11 ++--- runtime/karura/src/lib.rs | 2 +- runtime/mandala/src/lib.rs | 2 +- 6 files changed, 113 insertions(+), 25 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index c76b1dcdbe..d5f8333ee2 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -347,6 +347,7 @@ impl Pallet { } }); + // If treasury pool account has small native token, do not distribute to incentive pools. if total_native < threshold { return Ok(()); } @@ -365,7 +366,8 @@ impl Pallet { Ok(()) } - // Use dex swap foreign token to native token, then treasury pool account only has native token. + /// Use dex swap foreign token to native token, then treasury pool account only has native + /// token. fn get_native_account(treasury: &T::AccountId, native_token: CurrencyId, token: CurrencyId) -> Option { if native_token == token { let amount = T::Currency::free_balance(treasury); diff --git a/node/service/src/chain_spec/acala.rs b/node/service/src/chain_spec/acala.rs index f5268c2501..7d75703190 100644 --- a/node/service/src/chain_spec/acala.rs +++ b/node/service/src/chain_spec/acala.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use acala_primitives::AccountId; +use acala_primitives::{AccountId, IncomeSource}; use sc_chain_spec::{ChainType, Properties}; use serde_json::map::Map; use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -26,13 +26,16 @@ use sp_runtime::traits::Zero; use crate::chain_spec::{get_account_id_from_seed, get_parachain_authority_keys_from_seed, Extensions}; use acala_runtime::{ - dollar, Balance, BalancesConfig, BlockNumber, CdpEngineConfig, CdpTreasuryConfig, CollatorSelectionConfig, - DexConfig, EVMConfig, FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, + dollar, AcalaTreasuryAccount, Balance, BalancesConfig, BlockNumber, CdpEngineConfig, CdpTreasuryConfig, + CollatorSelectionConfig, DexConfig, EVMConfig, FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, PolkadotXcmConfig, SS58Prefix, SessionConfig, SessionDuration, SessionKeys, SessionManagerConfig, SudoConfig, SystemConfig, - TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, ACA, AUSD, DOT, LDOT, + TechnicalCommitteeMembershipConfig, TokensConfig, TreasuryPalletId, VestingConfig, ACA, AUSD, DOT, LDOT, +}; +use runtime_common::{ + CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, + HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, TokenInfo, }; -use runtime_common::TokenInfo; pub type ChainSpec = sc_service::GenericChainSpec; @@ -194,6 +197,51 @@ fn acala_dev_genesis( polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(2), }, - fees: Default::default(), + fees: fees_config(), + } +} + +fn fees_config() -> FeesConfig { + FeesConfig { + incomes: vec![ + ( + IncomeSource::TxFee, + vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + ), + (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), + (IncomeSource::DexSwapFee, vec![(NetworkTreasuryPool::get(), 100)]), + ( + IncomeSource::HonzonStabilityFee, + vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)], + ), + ( + IncomeSource::HonzonLiquidationFee, + vec![(NetworkTreasuryPool::get(), 30), (HonzonTreasuryPool::get(), 70)], + ), + ( + IncomeSource::HomaStakingRewardFee, + vec![(NetworkTreasuryPool::get(), 70), (HomaTreasuryPool::get(), 30)], + ), + ], + treasuries: vec![ + ( + NetworkTreasuryPool::get(), + 1000 * dollar(ACA), + vec![ + (StakingRewardPool::get(), 70), + (CollatorsRewardPool::get(), 10), + (EcosystemRewardPool::get(), 10), + (AcalaTreasuryAccount::get(), 10), + ], + ), + ( + HonzonTreasuryPool::get(), + 1000 * dollar(ACA), + vec![ + (HonzonInsuranceRewardPool::get(), 30), + (HonzonLiquitationRewardPool::get(), 70), + ], + ), + ], } } diff --git a/node/service/src/chain_spec/karura.rs b/node/service/src/chain_spec/karura.rs index 0a3caf6b7f..33c87b9e4e 100644 --- a/node/service/src/chain_spec/karura.rs +++ b/node/service/src/chain_spec/karura.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use acala_primitives::AccountId; +use acala_primitives::{AccountId, IncomeSource}; use sc_chain_spec::{ChainType, Properties}; use serde_json::map::Map; use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -26,13 +26,17 @@ use sp_runtime::traits::Zero; use crate::chain_spec::{get_account_id_from_seed, get_parachain_authority_keys_from_seed, Extensions}; use karura_runtime::{ - dollar, Balance, BalancesConfig, BlockNumber, CdpEngineConfig, CdpTreasuryConfig, CollatorSelectionConfig, - DexConfig, EVMConfig, FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, - HomaCouncilMembershipConfig, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, PolkadotXcmConfig, - SS58Prefix, SessionConfig, SessionDuration, SessionKeys, SessionManagerConfig, SudoConfig, SystemConfig, - TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, BNC, KAR, KSM, KUSD, LKSM, PHA, VSKSM, + dollar, Balance, BalancesConfig, BlockNumber, CDPTreasuryPalletId, CdpEngineConfig, CdpTreasuryConfig, + CollatorSelectionConfig, DexConfig, EVMConfig, FeesConfig, FinancialCouncilMembershipConfig, + GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, KaruraTreasuryAccount, OperatorMembershipAcalaConfig, + OrmlNFTConfig, ParachainInfoConfig, PolkadotXcmConfig, SS58Prefix, SessionConfig, SessionDuration, SessionKeys, + SessionManagerConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, TreasuryPalletId, + VestingConfig, BNC, KAR, KSM, KUSD, LKSM, PHA, VSKSM, +}; +use runtime_common::{ + CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, + HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, TokenInfo, }; -use runtime_common::TokenInfo; pub type ChainSpec = sc_service::GenericChainSpec; @@ -194,6 +198,45 @@ fn karura_dev_genesis( polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(2), }, - fees: Default::default(), + fees: fees_config(), + } +} + +fn fees_config() -> FeesConfig { + FeesConfig { + incomes: vec![ + ( + IncomeSource::TxFee, + vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + ), + (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), + (IncomeSource::DexSwapFee, vec![(NetworkTreasuryPool::get(), 100)]), + (IncomeSource::HonzonStabilityFee, vec![(HonzonTreasuryPool::get(), 30)]), + ( + IncomeSource::HonzonLiquidationFee, + vec![(NetworkTreasuryPool::get(), 30), (HonzonTreasuryPool::get(), 70)], + ), + ( + IncomeSource::HomaStakingRewardFee, + vec![(NetworkTreasuryPool::get(), 70), (HomaTreasuryPool::get(), 30)], + ), + ], + treasuries: vec![ + ( + NetworkTreasuryPool::get(), + 1000 * dollar(KAR), + vec![ + (StakingRewardPool::get(), 70), + (CollatorsRewardPool::get(), 10), + (EcosystemRewardPool::get(), 10), + (KaruraTreasuryAccount::get(), 10), + ], + ), + ( + HonzonTreasuryPool::get(), + 10 * dollar(KAR), + vec![(CDPTreasuryPalletId::get(), 100)], + ), + ], } } diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 5fabb965fa..7633ac6fb3 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -24,7 +24,7 @@ use k256::{ ecdsa::{SigningKey, VerifyingKey}, EncodedPoint as K256PublicKey, }; -use mandala_runtime::{FeesConfig, TreasuryPalletId}; +use mandala_runtime::{FeesConfig, TreasuryAccount, TreasuryPalletId, ACA}; use runtime_common::{ dollar, evm_genesis, CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, @@ -35,10 +35,7 @@ use serde_json::map::Map; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::UncheckedInto, sr25519, H160}; use sp_finality_grandpa::AuthorityId as GrandpaId; -use sp_runtime::{ - traits::{AccountIdConversion, Zero}, - FixedPointNumber, FixedU128, -}; +use sp_runtime::{traits::Zero, FixedPointNumber, FixedU128}; use sp_std::{collections::btree_map::BTreeMap, str::FromStr}; use tiny_keccak::{Hasher, Keccak}; @@ -693,8 +690,6 @@ fn mandala_genesis( } fn fees_config() -> FeesConfig { - use mandala_runtime::ACA; - FeesConfig { incomes: vec![ ( @@ -724,7 +719,7 @@ fn fees_config() -> FeesConfig { (StakingRewardPool::get(), 70), (CollatorsRewardPool::get(), 10), (EcosystemRewardPool::get(), 10), - (TreasuryPalletId::get().into_account_truncating(), 10), + (TreasuryAccount::get(), 10), ], ), ( diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index b8eabddf5a..5f5122e288 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1565,7 +1565,7 @@ impl module_idle_scheduler::Config for Runtime { } parameter_types! { - pub const AllocationPeriod: BlockNumber = 7 * DAYS; + pub const AllocationPeriod: BlockNumber = 3 * DAYS; } impl module_fees::Config for Runtime { diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 695ccdc738..8a700536d3 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1756,7 +1756,7 @@ impl module_idle_scheduler::Config for Runtime { } parameter_types! { - pub const AllocationPeriod: BlockNumber = DAYS; + pub const AllocationPeriod: BlockNumber = 10 * MINUTES; } impl module_fees::Config for Runtime { From e4c492364c02f9f4af6d7e96a062a5c63fe1a5a4 Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 20 Jun 2022 09:24:27 +0800 Subject: [PATCH 37/49] FeesConfig --- node/service/src/chain_spec/acala.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/node/service/src/chain_spec/acala.rs b/node/service/src/chain_spec/acala.rs index 7d75703190..a98f074efd 100644 --- a/node/service/src/chain_spec/acala.rs +++ b/node/service/src/chain_spec/acala.rs @@ -27,10 +27,11 @@ use crate::chain_spec::{get_account_id_from_seed, get_parachain_authority_keys_f use acala_runtime::{ dollar, AcalaTreasuryAccount, Balance, BalancesConfig, BlockNumber, CdpEngineConfig, CdpTreasuryConfig, - CollatorSelectionConfig, DexConfig, EVMConfig, FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, - HomaCouncilMembershipConfig, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, PolkadotXcmConfig, - SS58Prefix, SessionConfig, SessionDuration, SessionKeys, SessionManagerConfig, SudoConfig, SystemConfig, - TechnicalCommitteeMembershipConfig, TokensConfig, TreasuryPalletId, VestingConfig, ACA, AUSD, DOT, LDOT, + CollatorSelectionConfig, DexConfig, EVMConfig, FeesConfig, FinancialCouncilMembershipConfig, + GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, OperatorMembershipAcalaConfig, OrmlNFTConfig, + ParachainInfoConfig, PolkadotXcmConfig, SS58Prefix, SessionConfig, SessionDuration, SessionKeys, + SessionManagerConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, TreasuryPalletId, + VestingConfig, ACA, AUSD, DOT, LDOT, }; use runtime_common::{ CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, From 0a4aa8029b56308c11c6fff27214e74d4d7eee76 Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 20 Jun 2022 09:42:18 +0800 Subject: [PATCH 38/49] fix clippy --- node/service/src/chain_spec/acala.rs | 4 ++-- node/service/src/chain_spec/karura.rs | 12 ++++++------ node/service/src/chain_spec/mandala.rs | 6 +++--- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/node/service/src/chain_spec/acala.rs b/node/service/src/chain_spec/acala.rs index a98f074efd..f78247f6c6 100644 --- a/node/service/src/chain_spec/acala.rs +++ b/node/service/src/chain_spec/acala.rs @@ -30,8 +30,8 @@ use acala_runtime::{ CollatorSelectionConfig, DexConfig, EVMConfig, FeesConfig, FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, PolkadotXcmConfig, SS58Prefix, SessionConfig, SessionDuration, SessionKeys, - SessionManagerConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, TreasuryPalletId, - VestingConfig, ACA, AUSD, DOT, LDOT, + SessionManagerConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, + ACA, AUSD, DOT, LDOT, }; use runtime_common::{ CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, diff --git a/node/service/src/chain_spec/karura.rs b/node/service/src/chain_spec/karura.rs index 33c87b9e4e..4e8ec2ff5c 100644 --- a/node/service/src/chain_spec/karura.rs +++ b/node/service/src/chain_spec/karura.rs @@ -21,7 +21,7 @@ use sc_chain_spec::{ChainType, Properties}; use serde_json::map::Map; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::sr25519; -use sp_runtime::traits::Zero; +use sp_runtime::traits::{AccountIdConversion, Zero}; use crate::chain_spec::{get_account_id_from_seed, get_parachain_authority_keys_from_seed, Extensions}; @@ -30,12 +30,12 @@ use karura_runtime::{ CollatorSelectionConfig, DexConfig, EVMConfig, FeesConfig, FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, KaruraTreasuryAccount, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, PolkadotXcmConfig, SS58Prefix, SessionConfig, SessionDuration, SessionKeys, - SessionManagerConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, TreasuryPalletId, - VestingConfig, BNC, KAR, KSM, KUSD, LKSM, PHA, VSKSM, + SessionManagerConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, + BNC, KAR, KSM, KUSD, LKSM, PHA, VSKSM, }; use runtime_common::{ - CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, - HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, TokenInfo, + CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonTreasuryPool, NetworkTreasuryPool, + StakingRewardPool, TokenInfo, }; pub type ChainSpec = sc_service::GenericChainSpec; @@ -235,7 +235,7 @@ fn fees_config() -> FeesConfig { ( HonzonTreasuryPool::get(), 10 * dollar(KAR), - vec![(CDPTreasuryPalletId::get(), 100)], + vec![(CDPTreasuryPalletId::get().into_account_truncating(), 100)], ), ], } diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 7633ac6fb3..4453fbf31f 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -24,7 +24,7 @@ use k256::{ ecdsa::{SigningKey, VerifyingKey}, EncodedPoint as K256PublicKey, }; -use mandala_runtime::{FeesConfig, TreasuryAccount, TreasuryPalletId, ACA}; +use mandala_runtime::{FeesConfig, TreasuryAccount, ACA}; use runtime_common::{ dollar, evm_genesis, CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, @@ -317,7 +317,7 @@ fn testnet_genesis( FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, IndicesConfig, NativeTokenExistentialDeposit, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, PolkadotXcmConfig, RenVmBridgeConfig, SessionConfig, SessionDuration, SessionKeys, SessionManagerConfig, - StarportConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, ACA, + StarportConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, AUSD, DOT, LDOT, RENBTC, }; @@ -518,7 +518,7 @@ fn mandala_genesis( FinancialCouncilMembershipConfig, GeneralCouncilMembershipConfig, HomaCouncilMembershipConfig, IndicesConfig, NativeTokenExistentialDeposit, OperatorMembershipAcalaConfig, OrmlNFTConfig, ParachainInfoConfig, PolkadotXcmConfig, RenVmBridgeConfig, SessionConfig, SessionDuration, SessionKeys, SessionManagerConfig, - StarportConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, ACA, + StarportConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, AUSD, DOT, LDOT, RENBTC, }; From 30122aa69caba1a7f1dc07a1dca4c46f7780f850 Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 20 Jun 2022 13:32:49 +0800 Subject: [PATCH 39/49] merge master --- modules/fees/Cargo.toml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/fees/Cargo.toml b/modules/fees/Cargo.toml index 013d48333f..403a6ee7f4 100644 --- a/modules/fees/Cargo.toml +++ b/modules/fees/Cargo.toml @@ -9,11 +9,11 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = scale-info = { version = "2.1", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false } orml-traits = { package = "orml-traits", path = "../../orml/traits", default-features = false } orml-tokens = { package = "orml-tokens", path = "../../orml/tokens", default-features = false } @@ -24,8 +24,8 @@ primitives = { package = "acala-primitives", path = "../../primitives", default- paste = "1.0" [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" } orml-tokens = { path = "../../orml/tokens" } module-currencies = { path = "../../modules/currencies" } module-dex = { path = "../../modules/dex" } From 351a8b58fabc6c34422488f2a87edaca0cde4cb1 Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Mon, 20 Jun 2022 08:56:25 +0000 Subject: [PATCH 40/49] cargo run --profile production --color=never --bin=acala --features=runtime-benchmarks --features=with-mandala-runtime -- benchmark pallet --chain=dev --steps=50 --repeat=20 --pallet=module_fees --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --template=./templates/runtime-weight-template.hbs --output=./runtime/mandala/src/weights/ --- runtime/mandala/src/weights/module_fees.rs | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 runtime/mandala/src/weights/module_fees.rs diff --git a/runtime/mandala/src/weights/module_fees.rs b/runtime/mandala/src/weights/module_fees.rs new file mode 100644 index 0000000000..51a1aa99c7 --- /dev/null +++ b/runtime/mandala/src/weights/module_fees.rs @@ -0,0 +1,74 @@ +// This file is part of Acala. + +// Copyright (C) 2020-2022 Acala Foundation. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Autogenerated weights for module_fees +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-06-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/acala +// benchmark +// pallet +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=module_fees +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --template=./templates/runtime-weight-template.hbs +// --output=./runtime/mandala/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for module_fees. +pub struct WeightInfo(PhantomData); +impl module_fees::WeightInfo for WeightInfo { + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees IncomeToTreasuries (r:1 w:1) + fn set_income_fee() -> Weight { + (16_072_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees TreasuryToIncentives (r:1 w:1) + fn set_treasury_pool() -> Weight { + (16_821_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees TreasuryTokens (r:1 w:0) + // Storage: Fees TreasuryToIncentives (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: EvmAccounts EvmAddresses (r:1 w:0) + fn force_transfer_to_incentive() -> Weight { + (47_115_000 as Weight) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } +} From af7347ac42c2d8743e65d7e287372e52e197afd3 Mon Sep 17 00:00:00 2001 From: zqh Date: Mon, 20 Jun 2022 17:05:27 +0800 Subject: [PATCH 41/49] runtime upgrade --- modules/fees/src/lib.rs | 7 +- node/service/src/chain_spec/acala.rs | 46 +++++++----- node/service/src/chain_spec/karura.rs | 42 +++++++---- node/service/src/chain_spec/mandala.rs | 49 ++++++++----- primitives/src/lib.rs | 2 +- runtime/acala/src/lib.rs | 93 ++++++++++++++++++++++++- runtime/karura/src/lib.rs | 86 ++++++++++++++++++++++- runtime/mandala/src/lib.rs | 96 +++++++++++++++++++++++++- 8 files changed, 361 insertions(+), 60 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index d5f8333ee2..5b957777a2 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -55,7 +55,7 @@ pub type Treasuries = Vec<( Vec<(::AccountId, u32)>, )>; -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct PoolPercent { pub pool: AccountId, @@ -163,7 +163,6 @@ pub mod module { StorageMap<_, Twox64Concat, T::AccountId, BoundedVec, ValueQuery>; #[pallet::pallet] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::genesis_config] @@ -249,7 +248,7 @@ pub mod module { } impl Pallet { - fn do_set_treasury_rate( + pub fn do_set_treasury_rate( income: IncomeSource, treasury_pool_rates: Vec>, ) -> DispatchResult { @@ -272,7 +271,7 @@ impl Pallet { Ok(()) } - fn do_set_incentive_rate( + pub fn do_set_incentive_rate( treasury: T::AccountId, threshold: Balance, incentive_pool_rates: Vec>, diff --git a/node/service/src/chain_spec/acala.rs b/node/service/src/chain_spec/acala.rs index f78247f6c6..316f968698 100644 --- a/node/service/src/chain_spec/acala.rs +++ b/node/service/src/chain_spec/acala.rs @@ -33,10 +33,7 @@ use acala_runtime::{ SessionManagerConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, ACA, AUSD, DOT, LDOT, }; -use runtime_common::{ - CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, HonzonLiquitationRewardPool, - HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, TokenInfo, -}; +use runtime_common::TokenInfo; pub type ChainSpec = sc_service::GenericChainSpec; @@ -207,40 +204,55 @@ fn fees_config() -> FeesConfig { incomes: vec![ ( IncomeSource::TxFee, - vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::XcmFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::DexSwapFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], ), - (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), - (IncomeSource::DexSwapFee, vec![(NetworkTreasuryPool::get(), 100)]), ( IncomeSource::HonzonStabilityFee, - vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HonzonTreasuryPool::get(), 30), + ], ), ( IncomeSource::HonzonLiquidationFee, - vec![(NetworkTreasuryPool::get(), 30), (HonzonTreasuryPool::get(), 70)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 30), + (runtime_common::HonzonTreasuryPool::get(), 70), + ], ), ( IncomeSource::HomaStakingRewardFee, - vec![(NetworkTreasuryPool::get(), 70), (HomaTreasuryPool::get(), 30)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HomaTreasuryPool::get(), 30), + ], ), ], treasuries: vec![ ( - NetworkTreasuryPool::get(), + runtime_common::NetworkTreasuryPool::get(), 1000 * dollar(ACA), vec![ - (StakingRewardPool::get(), 70), - (CollatorsRewardPool::get(), 10), - (EcosystemRewardPool::get(), 10), + (runtime_common::StakingRewardPool::get(), 70), + (runtime_common::CollatorsRewardPool::get(), 10), + (runtime_common::EcosystemRewardPool::get(), 10), (AcalaTreasuryAccount::get(), 10), ], ), ( - HonzonTreasuryPool::get(), + runtime_common::HonzonTreasuryPool::get(), 1000 * dollar(ACA), vec![ - (HonzonInsuranceRewardPool::get(), 30), - (HonzonLiquitationRewardPool::get(), 70), + (runtime_common::HonzonInsuranceRewardPool::get(), 30), + (runtime_common::HonzonLiquitationRewardPool::get(), 70), ], ), ], diff --git a/node/service/src/chain_spec/karura.rs b/node/service/src/chain_spec/karura.rs index 4e8ec2ff5c..01d20aa3eb 100644 --- a/node/service/src/chain_spec/karura.rs +++ b/node/service/src/chain_spec/karura.rs @@ -33,10 +33,7 @@ use karura_runtime::{ SessionManagerConfig, SudoConfig, SystemConfig, TechnicalCommitteeMembershipConfig, TokensConfig, VestingConfig, BNC, KAR, KSM, KUSD, LKSM, PHA, VSKSM, }; -use runtime_common::{ - CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonTreasuryPool, NetworkTreasuryPool, - StakingRewardPool, TokenInfo, -}; +use runtime_common::TokenInfo; pub type ChainSpec = sc_service::GenericChainSpec; @@ -207,33 +204,48 @@ fn fees_config() -> FeesConfig { incomes: vec![ ( IncomeSource::TxFee, - vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::XcmFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::DexSwapFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::HonzonStabilityFee, + vec![(runtime_common::HonzonTreasuryPool::get(), 100)], ), - (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), - (IncomeSource::DexSwapFee, vec![(NetworkTreasuryPool::get(), 100)]), - (IncomeSource::HonzonStabilityFee, vec![(HonzonTreasuryPool::get(), 30)]), ( IncomeSource::HonzonLiquidationFee, - vec![(NetworkTreasuryPool::get(), 30), (HonzonTreasuryPool::get(), 70)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 30), + (runtime_common::HonzonTreasuryPool::get(), 70), + ], ), ( IncomeSource::HomaStakingRewardFee, - vec![(NetworkTreasuryPool::get(), 70), (HomaTreasuryPool::get(), 30)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HomaTreasuryPool::get(), 30), + ], ), ], treasuries: vec![ ( - NetworkTreasuryPool::get(), + runtime_common::NetworkTreasuryPool::get(), 1000 * dollar(KAR), vec![ - (StakingRewardPool::get(), 70), - (CollatorsRewardPool::get(), 10), - (EcosystemRewardPool::get(), 10), + (runtime_common::StakingRewardPool::get(), 70), + (runtime_common::CollatorsRewardPool::get(), 10), + (runtime_common::EcosystemRewardPool::get(), 10), (KaruraTreasuryAccount::get(), 10), ], ), ( - HonzonTreasuryPool::get(), + runtime_common::HonzonTreasuryPool::get(), 10 * dollar(KAR), vec![(CDPTreasuryPalletId::get().into_account_truncating(), 100)], ), diff --git a/node/service/src/chain_spec/mandala.rs b/node/service/src/chain_spec/mandala.rs index 4453fbf31f..92e901d228 100644 --- a/node/service/src/chain_spec/mandala.rs +++ b/node/service/src/chain_spec/mandala.rs @@ -25,10 +25,7 @@ use k256::{ EncodedPoint as K256PublicKey, }; use mandala_runtime::{FeesConfig, TreasuryAccount, ACA}; -use runtime_common::{ - dollar, evm_genesis, CollatorsRewardPool, EcosystemRewardPool, HomaTreasuryPool, HonzonInsuranceRewardPool, - HonzonLiquitationRewardPool, HonzonTreasuryPool, NetworkTreasuryPool, StakingRewardPool, -}; +use runtime_common::{dollar, evm_genesis}; use sc_chain_spec::ChainType; use sc_telemetry::TelemetryEndpoints; use serde_json::map::Map; @@ -694,40 +691,58 @@ fn fees_config() -> FeesConfig { incomes: vec![ ( IncomeSource::TxFee, - vec![(NetworkTreasuryPool::get(), 80), (CollatorsRewardPool::get(), 20)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 80), + (runtime_common::CollatorsRewardPool::get(), 20), + ], + ), + ( + IncomeSource::XcmFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::DexSwapFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], ), - (IncomeSource::XcmFee, vec![(NetworkTreasuryPool::get(), 100)]), - (IncomeSource::DexSwapFee, vec![(NetworkTreasuryPool::get(), 100)]), ( IncomeSource::HonzonStabilityFee, - vec![(NetworkTreasuryPool::get(), 70), (HonzonTreasuryPool::get(), 30)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HonzonTreasuryPool::get(), 30), + ], ), ( IncomeSource::HonzonLiquidationFee, - vec![(NetworkTreasuryPool::get(), 30), (HonzonTreasuryPool::get(), 70)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 30), + (runtime_common::HonzonTreasuryPool::get(), 70), + ], ), ( IncomeSource::HomaStakingRewardFee, - vec![(NetworkTreasuryPool::get(), 70), (HomaTreasuryPool::get(), 30)], + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HomaTreasuryPool::get(), 30), + ], ), ], treasuries: vec![ ( - NetworkTreasuryPool::get(), + runtime_common::NetworkTreasuryPool::get(), 1000 * dollar(ACA), vec![ - (StakingRewardPool::get(), 70), - (CollatorsRewardPool::get(), 10), - (EcosystemRewardPool::get(), 10), + (runtime_common::StakingRewardPool::get(), 70), + (runtime_common::CollatorsRewardPool::get(), 10), + (runtime_common::EcosystemRewardPool::get(), 10), (TreasuryAccount::get(), 10), ], ), ( - HonzonTreasuryPool::get(), + runtime_common::HonzonTreasuryPool::get(), 1000 * dollar(ACA), vec![ - (HonzonInsuranceRewardPool::get(), 30), - (HonzonLiquitationRewardPool::get(), 70), + (runtime_common::HonzonInsuranceRewardPool::get(), 30), + (runtime_common::HonzonLiquitationRewardPool::get(), 70), ], ), ], diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index e153cf658c..240371fb9e 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -192,7 +192,7 @@ pub enum ReserveIdentifier { Count, } -#[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, TypeInfo)] +#[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum IncomeSource { TxFee, diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index 153fd149d2..9c23f6fd41 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -1765,8 +1765,97 @@ pub type SignedPayload = generic::SignedPayload; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic; /// Executive: handles dispatch to the various modules. -pub type Executive = - frame_executive::Executive, Runtime, AllPalletsWithSystem, ()>; +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + FeesMigration, +>; + +pub struct FeesMigration; + +impl OnRuntimeUpgrade for FeesMigration { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + use primitives::IncomeSource; + let incomes = vec![ + ( + IncomeSource::TxFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::XcmFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::DexSwapFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::HonzonStabilityFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HonzonTreasuryPool::get(), 30), + ], + ), + ( + IncomeSource::HonzonLiquidationFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 30), + (runtime_common::HonzonTreasuryPool::get(), 70), + ], + ), + ( + IncomeSource::HomaStakingRewardFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HomaTreasuryPool::get(), 30), + ], + ), + ]; + let treasuries = vec![ + ( + runtime_common::NetworkTreasuryPool::get(), + 1000 * dollar(ACA), + vec![ + (runtime_common::StakingRewardPool::get(), 70), + (runtime_common::CollatorsRewardPool::get(), 10), + (runtime_common::EcosystemRewardPool::get(), 10), + (AcalaTreasuryAccount::get(), 10), + ], + ), + ( + runtime_common::HonzonTreasuryPool::get(), + 1000 * dollar(ACA), + vec![ + (runtime_common::HonzonInsuranceRewardPool::get(), 30), + (runtime_common::HonzonLiquitationRewardPool::get(), 70), + ], + ), + ]; + incomes.iter().for_each(|(income, pools)| { + let pool_rates = module_fees::build_pool_percents::(pools.clone()); + let _ = >::do_set_treasury_rate(*income, pool_rates); + }); + treasuries.iter().for_each(|(treasury, threshold, pools)| { + let pool_rates = module_fees::build_pool_percents::(pools.clone()); + let _ = >::do_set_incentive_rate(treasury.clone(), *threshold, pool_rates); + }); + + ::BlockWeights::get().max_block + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result<(), &'static str> { + Ok(()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade() -> Result<(), &'static str> { + Ok(()) + } +} #[cfg(feature = "runtime-benchmarks")] #[macro_use] diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index b7b14a11bc..9c3e9fb9f9 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1805,8 +1805,90 @@ pub type SignedPayload = generic::SignedPayload; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic; /// Executive: handles dispatch to the various modules. -pub type Executive = - frame_executive::Executive, Runtime, AllPalletsWithSystem, ()>; +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + FeesMigration, +>; + +pub struct FeesMigration; + +impl OnRuntimeUpgrade for FeesMigration { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + use primitives::IncomeSource; + let incomes = vec![ + ( + IncomeSource::TxFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::XcmFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::DexSwapFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::HonzonStabilityFee, + vec![(runtime_common::HonzonTreasuryPool::get(), 100)], + ), + ( + IncomeSource::HonzonLiquidationFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 30), + (runtime_common::HonzonTreasuryPool::get(), 70), + ], + ), + ( + IncomeSource::HomaStakingRewardFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HomaTreasuryPool::get(), 30), + ], + ), + ]; + let treasuries = vec![ + ( + runtime_common::NetworkTreasuryPool::get(), + 1000 * dollar(KAR), + vec![ + (runtime_common::StakingRewardPool::get(), 70), + (runtime_common::CollatorsRewardPool::get(), 10), + (runtime_common::EcosystemRewardPool::get(), 10), + (KaruraTreasuryAccount::get(), 10), + ], + ), + ( + runtime_common::HonzonTreasuryPool::get(), + 10 * dollar(KAR), + vec![(CDPTreasuryPalletId::get().into_account_truncating(), 100)], + ), + ]; + incomes.iter().for_each(|(income, pools)| { + let pool_rates = module_fees::build_pool_percents::(pools.clone()); + let _ = >::do_set_treasury_rate(*income, pool_rates); + }); + treasuries.iter().for_each(|(treasury, threshold, pools)| { + let pool_rates = module_fees::build_pool_percents::(pools.clone()); + let _ = >::do_set_incentive_rate(treasury.clone(), *threshold, pool_rates); + }); + ::BlockWeights::get().max_block + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result<(), &'static str> { + Ok(()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade() -> Result<(), &'static str> { + Ok(()) + } +} #[cfg(feature = "runtime-benchmarks")] #[macro_use] diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 4bd8e6b1b5..38d1127520 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1891,8 +1891,100 @@ pub type SignedPayload = generic::SignedPayload; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic; /// Executive: handles dispatch to the various modules. -pub type Executive = - frame_executive::Executive, Runtime, AllPalletsWithSystem, ()>; +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + FeesMigration, +>; + +pub struct FeesMigration; + +impl OnRuntimeUpgrade for FeesMigration { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + use primitives::IncomeSource; + let incomes = vec![ + ( + IncomeSource::TxFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 80), + (runtime_common::CollatorsRewardPool::get(), 20), + ], + ), + ( + IncomeSource::XcmFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::DexSwapFee, + vec![(runtime_common::NetworkTreasuryPool::get(), 100)], + ), + ( + IncomeSource::HonzonStabilityFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HonzonTreasuryPool::get(), 30), + ], + ), + ( + IncomeSource::HonzonLiquidationFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 30), + (runtime_common::HonzonTreasuryPool::get(), 70), + ], + ), + ( + IncomeSource::HomaStakingRewardFee, + vec![ + (runtime_common::NetworkTreasuryPool::get(), 70), + (runtime_common::HomaTreasuryPool::get(), 30), + ], + ), + ]; + let treasuries = vec![ + ( + runtime_common::NetworkTreasuryPool::get(), + 1000 * dollar(ACA), + vec![ + (runtime_common::StakingRewardPool::get(), 70), + (runtime_common::CollatorsRewardPool::get(), 10), + (runtime_common::EcosystemRewardPool::get(), 10), + (TreasuryAccount::get(), 10), + ], + ), + ( + runtime_common::HonzonTreasuryPool::get(), + 1000 * dollar(ACA), + vec![ + (runtime_common::HonzonInsuranceRewardPool::get(), 30), + (runtime_common::HonzonLiquitationRewardPool::get(), 70), + ], + ), + ]; + incomes.iter().for_each(|(income, pools)| { + let pool_rates = module_fees::build_pool_percents::(pools.clone()); + let _ = >::do_set_treasury_rate(*income, pool_rates); + }); + treasuries.iter().for_each(|(treasury, threshold, pools)| { + let pool_rates = module_fees::build_pool_percents::(pools.clone()); + let _ = >::do_set_incentive_rate(treasury.clone(), *threshold, pool_rates); + }); + + ::BlockWeights::get().max_block + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result<(), &'static str> { + Ok(()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade() -> Result<(), &'static str> { + Ok(()) + } +} construct_runtime!( pub enum Runtime where From 57444e59c8a8338507d5364b8a571cfbcdcc1fce Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Mon, 20 Jun 2022 09:48:04 +0000 Subject: [PATCH 42/49] cargo run --profile production --color=never --bin=acala --features=runtime-benchmarks --features=with-karura-runtime -- benchmark pallet --chain=karura-dev --steps=50 --repeat=20 --pallet=module_fees --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --template=./templates/runtime-weight-template.hbs --output=./runtime/karura/src/weights/ --- runtime/karura/src/weights/module_fees.rs | 72 +++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 runtime/karura/src/weights/module_fees.rs diff --git a/runtime/karura/src/weights/module_fees.rs b/runtime/karura/src/weights/module_fees.rs new file mode 100644 index 0000000000..5a0405f927 --- /dev/null +++ b/runtime/karura/src/weights/module_fees.rs @@ -0,0 +1,72 @@ +// This file is part of Acala. + +// Copyright (C) 2020-2022 Acala Foundation. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Autogenerated weights for module_fees +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-06-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("karura-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/acala +// benchmark +// pallet +// --chain=karura-dev +// --steps=50 +// --repeat=20 +// --pallet=module_fees +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --template=./templates/runtime-weight-template.hbs +// --output=./runtime/karura/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for module_fees. +pub struct WeightInfo(PhantomData); +impl module_fees::WeightInfo for WeightInfo { + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees IncomeToTreasuries (r:1 w:1) + fn set_income_fee() -> Weight { + (14_988_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees TreasuryToIncentives (r:1 w:1) + fn set_treasury_pool() -> Weight { + (15_911_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees TreasuryTokens (r:1 w:0) + // Storage: Fees TreasuryToIncentives (r:1 w:0) + fn force_transfer_to_incentive() -> Weight { + (8_493_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } +} From d79e376902f50959db275792f89ef9990d219db4 Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Mon, 20 Jun 2022 11:04:30 +0000 Subject: [PATCH 43/49] cargo run --profile production --color=never --bin=acala --features=runtime-benchmarks --features=with-acala-runtime -- benchmark pallet --chain=acala-dev --steps=50 --repeat=20 --pallet=module_fees --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --template=./templates/runtime-weight-template.hbs --output=./runtime/acala/src/weights/ --- runtime/acala/src/weights/module_fees.rs | 72 ++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 runtime/acala/src/weights/module_fees.rs diff --git a/runtime/acala/src/weights/module_fees.rs b/runtime/acala/src/weights/module_fees.rs new file mode 100644 index 0000000000..44d9cda670 --- /dev/null +++ b/runtime/acala/src/weights/module_fees.rs @@ -0,0 +1,72 @@ +// This file is part of Acala. + +// Copyright (C) 2020-2022 Acala Foundation. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Autogenerated weights for module_fees +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-06-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("acala-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/acala +// benchmark +// pallet +// --chain=acala-dev +// --steps=50 +// --repeat=20 +// --pallet=module_fees +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --template=./templates/runtime-weight-template.hbs +// --output=./runtime/acala/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for module_fees. +pub struct WeightInfo(PhantomData); +impl module_fees::WeightInfo for WeightInfo { + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees IncomeToTreasuries (r:1 w:1) + fn set_income_fee() -> Weight { + (15_453_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees TreasuryToIncentives (r:1 w:1) + fn set_treasury_pool() -> Weight { + (17_620_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees TreasuryTokens (r:1 w:0) + // Storage: Fees TreasuryToIncentives (r:1 w:0) + fn force_transfer_to_incentive() -> Weight { + (15_327_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } +} From 8a21a4a56e7fe8938f072ee69c4525cdc440c4c3 Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Mon, 20 Jun 2022 13:34:45 +0000 Subject: [PATCH 44/49] cargo run --release --color=never --bin=acala --features=runtime-benchmarks --features=with-mandala-runtime -- benchmark pallet --chain=dev --steps=50 --repeat=20 --pallet=module_fees --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./modules/fees/src/weights.rs --template=./templates/module-weight-template.hbs --- modules/fees/src/weights.rs | 67 ++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/modules/fees/src/weights.rs b/modules/fees/src/weights.rs index ac365ab82b..5f89026735 100644 --- a/modules/fees/src/weights.rs +++ b/modules/fees/src/weights.rs @@ -16,24 +16,25 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Autogenerated weights for module_asset_registry +//! Autogenerated weights for module_fees //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2022-03-24, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2022-06-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: // target/release/acala // benchmark +// pallet // --chain=dev // --steps=50 // --repeat=20 -// --pallet=module_asset_registry +// --pallet=module_fees // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./modules/asset-registry/src/weights.rs +// --output=./modules/fees/src/weights.rs // --template=./templates/module-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -44,9 +45,8 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; -/// Weight functions needed for module_asset_registry. +/// Weight functions needed for module_fees. pub trait WeightInfo { - fn on_initialize() -> Weight; fn set_income_fee() -> Weight; fn set_treasury_pool() -> Weight; fn force_transfer_to_incentive() -> Weight; @@ -55,48 +55,47 @@ pub trait WeightInfo { /// Weights for module_fees using the Acala node and recommended hardware. pub struct AcalaWeight(PhantomData); impl WeightInfo for AcalaWeight { - fn on_initialize() -> Weight { - (6_000_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - } - + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees IncomeToTreasuries (r:1 w:1) fn set_income_fee() -> Weight { - (21_475_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + (24_046_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) } + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees TreasuryToIncentives (r:1 w:1) fn set_treasury_pool() -> Weight { - (21_475_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + (24_273_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) } + // Storage: unknown [0x3a7472616e73616374696f6e5f6c6576656c3a] (r:1 w:1) + // Storage: Fees TreasuryTokens (r:1 w:0) + // Storage: Fees TreasuryToIncentives (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: EvmAccounts EvmAddresses (r:1 w:0) fn force_transfer_to_incentive() -> Weight { - (21_475_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + (69_853_000 as Weight) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) } } // For backwards compatibility and tests impl WeightInfo for () { - fn on_initialize() -> Weight { - (6_000_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - } - fn set_income_fee() -> Weight { - (21_475_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + (24_046_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } fn set_treasury_pool() -> Weight { - (21_475_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + (24_273_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } fn force_transfer_to_incentive() -> Weight { - (21_475_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + (69_853_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(6 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } } From db24f7ef5e84d0e76848c559c5dba94a691a6ab1 Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 21 Jun 2022 10:24:44 +0800 Subject: [PATCH 45/49] update runtime WeightInfo --- modules/fees/src/lib.rs | 2 +- runtime/acala/src/lib.rs | 2 +- runtime/acala/src/weights/mod.rs | 1 + runtime/karura/src/lib.rs | 2 +- runtime/karura/src/weights/mod.rs | 1 + runtime/mandala/src/lib.rs | 2 +- runtime/mandala/src/weights/mod.rs | 1 + 7 files changed, 7 insertions(+), 4 deletions(-) diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 5b957777a2..8064f0ab2d 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -202,7 +202,7 @@ pub mod module { Self::distribute_incentives(); ::WeightInfo::force_transfer_to_incentive() } else { - ::WeightInfo::on_initialize() + 0 } } } diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index b27ba9966b..46088fd715 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -1486,7 +1486,7 @@ parameter_types! { impl module_fees::Config for Runtime { type Event = Event; - type WeightInfo = (); + type WeightInfo = weights::module_fees::WeightInfo; type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; type Currency = Balances; type Currencies = Currencies; diff --git a/runtime/acala/src/weights/mod.rs b/runtime/acala/src/weights/mod.rs index 6cb5a57d0c..34f35ab452 100644 --- a/runtime/acala/src/weights/mod.rs +++ b/runtime/acala/src/weights/mod.rs @@ -30,6 +30,7 @@ pub mod module_dex_oracle; pub mod module_emergency_shutdown; pub mod module_evm; pub mod module_evm_accounts; +pub mod module_fees; pub mod module_homa; pub mod module_honzon; pub mod module_incentives; diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index b12f060c0b..4f04962a92 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1576,7 +1576,7 @@ parameter_types! { impl module_fees::Config for Runtime { type Event = Event; - type WeightInfo = (); + type WeightInfo = weights::module_fees::WeightInfo; type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; type Currency = Balances; type Currencies = Currencies; diff --git a/runtime/karura/src/weights/mod.rs b/runtime/karura/src/weights/mod.rs index 19cfb6ed65..121e79d913 100644 --- a/runtime/karura/src/weights/mod.rs +++ b/runtime/karura/src/weights/mod.rs @@ -30,6 +30,7 @@ pub mod module_dex_oracle; pub mod module_emergency_shutdown; pub mod module_evm; pub mod module_evm_accounts; +pub mod module_fees; pub mod module_homa; pub mod module_honzon; pub mod module_honzon_bridge; diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 864f4f99b1..7896771f13 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1767,7 +1767,7 @@ parameter_types! { impl module_fees::Config for Runtime { type Event = Event; - type WeightInfo = (); + type WeightInfo = weights::module_fees::WeightInfo; type UpdateOrigin = EnsureRootOrThreeFourthsGeneralCouncil; type Currency = Balances; type Currencies = Currencies; diff --git a/runtime/mandala/src/weights/mod.rs b/runtime/mandala/src/weights/mod.rs index ce9c0da45b..7844975b5d 100644 --- a/runtime/mandala/src/weights/mod.rs +++ b/runtime/mandala/src/weights/mod.rs @@ -30,6 +30,7 @@ pub mod module_dex_oracle; pub mod module_emergency_shutdown; pub mod module_evm; pub mod module_evm_accounts; +pub mod module_fees; pub mod module_homa; pub mod module_honzon; pub mod module_incentives; From c17c11f5d07dce5b904316bebb9766c7a87774f4 Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 21 Jun 2022 10:52:28 +0800 Subject: [PATCH 46/49] add DistributeTxFees to Karura/Acala --- runtime/acala/src/lib.rs | 19 ++----------------- runtime/karura/src/lib.rs | 19 ++----------------- runtime/karura/src/xcm_config.rs | 2 +- runtime/mandala/src/lib.rs | 4 ++-- 4 files changed, 7 insertions(+), 37 deletions(-) diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index 46088fd715..347f534ea6 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -72,8 +72,7 @@ pub use frame_support::{ traits::{ ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, Contains, ContainsLengthBound, Currency as PalletCurrency, EnsureOrigin, EqualPrivilegeOnly, Everything, Get, Imbalance, InstanceFilter, IsSubType, IsType, - KeyOwnerProofSystem, LockIdentifier, Nothing, OnRuntimeUpgrade, OnUnbalanced, Randomness, SortedMembers, - U128CurrencyToVote, + KeyOwnerProofSystem, LockIdentifier, Nothing, OnRuntimeUpgrade, Randomness, SortedMembers, U128CurrencyToVote, }, weights::{constants::RocksDbWeight, IdentityFee, Weight}, PalletId, RuntimeDebug, StorageValue, @@ -1168,27 +1167,13 @@ parameter_types! { pub DefaultFeeTokens: Vec = vec![AUSD, LCDOT, DOT, LDOT]; } -type NegativeImbalance = >::NegativeImbalance; -pub struct DealWithFees; -impl OnUnbalanced for DealWithFees { - fn on_unbalanceds(mut fees_then_tips: impl Iterator) { - if let Some(mut fees) = fees_then_tips.next() { - if let Some(tips) = fees_then_tips.next() { - tips.merge_into(&mut fees); - } - // for fees and tips, 100% to treasury - Treasury::on_unbalanced(fees); - } - } -} - impl module_transaction_payment::Config for Runtime { type Event = Event; type Call = Call; type NativeCurrencyId = GetNativeCurrencyId; type Currency = Balances; type MultiCurrency = Currencies; - type OnTransactionPayment = DealWithFees; + type OnTransactionPayment = module_fees::DistributeTxFees; type AlternativeFeeSwapDeposit = NativeTokenExistentialDeposit; type OperationalFeeMultiplier = OperationalFeeMultiplier; type TipPerWeightStep = TipPerWeightStep; diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 4f04962a92..38f5a682bc 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -71,8 +71,7 @@ pub use frame_support::{ traits::{ ConstBool, ConstU128, ConstU16, ConstU32, Contains, ContainsLengthBound, Currency as PalletCurrency, EnsureOrigin, EqualPrivilegeOnly, Everything, Get, Imbalance, InstanceFilter, IsSubType, IsType, - KeyOwnerProofSystem, LockIdentifier, Nothing, OnRuntimeUpgrade, OnUnbalanced, Randomness, SortedMembers, - U128CurrencyToVote, + KeyOwnerProofSystem, LockIdentifier, Nothing, OnRuntimeUpgrade, Randomness, SortedMembers, U128CurrencyToVote, }, weights::{constants::RocksDbWeight, IdentityFee, Weight}, PalletId, RuntimeDebug, StorageValue, @@ -1181,27 +1180,13 @@ parameter_types! { pub const AlternativeFeeSurplus: Percent = Percent::from_percent(25); } -type NegativeImbalance = >::NegativeImbalance; -pub struct DealWithFees; -impl OnUnbalanced for DealWithFees { - fn on_unbalanceds(mut fees_then_tips: impl Iterator) { - if let Some(mut fees) = fees_then_tips.next() { - if let Some(tips) = fees_then_tips.next() { - tips.merge_into(&mut fees); - } - // for fees and tips, 100% to treasury - Treasury::on_unbalanced(fees); - } - } -} - impl module_transaction_payment::Config for Runtime { type Event = Event; type Call = Call; type NativeCurrencyId = GetNativeCurrencyId; type Currency = Balances; type MultiCurrency = Currencies; - type OnTransactionPayment = DealWithFees; + type OnTransactionPayment = module_fees::DistributeTxFees; type AlternativeFeeSwapDeposit = NativeTokenExistentialDeposit; type OperationalFeeMultiplier = OperationalFeeMultiplier; type TipPerWeightStep = TipPerWeightStep; diff --git a/runtime/karura/src/xcm_config.rs b/runtime/karura/src/xcm_config.rs index e8681718c6..41bd97d7a3 100644 --- a/runtime/karura/src/xcm_config.rs +++ b/runtime/karura/src/xcm_config.rs @@ -171,7 +171,7 @@ parameter_types! { pub BaseRate: u128 = kar_per_second(); } -pub type XcmToTreasury = XcmFeeToTreasury; +type XcmToTreasury = XcmFeeToTreasury; pub type Trader = ( FixedRateOfAsset>, diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 7896771f13..83b24e7cf1 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -38,8 +38,8 @@ pub use frame_support::{ traits::{ ConstBool, ConstU128, ConstU16, ConstU32, Contains, ContainsLengthBound, Currency as PalletCurrency, EnsureOrigin, EqualPrivilegeOnly, Everything, Get, Imbalance, InstanceFilter, IsSubType, IsType, - KeyOwnerProofSystem, LockIdentifier, Nothing, OnRuntimeUpgrade, OnUnbalanced, Randomness, SortedMembers, - U128CurrencyToVote, WithdrawReasons, + KeyOwnerProofSystem, LockIdentifier, Nothing, OnRuntimeUpgrade, Randomness, SortedMembers, U128CurrencyToVote, + WithdrawReasons, }, weights::{ constants::{BlockExecutionWeight, RocksDbWeight, WEIGHT_PER_SECOND}, From 117f791eccc643a46b4fea707fc0c118e7bc94ff Mon Sep 17 00:00:00 2001 From: zqh Date: Tue, 21 Jun 2022 13:44:13 +0800 Subject: [PATCH 47/49] add post_upgrade assert --- runtime/acala/src/lib.rs | 20 +++++++++++++++++++- runtime/karura/src/lib.rs | 21 ++++++++++++++++++++- runtime/mandala/src/lib.rs | 21 ++++++++++++++++++++- 3 files changed, 59 insertions(+), 3 deletions(-) diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index 347f534ea6..7ba1dc646d 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -1763,11 +1763,11 @@ pub type Executive = frame_executive::Executive< FeesMigration, >; +use primitives::IncomeSource; pub struct FeesMigration; impl OnRuntimeUpgrade for FeesMigration { fn on_runtime_upgrade() -> frame_support::weights::Weight { - use primitives::IncomeSource; let incomes = vec![ ( IncomeSource::TxFee, @@ -1842,6 +1842,24 @@ impl OnRuntimeUpgrade for FeesMigration { #[cfg(feature = "try-runtime")] fn post_upgrade() -> Result<(), &'static str> { + assert!(>::contains_key( + &IncomeSource::TxFee + )); + assert!(>::contains_key( + &IncomeSource::XcmFee + )); + assert!(>::contains_key( + &IncomeSource::HonzonStabilityFee + )); + assert!(>::contains_key( + &IncomeSource::HomaStakingRewardFee + )); + assert!(>::contains_key( + &runtime_common::NetworkTreasuryPool::get() + )); + assert!(>::contains_key( + &runtime_common::HonzonTreasuryPool::get() + )); Ok(()) } } diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 38f5a682bc..d5f44c4841 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -1804,11 +1804,12 @@ pub type Executive = frame_executive::Executive< FeesMigration, >; +use primitives::IncomeSource; + pub struct FeesMigration; impl OnRuntimeUpgrade for FeesMigration { fn on_runtime_upgrade() -> frame_support::weights::Weight { - use primitives::IncomeSource; let incomes = vec![ ( IncomeSource::TxFee, @@ -1876,6 +1877,24 @@ impl OnRuntimeUpgrade for FeesMigration { #[cfg(feature = "try-runtime")] fn post_upgrade() -> Result<(), &'static str> { + assert!(>::contains_key( + &IncomeSource::TxFee + )); + assert!(>::contains_key( + &IncomeSource::XcmFee + )); + assert!(>::contains_key( + &IncomeSource::HonzonStabilityFee + )); + assert!(>::contains_key( + &IncomeSource::HomaStakingRewardFee + )); + assert!(>::contains_key( + &runtime_common::NetworkTreasuryPool::get() + )); + assert!(>::contains_key( + &runtime_common::HonzonTreasuryPool::get() + )); Ok(()) } } diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 83b24e7cf1..ca9b387329 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1905,11 +1905,12 @@ pub type Executive = frame_executive::Executive< FeesMigration, >; +use primitives::IncomeSource; + pub struct FeesMigration; impl OnRuntimeUpgrade for FeesMigration { fn on_runtime_upgrade() -> frame_support::weights::Weight { - use primitives::IncomeSource; let incomes = vec![ ( IncomeSource::TxFee, @@ -1987,6 +1988,24 @@ impl OnRuntimeUpgrade for FeesMigration { #[cfg(feature = "try-runtime")] fn post_upgrade() -> Result<(), &'static str> { + assert!(>::contains_key( + &IncomeSource::TxFee + )); + assert!(>::contains_key( + &IncomeSource::XcmFee + )); + assert!(>::contains_key( + &IncomeSource::HonzonStabilityFee + )); + assert!(>::contains_key( + &IncomeSource::HomaStakingRewardFee + )); + assert!(>::contains_key( + &runtime_common::NetworkTreasuryPool::get() + )); + assert!(>::contains_key( + &runtime_common::HonzonTreasuryPool::get() + )); Ok(()) } } From d0e6454f95f8e4897e495e9f4011c516a6cfd889 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Tue, 21 Jun 2022 21:00:47 +1200 Subject: [PATCH 48/49] Liquidation penalty now goes to OnFeeDeposit, and the same amount of debit is added to the Treasury. When liquidation is complete, the debit should be fully paid off. Updated tests accordingly. --- modules/cdp-engine/src/lib.rs | 8 +- modules/cdp-engine/src/tests.rs | 89 +++++++++++++++++-- modules/fees/src/lib.rs | 14 +-- modules/fees/src/mock.rs | 2 + modules/fees/src/tests.rs | 63 ++++++++++++- modules/homa/src/tests.rs | 2 +- primitives/src/lib.rs | 17 ++-- runtime/integration-tests/src/honzon.rs | 20 +++-- .../mandala/src/benchmarking/cdp_engine.rs | 21 ++++- runtime/mandala/src/benchmarking/fees.rs | 3 +- 10 files changed, 203 insertions(+), 36 deletions(-) diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 14f9e09e16..5d7f302c37 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -1155,6 +1155,13 @@ impl Pallet { let liquidation_penalty = Self::get_liquidation_penalty(currency_id)?; let target_stable_amount = liquidation_penalty.saturating_mul_acc_int(bad_debt_value); + let debt_penalty = liquidation_penalty.saturating_mul_int(bad_debt_value); + let stable_currency_id = T::GetStableCurrencyId::get(); + + // Deposit penalty to OnFeeDeposit and add the debt to the treasury. + T::OnFeeDeposit::on_fee_deposit(IncomeSource::HonzonLiquidationFee, stable_currency_id, debt_penalty)?; + ::CDPTreasury::on_system_debit(debt_penalty)?; + match currency_id { CurrencyId::DexShare(dex_share_0, dex_share_1) => { let token_0: CurrencyId = dex_share_0.into(); @@ -1165,7 +1172,6 @@ impl Pallet { ::CDPTreasury::remove_liquidity_for_lp_collateral(currency_id, collateral)?; // if these's stable - let stable_currency_id = T::GetStableCurrencyId::get(); if token_0 == stable_currency_id || token_1 == stable_currency_id { let (existing_stable, need_handle_currency, handle_amount) = if token_0 == stable_currency_id { (amount_0, token_1, amount_1) diff --git a/modules/cdp-engine/src/tests.rs b/modules/cdp-engine/src/tests.rs index cc2d3d5f6f..2e4972c67c 100644 --- a/modules/cdp-engine/src/tests.rs +++ b/modules/cdp-engine/src/tests.rs @@ -23,8 +23,8 @@ use super::*; use frame_support::{assert_noop, assert_ok}; use mock::{Call as MockCall, Event, *}; -use module_fees::PoolPercent; use orml_traits::MultiCurrency; +use primitives::PoolPercent; use sp_core::offchain::{testing, OffchainDbExt, OffchainWorkerExt, TransactionPoolExt}; use sp_io::offchain; use sp_runtime::{ @@ -68,6 +68,14 @@ fn setup_fees_distribution() { rate: Rate::one(), }], )); + assert_ok!(Fees::set_income_fee( + Origin::root(), + IncomeSource::HonzonLiquidationFee, + vec![PoolPercent { + pool: BOB, + rate: Rate::one(), + }], + )); } #[test] @@ -819,6 +827,7 @@ fn remain_debit_value_too_small_check() { #[test] fn liquidate_unsafe_cdp_by_collateral_auction() { ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -831,6 +840,7 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { )); setup_default_collateral(AUSD); assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 100, 500)); + assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 500); @@ -848,8 +858,10 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { Change::NoChange, Change::NoChange, )); - assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); + assert_eq!(CDPTreasuryModule::debit_pool(), 0); + assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); + assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP { collateral_type: BTC, owner: ALICE, @@ -857,7 +869,10 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { bad_debt_value: 50, target_amount: 60, })); - assert_eq!(CDPTreasuryModule::debit_pool(), 50); + // 50 debt + 10 penalty + assert_eq!(CDPTreasuryModule::debit_pool(), 60); + assert_eq!(Currencies::free_balance(AUSD, &BOB), 10); + assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 0); @@ -874,6 +889,7 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { #[test] fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -932,7 +948,7 @@ fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { })); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (100, 121)); - assert_eq!(CDPTreasuryModule::debit_pool(), 50); + assert_eq!(CDPTreasuryModule::debit_pool(), 60); assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 0); @@ -943,6 +959,7 @@ fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { #[test] fn liquidate_unsafe_cdp_by_swap() { ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -992,7 +1009,7 @@ fn liquidate_unsafe_cdp_by_swap() { })); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (199, 61)); - assert_eq!(CDPTreasuryModule::debit_pool(), 50); + assert_eq!(CDPTreasuryModule::debit_pool(), 60); assert_eq!(Currencies::free_balance(BTC, &ALICE), 901); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 0); @@ -1003,6 +1020,7 @@ fn liquidate_unsafe_cdp_by_swap() { #[test] fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_swap_dot() { ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -1082,7 +1100,7 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_swap_dot() { assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).debit, 0); assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).collateral, 0); assert_eq!(Currencies::free_balance(LP_AUSD_DOT, &LoansModule::account_id()), 0); - assert_eq!(CDPTreasuryModule::debit_pool(), 500); + assert_eq!(CDPTreasuryModule::debit_pool(), 600); assert_eq!(Currencies::free_balance(AUSD, &CDPTreasuryModule::account_id()), 600); assert_eq!(Currencies::free_balance(DOT, &CDPTreasuryModule::account_id()), 0); assert_eq!( @@ -1096,6 +1114,7 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_swap_dot() { #[test] fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_ausd_take_whole_target() { ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -1175,7 +1194,7 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_ausd_take_whole_target() { assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).debit, 0); assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).collateral, 0); assert_eq!(Currencies::free_balance(LP_AUSD_DOT, &LoansModule::account_id()), 0); - assert_eq!(CDPTreasuryModule::debit_pool(), 200); + assert_eq!(CDPTreasuryModule::debit_pool(), 240); assert_eq!(Currencies::free_balance(AUSD, &CDPTreasuryModule::account_id()), 240); assert_eq!(Currencies::free_balance(DOT, &CDPTreasuryModule::account_id()), 0); assert_eq!( @@ -1189,6 +1208,7 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_ausd_take_whole_target() { #[test] fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_create_dot_auction() { ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -1268,7 +1288,7 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_create_dot_auction() { assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).debit, 0); assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).collateral, 0); assert_eq!(Currencies::free_balance(LP_AUSD_DOT, &LoansModule::account_id()), 0); - assert_eq!(CDPTreasuryModule::debit_pool(), 500); + assert_eq!(CDPTreasuryModule::debit_pool(), 600); assert_eq!(Currencies::free_balance(AUSD, &CDPTreasuryModule::account_id()), 500); assert_eq!(Currencies::free_balance(DOT, &CDPTreasuryModule::account_id()), 25); assert_eq!( @@ -1644,6 +1664,7 @@ fn offchain_worker_works_cdp() { ext.register_extension(OffchainDbExt::new(offchain)); ext.execute_with(|| { + setup_fees_distribution(); // number of currencies allowed as collateral (cycles through all of them) setup_default_collateral(BTC); setup_default_collateral(LP_AUSD_DOT); @@ -1729,6 +1750,7 @@ fn offchain_worker_iteration_limit_works() { ext.register_extension(OffchainDbExt::new(offchain.clone())); ext.execute_with(|| { + setup_fees_distribution(); System::set_block_number(1); // sets max iterations value to 1 offchain.local_storage_set(StorageKind::PERSISTENT, OFFCHAIN_WORKER_MAX_ITERATIONS, &1u32.encode()); @@ -1950,3 +1972,54 @@ fn accumulated_interest_goes_to_on_fee_deposit() { ); }); } + +#[test] +fn liquidation_fee_goes_to_on_fee_deposit() { + ExtBuilder::default().build().execute_with(|| { + setup_fees_distribution(); + + assert_ok!(CDPEngineModule::set_collateral_params( + Origin::signed(1), + BTC, + Change::NewValue(Some(Rate::zero())), + Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), + Change::NewValue(Some(Rate::one())), + Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), + Change::NewValue(10000), + )); + assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 100, 500)); + + // Alice: -100 collateral. +50 from debit + assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); + assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); + // Bob's initial balance + assert_eq!(Currencies::free_balance(BTC, &BOB), 1000); + assert_eq!(Currencies::free_balance(AUSD, &BOB), 0); + // Treasury had no debt from before + assert_eq!(CDPTreasuryModule::get_debit_pool(), 0); + assert_eq!( + LoansModule::positions(BTC, &ALICE), + Position { + collateral: 100, + debit: 500, + } + ); + MockPriceSource::set_price(BTC, Some(Price::saturating_from_rational(1, 10))); + assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); + + // Treasury Debit: 50 from confiscation and +50 from penalty + assert_eq!(CDPTreasuryModule::get_debit_pool(), 100); + + assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); + assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); + assert_eq!( + LoansModule::positions(BTC, &ALICE), + Position { + collateral: 0, + debit: 0, + } + ); + assert_eq!(Currencies::free_balance(BTC, &BOB), 1000); + assert_eq!(Currencies::free_balance(AUSD, &BOB), 50); + }); +} diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 8064f0ab2d..35ec2f3da8 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -29,7 +29,7 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; -use primitives::{Balance, CurrencyId, IncomeSource}; +use primitives::{Balance, CurrencyId, IncomeSource, PoolPercent}; use sp_runtime::{ traits::{One, Saturating, Zero}, FixedPointNumber, FixedU128, @@ -40,11 +40,8 @@ use support::{DEXManager, OnFeeDeposit, SwapLimit}; mod mock; mod tests; pub mod weights; -pub use weights::WeightInfo; - -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; use sp_runtime::traits::UniqueSaturatedInto; +pub use weights::WeightInfo; pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; @@ -55,13 +52,6 @@ pub type Treasuries = Vec<( Vec<(::AccountId, u32)>, )>; -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct PoolPercent { - pub pool: AccountId, - pub rate: FixedU128, -} - /// helper method to create `PoolPercent` list by tuple. pub fn build_pool_percents(list: Vec<(AccountId, u32)>) -> Vec> { list.iter() diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index b6e547e64e..4dba4f353c 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -38,6 +38,8 @@ use sp_runtime::traits::AccountIdConversion; use support::mocks::MockAddressMapping; pub const ALICE: AccountId = AccountId::new([1u8; 32]); +pub const BOB: AccountId = AccountId::new([2u8; 32]); +pub const CHARLIE: AccountId = AccountId::new([3u8; 32]); pub const AUSD: CurrencyId = CurrencyId::Token(TokenSymbol::AUSD); pub const ACA: CurrencyId = CurrencyId::Token(TokenSymbol::ACA); pub const DOT: CurrencyId = CurrencyId::Token(TokenSymbol::DOT); diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 6833924abb..6693053b1c 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -25,7 +25,8 @@ use crate::mock::*; use frame_support::traits::{ExistenceRequirement, WithdrawReasons}; use frame_support::{assert_noop, assert_ok}; use mock::{Event, ExtBuilder, Origin, Runtime, System}; -use primitives::AccountId; +use primitives::{AccountId, PoolPercent}; +use support::Rate; #[test] fn set_income_fee_works() { @@ -215,6 +216,19 @@ fn on_fee_deposit_works() { .balances(vec![(ALICE, ACA, 10000), (ALICE, DOT, 10000)]) .build() .execute_with(|| { + assert_ok!(Fees::do_set_treasury_rate( + IncomeSource::TxFee, + vec![ + PoolPercent { + pool: NetworkTreasuryPool::get(), + rate: Rate::saturating_from_rational(8, 10) + }, + PoolPercent { + pool: CollatorsRewardPool::get(), + rate: Rate::saturating_from_rational(2, 10) + }, + ] + )); // Native token tests // FeeToTreasuryPool based on pre-configured treasury pool percentage. assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, ACA, 10000)); @@ -406,3 +420,50 @@ fn distribution_incentive_threshold_works() { })); }); } + +#[test] +fn independent_pools_on_fee_deposit_works() { + ExtBuilder::default().build().execute_with(|| { + // Register payout destination for multiple pools + assert_ok!(Fees::do_set_treasury_rate( + IncomeSource::TxFee, + vec![PoolPercent { + pool: ALICE, + rate: Rate::one() + },] + )); + assert_ok!(Fees::do_set_treasury_rate( + IncomeSource::XcmFee, + vec![PoolPercent { + pool: BOB, + rate: Rate::one() + },] + )); + assert_ok!(Fees::do_set_treasury_rate( + IncomeSource::HonzonStabilityFee, + vec![PoolPercent { + pool: CHARLIE, + rate: Rate::one() + },] + )); + + assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, ACA, 1000)); + assert_eq!(Currencies::free_balance(ACA, &ALICE), 1000); + assert_eq!(Currencies::free_balance(ACA, &BOB), 0); + assert_eq!(Currencies::free_balance(ACA, &CHARLIE), 0); + + assert_ok!(Pallet::::on_fee_deposit(IncomeSource::XcmFee, ACA, 1000)); + assert_eq!(Currencies::free_balance(ACA, &ALICE), 1000); + assert_eq!(Currencies::free_balance(ACA, &BOB), 1000); + assert_eq!(Currencies::free_balance(ACA, &CHARLIE), 0); + + assert_ok!(Pallet::::on_fee_deposit( + IncomeSource::HonzonStabilityFee, + ACA, + 1000 + )); + assert_eq!(Currencies::free_balance(ACA, &ALICE), 1000); + assert_eq!(Currencies::free_balance(ACA, &BOB), 1000); + assert_eq!(Currencies::free_balance(ACA, &CHARLIE), 1000); + }); +} diff --git a/modules/homa/src/tests.rs b/modules/homa/src/tests.rs index e2a6c9b1b9..cb47596834 100644 --- a/modules/homa/src/tests.rs +++ b/modules/homa/src/tests.rs @@ -22,8 +22,8 @@ use super::*; use frame_support::{assert_noop, assert_ok}; use mock::{Event, *}; -use module_fees::PoolPercent; use orml_traits::MultiCurrency; +use primitives::PoolPercent; use sp_runtime::{traits::BadOrigin, FixedPointNumber}; fn setup_fees_distribution() { diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 240371fb9e..bc07a43323 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -192,6 +192,13 @@ pub enum ReserveIdentifier { Count, } +pub type CashYieldIndex = u128; + +/// Convert any type that implements Into into byte representation ([u8, 32]) +pub fn to_bytes>(value: T) -> [u8; 32] { + Into::<[u8; 32]>::into(value.into()) +} + #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum IncomeSource { @@ -203,9 +210,9 @@ pub enum IncomeSource { HomaStakingRewardFee, } -pub type CashYieldIndex = u128; - -/// Convert any type that implements Into into byte representation ([u8, 32]) -pub fn to_bytes>(value: T) -> [u8; 32] { - Into::<[u8; 32]>::into(value.into()) +#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub struct PoolPercent { + pub pool: AccountId, + pub rate: FixedU128, } diff --git a/runtime/integration-tests/src/honzon.rs b/runtime/integration-tests/src/honzon.rs index 8a6a1e9021..37a0b97023 100644 --- a/runtime/integration-tests/src/honzon.rs +++ b/runtime/integration-tests/src/honzon.rs @@ -17,8 +17,7 @@ // along with this program. If not, see . use crate::setup::*; -use module_fees::PoolPercent; -use primitives::IncomeSource; +use primitives::{IncomeSource, PoolPercent}; use sp_runtime::traits::One; fn setup_default_collateral(currency_id: CurrencyId) { @@ -42,6 +41,14 @@ fn setup_fees_distribution() { rate: Rate::one(), }], )); + assert_ok!(Fees::set_income_fee( + Origin::root(), + IncomeSource::HonzonLiquidationFee, + vec![PoolPercent { + pool: CdpTreasury::account_id(), + rate: Rate::one(), + }], + )); } #[test] @@ -143,6 +150,7 @@ fn liquidate_cdp() { .build() .execute_with(|| { set_oracle_price(vec![(RELAY_CHAIN_CURRENCY, Price::saturating_from_rational(10000, 1))]); // 10000 usd + setup_fees_distribution(); assert_ok!(Dex::add_liquidity( Origin::signed(AccountId::from(BOB)), @@ -229,7 +237,8 @@ fn liquidate_cdp() { 0 ); assert!(AuctionManager::collateral_auctions(0).is_some()); - assert_eq!(CdpTreasury::debit_pool(), 250_000 * dollar(USD_CURRENCY)); + // 250_000 debit + (20%) 50_000 penalty + assert_eq!(CdpTreasury::debit_pool(), 300_000 * dollar(USD_CURRENCY)); assert_ok!(CdpEngine::liquidate_unsafe_cdp( AccountId::from(BOB), @@ -254,7 +263,8 @@ fn liquidate_cdp() { Loans::positions(RELAY_CHAIN_CURRENCY, AccountId::from(BOB)).collateral, 0 ); - assert_eq!(CdpTreasury::debit_pool(), 255_000 * dollar(USD_CURRENCY)); + // 300_000 + 5000 debit + (20%) 1000 penalty + assert_eq!(CdpTreasury::debit_pool(), 306_000 * dollar(USD_CURRENCY)); assert!(CdpTreasury::surplus_pool() >= 5_000 * dollar(USD_CURRENCY)); }); } @@ -270,7 +280,7 @@ fn test_honzon_module() { .build() .execute_with(|| { set_oracle_price(vec![(RELAY_CHAIN_CURRENCY, Price::saturating_from_rational(1, 1))]); - + setup_fees_distribution(); assert_ok!(CdpEngine::set_collateral_params( Origin::root(), RELAY_CHAIN_CURRENCY, diff --git a/runtime/mandala/src/benchmarking/cdp_engine.rs b/runtime/mandala/src/benchmarking/cdp_engine.rs index 6c4559a6b7..48e174b4ea 100644 --- a/runtime/mandala/src/benchmarking/cdp_engine.rs +++ b/runtime/mandala/src/benchmarking/cdp_engine.rs @@ -18,7 +18,7 @@ use crate::{ AccountId, Address, Amount, Balance, CdpEngine, CdpTreasury, CurrencyId, DefaultDebitExchangeRate, Dex, - EmergencyShutdown, ExistentialDeposits, GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, + EmergencyShutdown, ExistentialDeposits, Fees, GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, GetStakingCurrencyId, MinimumDebitValue, NativeTokenExistentialDeposit, Price, Rate, Ratio, Runtime, Timestamp, MILLISECS_PER_BLOCK, }; @@ -33,6 +33,7 @@ use frame_system::RawOrigin; use module_support::DEXManager; use orml_benchmarking::runtime_benchmarks; use orml_traits::{Change, GetByKey}; +use primitives::{IncomeSource, PoolPercent}; use sp_runtime::{ traits::{AccountIdLookup, One, StaticLookup, UniqueSaturatedInto}, FixedPointNumber, @@ -156,6 +157,15 @@ runtime_benchmarks! { let collateral_value = 2 * min_debit_value; let collateral_amount = Price::saturating_from_rational(dollar(STAKING), dollar(STABLECOIN)).saturating_mul_int(collateral_value); + let _ = Fees::set_income_fee( + RawOrigin::Root.into(), + IncomeSource::HonzonLiquidationFee, + vec![PoolPercent { + pool: owner.clone(), + rate: Rate::one(), + }], + ); + // set balance set_balance(STAKING, &owner, collateral_amount + ExistentialDeposits::get(&STAKING)); @@ -204,6 +214,15 @@ runtime_benchmarks! { let collateral_amount = Price::saturating_from_rational(dollar(LIQUID), dollar(STABLECOIN)).saturating_mul_int(collateral_value); let collateral_price = Price::one(); // 1 USD + let _ = Fees::set_income_fee( + RawOrigin::Root.into(), + IncomeSource::HonzonLiquidationFee, + vec![PoolPercent { + pool: owner.clone(), + rate: Rate::one(), + }], + ); + set_balance(LIQUID, &owner, (10 * collateral_amount) + ExistentialDeposits::get(&LIQUID)); inject_liquidity(funder.clone(), LIQUID, STAKING, 10_000 * dollar(LIQUID), 10_000 * dollar(STAKING))?; inject_liquidity(funder, STAKING, STABLECOIN, 10_000 * dollar(STAKING), 10_000 * dollar(STABLECOIN))?; diff --git a/runtime/mandala/src/benchmarking/fees.rs b/runtime/mandala/src/benchmarking/fees.rs index b98491dd83..a2c6f48018 100644 --- a/runtime/mandala/src/benchmarking/fees.rs +++ b/runtime/mandala/src/benchmarking/fees.rs @@ -18,10 +18,9 @@ use crate::{Event, Fees, GetNativeCurrencyId, Origin, Runtime, System}; use frame_system::RawOrigin; -use module_fees::PoolPercent; use module_support::OnFeeDeposit; use orml_benchmarking::runtime_benchmarks; -use primitives::{AccountId, Balance, CurrencyId, IncomeSource}; +use primitives::{AccountId, Balance, CurrencyId, IncomeSource, PoolPercent}; use sp_runtime::{FixedPointNumber, FixedU128}; use sp_std::prelude::*; From d5707e56c9673a0108bcb072b355a6577f97f80d Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Mon, 4 Jul 2022 09:45:06 +1200 Subject: [PATCH 49/49] Revert "Liquidation penalty now goes to OnFeeDeposit, and the same amount of debit is added to the Treasury. When liquidation is complete, the debit should be fully paid off." This reverts commit d0e6454f95f8e4897e495e9f4011c516a6cfd889. --- modules/cdp-engine/src/lib.rs | 8 +- modules/cdp-engine/src/tests.rs | 89 ++----------------- modules/fees/src/lib.rs | 14 ++- modules/fees/src/mock.rs | 2 - modules/fees/src/tests.rs | 63 +------------ modules/homa/src/tests.rs | 2 +- primitives/src/lib.rs | 17 ++-- runtime/integration-tests/src/honzon.rs | 20 ++--- .../mandala/src/benchmarking/cdp_engine.rs | 21 +---- runtime/mandala/src/benchmarking/fees.rs | 3 +- 10 files changed, 36 insertions(+), 203 deletions(-) diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 5d7f302c37..14f9e09e16 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -1155,13 +1155,6 @@ impl Pallet { let liquidation_penalty = Self::get_liquidation_penalty(currency_id)?; let target_stable_amount = liquidation_penalty.saturating_mul_acc_int(bad_debt_value); - let debt_penalty = liquidation_penalty.saturating_mul_int(bad_debt_value); - let stable_currency_id = T::GetStableCurrencyId::get(); - - // Deposit penalty to OnFeeDeposit and add the debt to the treasury. - T::OnFeeDeposit::on_fee_deposit(IncomeSource::HonzonLiquidationFee, stable_currency_id, debt_penalty)?; - ::CDPTreasury::on_system_debit(debt_penalty)?; - match currency_id { CurrencyId::DexShare(dex_share_0, dex_share_1) => { let token_0: CurrencyId = dex_share_0.into(); @@ -1172,6 +1165,7 @@ impl Pallet { ::CDPTreasury::remove_liquidity_for_lp_collateral(currency_id, collateral)?; // if these's stable + let stable_currency_id = T::GetStableCurrencyId::get(); if token_0 == stable_currency_id || token_1 == stable_currency_id { let (existing_stable, need_handle_currency, handle_amount) = if token_0 == stable_currency_id { (amount_0, token_1, amount_1) diff --git a/modules/cdp-engine/src/tests.rs b/modules/cdp-engine/src/tests.rs index 2e4972c67c..cc2d3d5f6f 100644 --- a/modules/cdp-engine/src/tests.rs +++ b/modules/cdp-engine/src/tests.rs @@ -23,8 +23,8 @@ use super::*; use frame_support::{assert_noop, assert_ok}; use mock::{Call as MockCall, Event, *}; +use module_fees::PoolPercent; use orml_traits::MultiCurrency; -use primitives::PoolPercent; use sp_core::offchain::{testing, OffchainDbExt, OffchainWorkerExt, TransactionPoolExt}; use sp_io::offchain; use sp_runtime::{ @@ -68,14 +68,6 @@ fn setup_fees_distribution() { rate: Rate::one(), }], )); - assert_ok!(Fees::set_income_fee( - Origin::root(), - IncomeSource::HonzonLiquidationFee, - vec![PoolPercent { - pool: BOB, - rate: Rate::one(), - }], - )); } #[test] @@ -827,7 +819,6 @@ fn remain_debit_value_too_small_check() { #[test] fn liquidate_unsafe_cdp_by_collateral_auction() { ExtBuilder::default().build().execute_with(|| { - setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -840,7 +831,6 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { )); setup_default_collateral(AUSD); assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 100, 500)); - assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 500); @@ -858,10 +848,8 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { Change::NoChange, Change::NoChange, )); - - assert_eq!(CDPTreasuryModule::debit_pool(), 0); - assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); + System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP { collateral_type: BTC, owner: ALICE, @@ -869,10 +857,7 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { bad_debt_value: 50, target_amount: 60, })); - // 50 debt + 10 penalty - assert_eq!(CDPTreasuryModule::debit_pool(), 60); - assert_eq!(Currencies::free_balance(AUSD, &BOB), 10); - + assert_eq!(CDPTreasuryModule::debit_pool(), 50); assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 0); @@ -889,7 +874,6 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { #[test] fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { ExtBuilder::default().build().execute_with(|| { - setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -948,7 +932,7 @@ fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { })); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (100, 121)); - assert_eq!(CDPTreasuryModule::debit_pool(), 60); + assert_eq!(CDPTreasuryModule::debit_pool(), 50); assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 0); @@ -959,7 +943,6 @@ fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { #[test] fn liquidate_unsafe_cdp_by_swap() { ExtBuilder::default().build().execute_with(|| { - setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -1009,7 +992,7 @@ fn liquidate_unsafe_cdp_by_swap() { })); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (199, 61)); - assert_eq!(CDPTreasuryModule::debit_pool(), 60); + assert_eq!(CDPTreasuryModule::debit_pool(), 50); assert_eq!(Currencies::free_balance(BTC, &ALICE), 901); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 0); @@ -1020,7 +1003,6 @@ fn liquidate_unsafe_cdp_by_swap() { #[test] fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_swap_dot() { ExtBuilder::default().build().execute_with(|| { - setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -1100,7 +1082,7 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_swap_dot() { assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).debit, 0); assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).collateral, 0); assert_eq!(Currencies::free_balance(LP_AUSD_DOT, &LoansModule::account_id()), 0); - assert_eq!(CDPTreasuryModule::debit_pool(), 600); + assert_eq!(CDPTreasuryModule::debit_pool(), 500); assert_eq!(Currencies::free_balance(AUSD, &CDPTreasuryModule::account_id()), 600); assert_eq!(Currencies::free_balance(DOT, &CDPTreasuryModule::account_id()), 0); assert_eq!( @@ -1114,7 +1096,6 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_swap_dot() { #[test] fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_ausd_take_whole_target() { ExtBuilder::default().build().execute_with(|| { - setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -1194,7 +1175,7 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_ausd_take_whole_target() { assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).debit, 0); assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).collateral, 0); assert_eq!(Currencies::free_balance(LP_AUSD_DOT, &LoansModule::account_id()), 0); - assert_eq!(CDPTreasuryModule::debit_pool(), 240); + assert_eq!(CDPTreasuryModule::debit_pool(), 200); assert_eq!(Currencies::free_balance(AUSD, &CDPTreasuryModule::account_id()), 240); assert_eq!(Currencies::free_balance(DOT, &CDPTreasuryModule::account_id()), 0); assert_eq!( @@ -1208,7 +1189,6 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_ausd_take_whole_target() { #[test] fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_create_dot_auction() { ExtBuilder::default().build().execute_with(|| { - setup_fees_distribution(); System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -1288,7 +1268,7 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_create_dot_auction() { assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).debit, 0); assert_eq!(LoansModule::positions(LP_AUSD_DOT, ALICE).collateral, 0); assert_eq!(Currencies::free_balance(LP_AUSD_DOT, &LoansModule::account_id()), 0); - assert_eq!(CDPTreasuryModule::debit_pool(), 600); + assert_eq!(CDPTreasuryModule::debit_pool(), 500); assert_eq!(Currencies::free_balance(AUSD, &CDPTreasuryModule::account_id()), 500); assert_eq!(Currencies::free_balance(DOT, &CDPTreasuryModule::account_id()), 25); assert_eq!( @@ -1664,7 +1644,6 @@ fn offchain_worker_works_cdp() { ext.register_extension(OffchainDbExt::new(offchain)); ext.execute_with(|| { - setup_fees_distribution(); // number of currencies allowed as collateral (cycles through all of them) setup_default_collateral(BTC); setup_default_collateral(LP_AUSD_DOT); @@ -1750,7 +1729,6 @@ fn offchain_worker_iteration_limit_works() { ext.register_extension(OffchainDbExt::new(offchain.clone())); ext.execute_with(|| { - setup_fees_distribution(); System::set_block_number(1); // sets max iterations value to 1 offchain.local_storage_set(StorageKind::PERSISTENT, OFFCHAIN_WORKER_MAX_ITERATIONS, &1u32.encode()); @@ -1972,54 +1950,3 @@ fn accumulated_interest_goes_to_on_fee_deposit() { ); }); } - -#[test] -fn liquidation_fee_goes_to_on_fee_deposit() { - ExtBuilder::default().build().execute_with(|| { - setup_fees_distribution(); - - assert_ok!(CDPEngineModule::set_collateral_params( - Origin::signed(1), - BTC, - Change::NewValue(Some(Rate::zero())), - Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), - Change::NewValue(Some(Rate::one())), - Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), - Change::NewValue(10000), - )); - assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 100, 500)); - - // Alice: -100 collateral. +50 from debit - assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); - assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); - // Bob's initial balance - assert_eq!(Currencies::free_balance(BTC, &BOB), 1000); - assert_eq!(Currencies::free_balance(AUSD, &BOB), 0); - // Treasury had no debt from before - assert_eq!(CDPTreasuryModule::get_debit_pool(), 0); - assert_eq!( - LoansModule::positions(BTC, &ALICE), - Position { - collateral: 100, - debit: 500, - } - ); - MockPriceSource::set_price(BTC, Some(Price::saturating_from_rational(1, 10))); - assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); - - // Treasury Debit: 50 from confiscation and +50 from penalty - assert_eq!(CDPTreasuryModule::get_debit_pool(), 100); - - assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); - assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); - assert_eq!( - LoansModule::positions(BTC, &ALICE), - Position { - collateral: 0, - debit: 0, - } - ); - assert_eq!(Currencies::free_balance(BTC, &BOB), 1000); - assert_eq!(Currencies::free_balance(AUSD, &BOB), 50); - }); -} diff --git a/modules/fees/src/lib.rs b/modules/fees/src/lib.rs index 35ec2f3da8..8064f0ab2d 100644 --- a/modules/fees/src/lib.rs +++ b/modules/fees/src/lib.rs @@ -29,7 +29,7 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; -use primitives::{Balance, CurrencyId, IncomeSource, PoolPercent}; +use primitives::{Balance, CurrencyId, IncomeSource}; use sp_runtime::{ traits::{One, Saturating, Zero}, FixedPointNumber, FixedU128, @@ -40,9 +40,12 @@ use support::{DEXManager, OnFeeDeposit, SwapLimit}; mod mock; mod tests; pub mod weights; -use sp_runtime::traits::UniqueSaturatedInto; pub use weights::WeightInfo; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; +use sp_runtime::traits::UniqueSaturatedInto; + pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; pub type Incomes = Vec<(IncomeSource, Vec<(::AccountId, u32)>)>; @@ -52,6 +55,13 @@ pub type Treasuries = Vec<( Vec<(::AccountId, u32)>, )>; +#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub struct PoolPercent { + pub pool: AccountId, + pub rate: FixedU128, +} + /// helper method to create `PoolPercent` list by tuple. pub fn build_pool_percents(list: Vec<(AccountId, u32)>) -> Vec> { list.iter() diff --git a/modules/fees/src/mock.rs b/modules/fees/src/mock.rs index 4dba4f353c..b6e547e64e 100644 --- a/modules/fees/src/mock.rs +++ b/modules/fees/src/mock.rs @@ -38,8 +38,6 @@ use sp_runtime::traits::AccountIdConversion; use support::mocks::MockAddressMapping; pub const ALICE: AccountId = AccountId::new([1u8; 32]); -pub const BOB: AccountId = AccountId::new([2u8; 32]); -pub const CHARLIE: AccountId = AccountId::new([3u8; 32]); pub const AUSD: CurrencyId = CurrencyId::Token(TokenSymbol::AUSD); pub const ACA: CurrencyId = CurrencyId::Token(TokenSymbol::ACA); pub const DOT: CurrencyId = CurrencyId::Token(TokenSymbol::DOT); diff --git a/modules/fees/src/tests.rs b/modules/fees/src/tests.rs index 6693053b1c..6833924abb 100644 --- a/modules/fees/src/tests.rs +++ b/modules/fees/src/tests.rs @@ -25,8 +25,7 @@ use crate::mock::*; use frame_support::traits::{ExistenceRequirement, WithdrawReasons}; use frame_support::{assert_noop, assert_ok}; use mock::{Event, ExtBuilder, Origin, Runtime, System}; -use primitives::{AccountId, PoolPercent}; -use support::Rate; +use primitives::AccountId; #[test] fn set_income_fee_works() { @@ -216,19 +215,6 @@ fn on_fee_deposit_works() { .balances(vec![(ALICE, ACA, 10000), (ALICE, DOT, 10000)]) .build() .execute_with(|| { - assert_ok!(Fees::do_set_treasury_rate( - IncomeSource::TxFee, - vec![ - PoolPercent { - pool: NetworkTreasuryPool::get(), - rate: Rate::saturating_from_rational(8, 10) - }, - PoolPercent { - pool: CollatorsRewardPool::get(), - rate: Rate::saturating_from_rational(2, 10) - }, - ] - )); // Native token tests // FeeToTreasuryPool based on pre-configured treasury pool percentage. assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, ACA, 10000)); @@ -420,50 +406,3 @@ fn distribution_incentive_threshold_works() { })); }); } - -#[test] -fn independent_pools_on_fee_deposit_works() { - ExtBuilder::default().build().execute_with(|| { - // Register payout destination for multiple pools - assert_ok!(Fees::do_set_treasury_rate( - IncomeSource::TxFee, - vec![PoolPercent { - pool: ALICE, - rate: Rate::one() - },] - )); - assert_ok!(Fees::do_set_treasury_rate( - IncomeSource::XcmFee, - vec![PoolPercent { - pool: BOB, - rate: Rate::one() - },] - )); - assert_ok!(Fees::do_set_treasury_rate( - IncomeSource::HonzonStabilityFee, - vec![PoolPercent { - pool: CHARLIE, - rate: Rate::one() - },] - )); - - assert_ok!(Pallet::::on_fee_deposit(IncomeSource::TxFee, ACA, 1000)); - assert_eq!(Currencies::free_balance(ACA, &ALICE), 1000); - assert_eq!(Currencies::free_balance(ACA, &BOB), 0); - assert_eq!(Currencies::free_balance(ACA, &CHARLIE), 0); - - assert_ok!(Pallet::::on_fee_deposit(IncomeSource::XcmFee, ACA, 1000)); - assert_eq!(Currencies::free_balance(ACA, &ALICE), 1000); - assert_eq!(Currencies::free_balance(ACA, &BOB), 1000); - assert_eq!(Currencies::free_balance(ACA, &CHARLIE), 0); - - assert_ok!(Pallet::::on_fee_deposit( - IncomeSource::HonzonStabilityFee, - ACA, - 1000 - )); - assert_eq!(Currencies::free_balance(ACA, &ALICE), 1000); - assert_eq!(Currencies::free_balance(ACA, &BOB), 1000); - assert_eq!(Currencies::free_balance(ACA, &CHARLIE), 1000); - }); -} diff --git a/modules/homa/src/tests.rs b/modules/homa/src/tests.rs index cb47596834..e2a6c9b1b9 100644 --- a/modules/homa/src/tests.rs +++ b/modules/homa/src/tests.rs @@ -22,8 +22,8 @@ use super::*; use frame_support::{assert_noop, assert_ok}; use mock::{Event, *}; +use module_fees::PoolPercent; use orml_traits::MultiCurrency; -use primitives::PoolPercent; use sp_runtime::{traits::BadOrigin, FixedPointNumber}; fn setup_fees_distribution() { diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index bc07a43323..240371fb9e 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -192,13 +192,6 @@ pub enum ReserveIdentifier { Count, } -pub type CashYieldIndex = u128; - -/// Convert any type that implements Into into byte representation ([u8, 32]) -pub fn to_bytes>(value: T) -> [u8; 32] { - Into::<[u8; 32]>::into(value.into()) -} - #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum IncomeSource { @@ -210,9 +203,9 @@ pub enum IncomeSource { HomaStakingRewardFee, } -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct PoolPercent { - pub pool: AccountId, - pub rate: FixedU128, +pub type CashYieldIndex = u128; + +/// Convert any type that implements Into into byte representation ([u8, 32]) +pub fn to_bytes>(value: T) -> [u8; 32] { + Into::<[u8; 32]>::into(value.into()) } diff --git a/runtime/integration-tests/src/honzon.rs b/runtime/integration-tests/src/honzon.rs index 37a0b97023..8a6a1e9021 100644 --- a/runtime/integration-tests/src/honzon.rs +++ b/runtime/integration-tests/src/honzon.rs @@ -17,7 +17,8 @@ // along with this program. If not, see . use crate::setup::*; -use primitives::{IncomeSource, PoolPercent}; +use module_fees::PoolPercent; +use primitives::IncomeSource; use sp_runtime::traits::One; fn setup_default_collateral(currency_id: CurrencyId) { @@ -41,14 +42,6 @@ fn setup_fees_distribution() { rate: Rate::one(), }], )); - assert_ok!(Fees::set_income_fee( - Origin::root(), - IncomeSource::HonzonLiquidationFee, - vec![PoolPercent { - pool: CdpTreasury::account_id(), - rate: Rate::one(), - }], - )); } #[test] @@ -150,7 +143,6 @@ fn liquidate_cdp() { .build() .execute_with(|| { set_oracle_price(vec![(RELAY_CHAIN_CURRENCY, Price::saturating_from_rational(10000, 1))]); // 10000 usd - setup_fees_distribution(); assert_ok!(Dex::add_liquidity( Origin::signed(AccountId::from(BOB)), @@ -237,8 +229,7 @@ fn liquidate_cdp() { 0 ); assert!(AuctionManager::collateral_auctions(0).is_some()); - // 250_000 debit + (20%) 50_000 penalty - assert_eq!(CdpTreasury::debit_pool(), 300_000 * dollar(USD_CURRENCY)); + assert_eq!(CdpTreasury::debit_pool(), 250_000 * dollar(USD_CURRENCY)); assert_ok!(CdpEngine::liquidate_unsafe_cdp( AccountId::from(BOB), @@ -263,8 +254,7 @@ fn liquidate_cdp() { Loans::positions(RELAY_CHAIN_CURRENCY, AccountId::from(BOB)).collateral, 0 ); - // 300_000 + 5000 debit + (20%) 1000 penalty - assert_eq!(CdpTreasury::debit_pool(), 306_000 * dollar(USD_CURRENCY)); + assert_eq!(CdpTreasury::debit_pool(), 255_000 * dollar(USD_CURRENCY)); assert!(CdpTreasury::surplus_pool() >= 5_000 * dollar(USD_CURRENCY)); }); } @@ -280,7 +270,7 @@ fn test_honzon_module() { .build() .execute_with(|| { set_oracle_price(vec![(RELAY_CHAIN_CURRENCY, Price::saturating_from_rational(1, 1))]); - setup_fees_distribution(); + assert_ok!(CdpEngine::set_collateral_params( Origin::root(), RELAY_CHAIN_CURRENCY, diff --git a/runtime/mandala/src/benchmarking/cdp_engine.rs b/runtime/mandala/src/benchmarking/cdp_engine.rs index 48e174b4ea..6c4559a6b7 100644 --- a/runtime/mandala/src/benchmarking/cdp_engine.rs +++ b/runtime/mandala/src/benchmarking/cdp_engine.rs @@ -18,7 +18,7 @@ use crate::{ AccountId, Address, Amount, Balance, CdpEngine, CdpTreasury, CurrencyId, DefaultDebitExchangeRate, Dex, - EmergencyShutdown, ExistentialDeposits, Fees, GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, + EmergencyShutdown, ExistentialDeposits, GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, GetStakingCurrencyId, MinimumDebitValue, NativeTokenExistentialDeposit, Price, Rate, Ratio, Runtime, Timestamp, MILLISECS_PER_BLOCK, }; @@ -33,7 +33,6 @@ use frame_system::RawOrigin; use module_support::DEXManager; use orml_benchmarking::runtime_benchmarks; use orml_traits::{Change, GetByKey}; -use primitives::{IncomeSource, PoolPercent}; use sp_runtime::{ traits::{AccountIdLookup, One, StaticLookup, UniqueSaturatedInto}, FixedPointNumber, @@ -157,15 +156,6 @@ runtime_benchmarks! { let collateral_value = 2 * min_debit_value; let collateral_amount = Price::saturating_from_rational(dollar(STAKING), dollar(STABLECOIN)).saturating_mul_int(collateral_value); - let _ = Fees::set_income_fee( - RawOrigin::Root.into(), - IncomeSource::HonzonLiquidationFee, - vec![PoolPercent { - pool: owner.clone(), - rate: Rate::one(), - }], - ); - // set balance set_balance(STAKING, &owner, collateral_amount + ExistentialDeposits::get(&STAKING)); @@ -214,15 +204,6 @@ runtime_benchmarks! { let collateral_amount = Price::saturating_from_rational(dollar(LIQUID), dollar(STABLECOIN)).saturating_mul_int(collateral_value); let collateral_price = Price::one(); // 1 USD - let _ = Fees::set_income_fee( - RawOrigin::Root.into(), - IncomeSource::HonzonLiquidationFee, - vec![PoolPercent { - pool: owner.clone(), - rate: Rate::one(), - }], - ); - set_balance(LIQUID, &owner, (10 * collateral_amount) + ExistentialDeposits::get(&LIQUID)); inject_liquidity(funder.clone(), LIQUID, STAKING, 10_000 * dollar(LIQUID), 10_000 * dollar(STAKING))?; inject_liquidity(funder, STAKING, STABLECOIN, 10_000 * dollar(STAKING), 10_000 * dollar(STABLECOIN))?; diff --git a/runtime/mandala/src/benchmarking/fees.rs b/runtime/mandala/src/benchmarking/fees.rs index a2c6f48018..b98491dd83 100644 --- a/runtime/mandala/src/benchmarking/fees.rs +++ b/runtime/mandala/src/benchmarking/fees.rs @@ -18,9 +18,10 @@ use crate::{Event, Fees, GetNativeCurrencyId, Origin, Runtime, System}; use frame_system::RawOrigin; +use module_fees::PoolPercent; use module_support::OnFeeDeposit; use orml_benchmarking::runtime_benchmarks; -use primitives::{AccountId, Balance, CurrencyId, IncomeSource, PoolPercent}; +use primitives::{AccountId, Balance, CurrencyId, IncomeSource}; use sp_runtime::{FixedPointNumber, FixedU128}; use sp_std::prelude::*;