From 9da1d45b22d87fb194158b0de6e21fdf30f4337e Mon Sep 17 00:00:00 2001 From: wangjj9219 <183318287@qq.com> Date: Thu, 16 Dec 2021 00:32:35 +0800 Subject: [PATCH 01/10] optimize internal swap --- modules/auction-manager/src/lib.rs | 144 ++++++--------- modules/auction-manager/src/mock.rs | 10 +- modules/auction-manager/src/tests.rs | 21 ++- modules/cdp-engine/src/lib.rs | 99 +++-------- modules/cdp-engine/src/mock.rs | 9 +- modules/cdp-engine/src/tests.rs | 27 +-- modules/cdp-treasury/src/lib.rs | 83 +++------ modules/cdp-treasury/src/mock.rs | 6 + modules/cdp-treasury/src/tests.rs | 145 +++------------ modules/dex/src/lib.rs | 97 +++++++--- modules/dex/src/tests.rs | 167 +++++++++++++++++- modules/emergency-shutdown/src/mock.rs | 2 + modules/honzon/src/lib.rs | 17 +- modules/honzon/src/mock.rs | 8 +- modules/honzon/src/tests.rs | 3 +- modules/honzon/src/weights.rs | 25 +-- modules/incentives/src/mock.rs | 27 ++- modules/loans/src/mock.rs | 2 + modules/prices/src/mock.rs | 31 ++-- modules/support/src/lib.rs | 72 ++++---- modules/transaction-payment/src/lib.rs | 12 +- modules/transaction-payment/src/tests.rs | 10 +- runtime/acala/src/lib.rs | 12 +- runtime/acala/src/weights/module_honzon.rs | 11 +- runtime/common/src/precompile/dex.rs | 16 +- runtime/integration-tests/src/honzon.rs | 1 - runtime/karura/src/lib.rs | 12 +- runtime/karura/src/weights/module_honzon.rs | 11 +- .../mandala/src/benchmarking/cdp_engine.rs | 16 +- runtime/mandala/src/benchmarking/honzon.rs | 80 +-------- runtime/mandala/src/lib.rs | 8 +- runtime/mandala/src/weights/module_honzon.rs | 11 +- 32 files changed, 530 insertions(+), 665 deletions(-) diff --git a/modules/auction-manager/src/lib.rs b/modules/auction-manager/src/lib.rs index b783e65651..5b71c52fa8 100644 --- a/modules/auction-manager/src/lib.rs +++ b/modules/auction-manager/src/lib.rs @@ -51,7 +51,7 @@ use sp_runtime::{ DispatchError, DispatchResult, FixedPointNumber, RuntimeDebug, }; use sp_std::prelude::*; -use support::{AuctionManager, CDPTreasury, CDPTreasuryExtended, DEXManager, EmergencyShutdown, PriceProvider, Rate}; +use support::{AuctionManager, CDPTreasury, CDPTreasuryExtended, EmergencyShutdown, PriceProvider, Rate, SwapLimit}; mod mock; mod tests; @@ -158,9 +158,6 @@ pub mod module { /// CDP treasury to escrow assets related to auction type CDPTreasury: CDPTreasuryExtended; - /// DEX to get exchange info - type DEX: DEXManager; - /// The price source of currencies type PriceSource: PriceProvider; @@ -174,12 +171,6 @@ pub mod module { /// Emergency shutdown. type EmergencyShutdown: EmergencyShutdown; - /// The default parital path list for DEX to directly take auction, - /// Note: the path is parital, the whole swap path is collateral currency id concat - /// the partial path. And the list is sorted, DEX try to take auction by order. - #[pallet::constant] - type DefaultSwapParitalPathList: Get>>; - /// Weight information for the extrinsics in this module. type WeightInfo: WeightInfo; } @@ -263,12 +254,6 @@ pub mod module { } } } - - fn integrity_test() { - assert!(T::DefaultSwapParitalPathList::get() - .iter() - .all(|path| !path.is_empty() && path[path.len() - 1] == T::GetStableCurrencyId::get())); - } } #[pallet::call] @@ -597,85 +582,58 @@ impl Pallet { // if bid_price doesn't reach target, DEX will try trading with DEX to get better result. if !collateral_auction.in_reverse_stage(bid_price) { - let default_swap_parital_path_list: Vec> = T::DefaultSwapParitalPathList::get(); - - // iterator default_swap_parital_path_list to try swap until swap succeed. - for partial_path in default_swap_parital_path_list { - let partial_path_len = partial_path.len(); - - // check collateral currency_id and partial_path can form a valid swap path. - if partial_path_len > 0 && collateral_auction.currency_id != partial_path[0] { - let mut swap_path = vec![collateral_auction.currency_id]; - swap_path.extend(partial_path); - - // DEX must take a higher bid. - if bid_price - < T::DEX::get_swap_target_amount(&swap_path, collateral_auction.amount).unwrap_or_default() - { - // try swap collateral in auction with DEX to get stable. - if let Ok(stable_amount) = T::CDPTreasury::swap_exact_collateral_to_stable( - collateral_auction.currency_id, - collateral_auction.amount, - Zero::zero(), - &swap_path, - true, - ) { - // swap successfully, will not deal. - should_deal = false; - - // refund stable currency to the last bidder, it shouldn't fail and affect the - // process. but even it failed, just the winner did not get the bid price. it - // can be fixed by treasury council. - if let Some(bidder) = maybe_bidder.as_ref() { - let res = T::CDPTreasury::issue_debit(bidder, bid_price, false); - if let Err(e) = res { - log::warn!( - target: "auction-manager", - "issue_debit: failed to issue stable {:?} to {:?}: {:?}. \ - This is unexpected but should be safe", - bid_price, bidder, e - ); - debug_assert!(false); - } - } - - // DEX bid is higher than the target amount of auction, - // need refund extra stable currency to recipient. - if collateral_auction.in_reverse_stage(stable_amount) { - let refund_amount = stable_amount - .checked_sub(collateral_auction.target) - .expect("ensured stable_amount > target; qed"); - // it shouldn't fail and affect the process. - // but even it failed, just the winner did not get the refund amount. it can be - // fixed by treasury council. - let res = T::CDPTreasury::issue_debit( - &collateral_auction.refund_recipient, - refund_amount, - false, - ); - if let Err(e) = res { - log::warn!( - target: "auction-manager", - "issue_debit: failed to issue stable {:?} to {:?}: {:?}. \ - This is unexpected but should be safe", - refund_amount, collateral_auction.refund_recipient, e - ); - debug_assert!(false); - } - } - - Self::deposit_event(Event::DEXTakeCollateralAuction( - auction_id, - collateral_auction.currency_id, - collateral_auction.amount, - stable_amount, - )); - - // break loop. - break; - } + // try swap collateral in auction with DEX to get stable at least bid_price. + if let Ok((_, stable_amount)) = T::CDPTreasury::swap_collateral_to_stable( + collateral_auction.currency_id, + SwapLimit::ExactSupply(collateral_auction.amount, bid_price), + true, + ) { + // swap successfully, will not deal. + should_deal = false; + + // refund stable currency to the last bidder, it shouldn't fail and affect the + // process. but even it failed, just the winner did not get the bid price. it + // can be fixed by treasury council. + if let Some(bidder) = maybe_bidder.as_ref() { + let res = T::CDPTreasury::issue_debit(bidder, bid_price, false); + if let Err(e) = res { + log::warn!( + target: "auction-manager", + "issue_debit: failed to issue stable {:?} to {:?}: {:?}. \ + This is unexpected but should be safe", + bid_price, bidder, e + ); + debug_assert!(false); + } + } + + // DEX bid is higher than the target amount of auction, + // need refund extra stable currency to recipient. + if collateral_auction.in_reverse_stage(stable_amount) { + let refund_amount = stable_amount + .checked_sub(collateral_auction.target) + .expect("ensured stable_amount > target; qed"); + // it shouldn't fail and affect the process. + // but even it failed, just the winner did not get the refund amount. it can be + // fixed by treasury council. + let res = T::CDPTreasury::issue_debit(&collateral_auction.refund_recipient, refund_amount, false); + if let Err(e) = res { + log::warn!( + target: "auction-manager", + "issue_debit: failed to issue stable {:?} to {:?}: {:?}. \ + This is unexpected but should be safe", + refund_amount, collateral_auction.refund_recipient, e + ); + debug_assert!(false); } } + + Self::deposit_event(Event::DEXTakeCollateralAuction( + auction_id, + collateral_auction.currency_id, + collateral_auction.amount, + stable_amount, + )); } } diff --git a/modules/auction-manager/src/mock.rs b/modules/auction-manager/src/mock.rs index a59d8509a9..0208bb8568 100644 --- a/modules/auction-manager/src/mock.rs +++ b/modules/auction-manager/src/mock.rs @@ -118,6 +118,9 @@ parameter_types! { pub const MaxAuctionsCount: u32 = 10_000; pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub TreasuryAccount: AccountId = PalletId(*b"aca/hztr").into_account(); + pub AlternativeSwapPathJointList: Vec> = vec![ + vec![DOT], + ]; } impl cdp_treasury::Config for Runtime { @@ -130,6 +133,7 @@ impl cdp_treasury::Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = TreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = (); } @@ -196,10 +200,6 @@ parameter_types! { pub const AuctionTimeToClose: u64 = 100; pub const AuctionDurationSoftCap: u64 = 2000; pub const UnsignedPriority: u64 = 1 << 20; - pub DefaultSwapParitalPathList: Vec> = vec![ - vec![AUSD], - vec![DOT, AUSD], - ]; } impl Config for Runtime { @@ -211,11 +211,9 @@ impl Config for Runtime { type AuctionDurationSoftCap = AuctionDurationSoftCap; type GetStableCurrencyId = GetStableCurrencyId; type CDPTreasury = CDPTreasuryModule; - type DEX = DEXModule; type PriceSource = MockPriceSource; type UnsignedPriority = UnsignedPriority; type EmergencyShutdown = MockEmergencyShutdown; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = (); } diff --git a/modules/auction-manager/src/tests.rs b/modules/auction-manager/src/tests.rs index 72bc5d76a7..f016d3ecd3 100644 --- a/modules/auction-manager/src/tests.rs +++ b/modules/auction-manager/src/tests.rs @@ -26,6 +26,7 @@ use mock::{Call as MockCall, Event, *}; use sp_core::offchain::{testing, DbExternalities, OffchainDbExt, OffchainWorkerExt, StorageKind, TransactionPoolExt}; use sp_io::offchain; use sp_runtime::traits::One; +use support::DEXManager; fn run_to_block_offchain(n: u64) { while System::block_number() < n { @@ -187,7 +188,10 @@ fn collateral_auction_end_handler_without_bid() { false )); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (100, 1000)); - assert_eq!(DEXModule::get_swap_target_amount(&[BTC, AUSD], 100).unwrap(), 500); + assert_eq!( + DEXModule::get_swap_amount(&vec![BTC, AUSD], SwapLimit::ExactSupply(100, 0)), + Some((100, 500)) + ); assert_ok!(AuctionManagerModule::new_collateral_auction(&ALICE, BTC, 100, 200)); assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 100); @@ -244,8 +248,14 @@ fn collateral_auction_end_handler_without_bid_and_swap_by_alternative_path() { )); assert_eq!(DEXModule::get_liquidity_pool(BTC, DOT), (100, 1000)); assert_eq!(DEXModule::get_liquidity_pool(DOT, AUSD), (1000, 1000)); - assert_eq!(DEXModule::get_swap_target_amount(&[BTC, AUSD], 100), None); - assert_eq!(DEXModule::get_swap_target_amount(&[BTC, DOT, AUSD], 100), Some(333)); + assert_eq!( + DEXModule::get_swap_amount(&vec![BTC, AUSD], SwapLimit::ExactSupply(100, 0)), + None + ); + assert_eq!( + DEXModule::get_swap_amount(&vec![BTC, DOT, AUSD], SwapLimit::ExactSupply(100, 0)), + Some((100, 333)) + ); assert_ok!(AuctionManagerModule::new_collateral_auction(&ALICE, BTC, 100, 200)); assert_eq!(Tokens::free_balance(BTC, &ALICE), 1000); @@ -354,7 +364,10 @@ fn collateral_auction_end_handler_by_dex_which_target_not_zero() { 0, false )); - assert_eq!(DEXModule::get_swap_target_amount(&[BTC, AUSD], 100).unwrap(), 500); + assert_eq!( + DEXModule::get_swap_amount(&vec![BTC, AUSD], SwapLimit::ExactSupply(100, 0)), + Some((100, 500)) + ); assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 100); assert_eq!(AuctionManagerModule::total_target_in_auction(), 200); diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 0f403c7a82..48944efc80 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -57,6 +57,7 @@ use sp_runtime::{ use sp_std::prelude::*; use support::{ CDPTreasury, CDPTreasuryExtended, EmergencyShutdown, ExchangeRate, Price, PriceProvider, Rate, Ratio, RiskManager, + SwapLimit, }; mod debit_exchange_rate_convertor; @@ -189,12 +190,6 @@ pub mod module { /// Thus value at genesis is not used. type UnixTime: UnixTime; - /// The default parital path list for CDP engine to swap collateral to stable, - /// Note: the path is parital, the whole swap path is collateral currency id concat - /// the partial path. And the list is sorted, CDP engine trys to swap stable by order. - #[pallet::constant] - type DefaultSwapParitalPathList: Get>>; - /// Weight information for the extrinsics in this module. type WeightInfo: WeightInfo; } @@ -372,12 +367,6 @@ pub mod module { ); } } - - fn integrity_test() { - assert!(T::DefaultSwapParitalPathList::get() - .iter() - .all(|path| !path.is_empty() && path[path.len() - 1] == T::GetStableCurrencyId::get())); - } } #[pallet::call] @@ -827,7 +816,6 @@ impl Pallet { who: T::AccountId, currency_id: CurrencyId, max_collateral_amount: Balance, - maybe_path: Option<&[CurrencyId]>, ) -> DispatchResult { let Position { collateral, debit } = >::positions(currency_id, &who); ensure!(!debit.is_zero(), Error::::NoDebitValue); @@ -844,43 +832,12 @@ impl Pallet { let collateral_supply = collateral.min(max_collateral_amount); // if specify swap path - let actual_supply_collateral = (|| -> Result { - if let Some(path) = maybe_path { - ::CDPTreasury::swap_collateral_to_exact_stable( - currency_id, - collateral_supply, - debit_value, - path, - false, - ) - } else { - let default_swap_parital_path_list: Vec> = T::DefaultSwapParitalPathList::get(); - - // iterator default_swap_parital_path_list to try swap until swap succeed. - for partial_path in default_swap_parital_path_list { - let partial_path_len = partial_path.len(); - - // check collateral currency_id and partial_path can form a valid swap path. - if partial_path_len > 0 && currency_id != partial_path[0] { - let mut swap_path = vec![currency_id]; - swap_path.extend(partial_path); - - if let Ok(actual_supply_collateral) = - ::CDPTreasury::swap_collateral_to_exact_stable( - currency_id, - collateral_supply, - debit_value, - &swap_path, - false, - ) { - return Ok(actual_supply_collateral); - } - } - } - - Err(Error::::SwapDebitFailed.into()) - } - })()?; + let (actual_supply_collateral, _) = ::CDPTreasury::swap_collateral_to_stable( + currency_id, + SwapLimit::ExactTarget(collateral_supply, debit_value), + false, + ) + .map_err(|_| Error::::SwapDebitFailed)?; // refund remain collateral to CDP owner let refund_collateral_amount = collateral @@ -917,8 +874,6 @@ impl Pallet { let bad_debt_value = Self::get_debit_value(currency_id, debit); let target_stable_amount = Self::get_liquidation_penalty(currency_id).saturating_mul_acc_int(bad_debt_value); let liquidation_strategy = (|| -> Result { - let default_swap_parital_path_list: Vec> = T::DefaultSwapParitalPathList::get(); - // calculate the supply limit by slippage limit for the price of oracle, let max_supply_limit = Ratio::one() .saturating_sub(T::MaxSwapSlippageCompareToOracle::get()) @@ -931,32 +886,22 @@ impl Pallet { ); let collateral_supply = collateral.min(max_supply_limit); - // iterator default_swap_parital_path_list to try swap until swap succeed. - for partial_path in default_swap_parital_path_list { - let partial_path_len = partial_path.len(); - - // check collateral currency_id and partial_path can form a valid swap path. - if partial_path_len > 0 && currency_id != partial_path[0] { - let mut swap_path = vec![currency_id]; - swap_path.extend(partial_path); - - if let Ok(actual_supply_collateral) = ::CDPTreasury::swap_collateral_to_exact_stable( - currency_id, - collateral_supply, - target_stable_amount, - &swap_path, - false, - ) { - // refund remain collateral to CDP owner - let refund_collateral_amount = collateral - .checked_sub(actual_supply_collateral) - .expect("swap succecced means collateral >= actual_supply_collateral; qed"); - - ::CDPTreasury::withdraw_collateral(&who, currency_id, refund_collateral_amount)?; - - return Ok(LiquidationStrategy::Exchange); - } + // try swap collateral to stable to settle debit swap succeed. + if let Ok((actual_supply_collateral, _)) = ::CDPTreasury::swap_collateral_to_stable( + currency_id, + SwapLimit::ExactTarget(collateral_supply, target_stable_amount), + false, + ) { + let refund_collateral_amount = collateral + .checked_sub(actual_supply_collateral) + .expect("swap succecced means collateral >= actual_supply_collateral; qed"); + + // refund remain collateral to CDP owner + if !refund_collateral_amount.is_zero() { + ::CDPTreasury::withdraw_collateral(&who, currency_id, refund_collateral_amount)?; } + + return Ok(LiquidationStrategy::Exchange); } // if cannot liquidate by swap, create collateral auctions by cdp treasury diff --git a/modules/cdp-engine/src/mock.rs b/modules/cdp-engine/src/mock.rs index e20d767ab4..f38283d4cc 100644 --- a/modules/cdp-engine/src/mock.rs +++ b/modules/cdp-engine/src/mock.rs @@ -202,6 +202,9 @@ parameter_types! { pub const MaxAuctionsCount: u32 = 10_000; pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub TreasuryAccount: AccountId = PalletId(*b"aca/hztr").into_account(); + pub AlternativeSwapPathJointList: Vec> = vec![ + vec![ACA], + ]; } impl cdp_treasury::Config for Runtime { @@ -214,6 +217,7 @@ impl cdp_treasury::Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = TreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = (); } @@ -279,10 +283,6 @@ parameter_types! { pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(50, 100); pub const UnsignedPriority: u64 = 1 << 20; pub CollateralCurrencyIds: Vec = vec![BTC, DOT]; - pub DefaultSwapParitalPathList: Vec> = vec![ - vec![AUSD], - vec![ACA, AUSD], - ]; } impl Config for Runtime { @@ -300,7 +300,6 @@ impl Config for Runtime { type UnsignedPriority = UnsignedPriority; type EmergencyShutdown = MockEmergencyShutdown; type UnixTime = Timestamp; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = (); } diff --git a/modules/cdp-engine/src/tests.rs b/modules/cdp-engine/src/tests.rs index a8fd1e3689..a1e07bcef7 100644 --- a/modules/cdp-engine/src/tests.rs +++ b/modules/cdp-engine/src/tests.rs @@ -520,8 +520,14 @@ fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { // pool is enough, but slippage limit the swap MockPriceSource::set_relative_price(Some(Price::saturating_from_rational(1, 2))); - assert_eq!(DEXModule::get_swap_supply_amount(&[BTC, AUSD], 60), Some(99)); - assert_eq!(DEXModule::get_swap_target_amount(&[BTC, AUSD], 100), Some(60)); + assert_eq!( + DEXModule::get_swap_amount(&vec![BTC, AUSD], SwapLimit::ExactTarget(Balance::MAX, 60)), + Some((99, 60)) + ); + assert_eq!( + DEXModule::get_swap_amount(&vec![BTC, AUSD], SwapLimit::ExactSupply(100, 0)), + Some((100, 60)) + ); assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP( BTC, @@ -813,7 +819,7 @@ fn close_cdp_has_debit_by_dex_work() { assert_eq!(LoansModule::positions(BTC, ALICE).collateral, 100); assert_noop!( - CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 100, None), + CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 100), Error::::NoDebitValue ); @@ -835,7 +841,7 @@ fn close_cdp_has_debit_by_dex_work() { Change::NoChange, )); assert_noop!( - CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 100, None), + CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 100), Error::::MustBeSafe ); @@ -849,19 +855,14 @@ fn close_cdp_has_debit_by_dex_work() { Change::NoChange, )); - assert_noop!( - CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 5, None), - Error::::SwapDebitFailed - ); - // max collateral amount limit swap assert_noop!( - CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 5, Some(&[BTC, AUSD])), - dex::Error::::ExcessiveSupplyAmount + CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 5), + Error::::SwapDebitFailed ); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (100, 1000)); - assert_ok!(CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 6, None)); + assert_ok!(CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 6)); System::assert_last_event(Event::CDPEngineModule(crate::Event::CloseCDPInDebitByDEX( BTC, ALICE, 6, 94, 50, ))); @@ -927,7 +928,7 @@ fn close_cdp_has_debit_by_swap_on_alternative_path() { Change::NoChange, Change::NoChange, )); - assert_ok!(CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 100, None)); + assert_ok!(CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 100)); System::assert_last_event(Event::CDPEngineModule(crate::Event::CloseCDPInDebitByDEX( BTC, ALICE, 6, 94, 50, ))); diff --git a/modules/cdp-treasury/src/lib.rs b/modules/cdp-treasury/src/lib.rs index eb06b77b45..5a0b82ecb1 100644 --- a/modules/cdp-treasury/src/lib.rs +++ b/modules/cdp-treasury/src/lib.rs @@ -36,7 +36,8 @@ use sp_runtime::{ traits::{AccountIdConversion, One, Zero}, ArithmeticError, DispatchError, DispatchResult, FixedPointNumber, }; -use support::{AuctionManager, CDPTreasury, CDPTreasuryExtended, DEXManager, Ratio}; +use sp_std::prelude::*; +use support::{AuctionManager, CDPTreasury, CDPTreasuryExtended, DEXManager, Ratio, SwapLimit}; mod mock; mod tests; @@ -85,6 +86,12 @@ pub mod module { #[pallet::constant] type PalletId: Get; + /// The default parital path list for DEX to directly take auction, + /// Note: the path is parital, the whole swap path is collateral currency id concat + /// the partial path. And the list is sorted, DEX try to take auction by order. + #[pallet::constant] + type AlternativeSwapPathJointList: Get>>; + /// Weight information for the extrinsics in this module. type WeightInfo: WeightInfo; } @@ -97,8 +104,8 @@ pub mod module { SurplusPoolNotEnough, /// The debit pool of CDP treasury is not enough DebitPoolNotEnough, - /// The swap path is invalid - InvalidSwapPath, + /// There's no swap path for collateral to swap stable + NoSwapPath, } #[pallet::event] @@ -319,70 +326,36 @@ impl CDPTreasury for Pallet { } impl CDPTreasuryExtended for Pallet { - /// Swap exact amount of collateral stable, - /// return actual target stable amount - fn swap_exact_collateral_to_stable( + fn swap_collateral_to_stable( currency_id: CurrencyId, - supply_amount: Balance, - min_target_amount: Balance, - swap_path: &[CurrencyId], + limit: SwapLimit, collateral_in_auction: bool, - ) -> sp_std::result::Result { - if collateral_in_auction { - ensure!( - Self::total_collaterals(currency_id) >= supply_amount - && T::AuctionManagerHandler::get_total_collateral_in_auction(currency_id) >= supply_amount, - Error::::CollateralNotEnough, - ); - } else { - ensure!( - Self::total_collaterals_not_in_auction(currency_id) >= supply_amount, - Error::::CollateralNotEnough, - ); - } - - let swap_path_length = swap_path.len(); - ensure!( - swap_path_length >= 2 - && swap_path[0] == currency_id - && swap_path[swap_path_length - 1] == T::GetStableCurrencyId::get(), - Error::::InvalidSwapPath - ); - - T::DEX::swap_with_exact_supply(&Self::account_id(), swap_path, supply_amount, min_target_amount) - } - - /// swap collateral which not in auction to get exact stable, - /// return actual supply collateral amount - fn swap_collateral_to_exact_stable( - currency_id: CurrencyId, - max_supply_amount: Balance, - target_amount: Balance, - swap_path: &[CurrencyId], - collateral_in_auction: bool, - ) -> sp_std::result::Result { + ) -> sp_std::result::Result<(Balance, Balance), DispatchError> { + let supply_limit = match limit { + SwapLimit::ExactSupply(supply_amount, _) => supply_amount, + SwapLimit::ExactTarget(max_supply_amount, _) => max_supply_amount, + }; if collateral_in_auction { ensure!( - Self::total_collaterals(currency_id) >= max_supply_amount - && T::AuctionManagerHandler::get_total_collateral_in_auction(currency_id) >= max_supply_amount, + Self::total_collaterals(currency_id) >= supply_limit + && T::AuctionManagerHandler::get_total_collateral_in_auction(currency_id) >= supply_limit, Error::::CollateralNotEnough, ); } else { ensure!( - Self::total_collaterals_not_in_auction(currency_id) >= max_supply_amount, + Self::total_collaterals_not_in_auction(currency_id) >= supply_limit, Error::::CollateralNotEnough, ); } - let swap_path_length = swap_path.len(); - ensure!( - swap_path_length >= 2 - && swap_path[0] == currency_id - && swap_path[swap_path_length - 1] == T::GetStableCurrencyId::get(), - Error::::InvalidSwapPath - ); - - T::DEX::swap_with_exact_target(&Self::account_id(), swap_path, target_amount, max_supply_amount) + let swap_path = T::DEX::get_best_price_swap_path( + currency_id, + T::GetStableCurrencyId::get(), + limit, + T::AlternativeSwapPathJointList::get(), + ) + .ok_or(Error::::NoSwapPath)?; + T::DEX::swap_with_specific_path(&Self::account_id(), &swap_path, limit) } fn create_collateral_auctions( diff --git a/modules/cdp-treasury/src/mock.rs b/modules/cdp-treasury/src/mock.rs index e2edd41d67..cea3859344 100644 --- a/modules/cdp-treasury/src/mock.rs +++ b/modules/cdp-treasury/src/mock.rs @@ -39,6 +39,7 @@ pub type AuctionId = u32; pub const ALICE: AccountId = 0; pub const BOB: AccountId = 1; +pub const CHARLIE: AccountId = 2; pub const ACA: CurrencyId = CurrencyId::Token(TokenSymbol::ACA); pub const AUSD: CurrencyId = CurrencyId::Token(TokenSymbol::AUSD); pub const BTC: CurrencyId = CurrencyId::Token(TokenSymbol::RENBTC); @@ -192,6 +193,9 @@ ord_parameter_types! { parameter_types! { pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub const TreasuryAccount: AccountId = 10; + pub AlternativeSwapPathJointList: Vec> = vec![ + vec![DOT], + ]; } thread_local! { @@ -208,6 +212,7 @@ impl Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = TreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = (); } @@ -243,6 +248,7 @@ impl Default for ExtBuilder { (BOB, DOT, 1000), (BOB, AUSD, 1000), (BOB, BTC, 1000), + (CHARLIE, DOT, 1000), ], } } diff --git a/modules/cdp-treasury/src/tests.rs b/modules/cdp-treasury/src/tests.rs index 7d0dd77767..bc8de40b05 100644 --- a/modules/cdp-treasury/src/tests.rs +++ b/modules/cdp-treasury/src/tests.rs @@ -187,26 +187,13 @@ fn get_debit_proportion_work() { } #[test] -fn swap_collateral_to_exact_stable_work() { +fn swap_collateral_to_stable_work() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(DEXModule::add_liquidity( - Origin::signed(ALICE), - BTC, - AUSD, - 100, - 1000, - 0, - false - )); - assert_ok!(DEXModule::add_liquidity( - Origin::signed(ALICE), - BTC, - DOT, - 900, - 1000, - 0, - false - )); + assert_ok!(CDPTreasuryModule::deposit_collateral(&BOB, BTC, 200)); + assert_ok!(CDPTreasuryModule::deposit_collateral(&CHARLIE, DOT, 1000)); + assert_eq!(CDPTreasuryModule::total_collaterals_not_in_auction(BTC), 200); + assert_eq!(CDPTreasuryModule::total_collaterals_not_in_auction(DOT), 1000); + assert_eq!(CDPTreasuryModule::surplus_pool(), 0); assert_ok!(DEXModule::add_liquidity( Origin::signed(BOB), DOT, @@ -216,128 +203,48 @@ fn swap_collateral_to_exact_stable_work() { 0, false )); - assert_ok!(CDPTreasuryModule::deposit_collateral(&BOB, BTC, 200)); - assert_eq!(CDPTreasuryModule::surplus_pool(), 0); - assert_eq!(CDPTreasuryModule::total_collaterals_not_in_auction(BTC), 200); assert_noop!( - CDPTreasuryModule::swap_collateral_to_exact_stable(BTC, 201, 499, &[BTC, AUSD], false), + CDPTreasuryModule::swap_collateral_to_stable(BTC, SwapLimit::ExactTarget(201, 200), false), Error::::CollateralNotEnough, ); - - assert_ok!(CDPTreasuryModule::swap_collateral_to_exact_stable( - BTC, - 100, - 499, - &[BTC, AUSD], - false - )); - assert_eq!(CDPTreasuryModule::surplus_pool(), 499); - assert_eq!(CDPTreasuryModule::total_collaterals_not_in_auction(BTC), 100); - - assert_noop!( - CDPTreasuryModule::swap_collateral_to_exact_stable(BTC, 100, 199, &[BTC], false), - Error::::InvalidSwapPath - ); assert_noop!( - CDPTreasuryModule::swap_collateral_to_exact_stable(BTC, 100, 199, &[BTC, DOT], false), - Error::::InvalidSwapPath + CDPTreasuryModule::swap_collateral_to_stable(DOT, SwapLimit::ExactSupply(1001, 0), false), + Error::::CollateralNotEnough, ); + assert_noop!( - CDPTreasuryModule::swap_collateral_to_exact_stable(BTC, 100, 199, &[DOT, AUSD], false), - Error::::InvalidSwapPath + CDPTreasuryModule::swap_collateral_to_stable(BTC, SwapLimit::ExactTarget(200, 399), false), + Error::::NoSwapPath ); - assert_ok!(CDPTreasuryModule::swap_collateral_to_exact_stable( - BTC, - 100, - 10, - &[BTC, DOT, AUSD], - false - )); - assert_eq!(CDPTreasuryModule::surplus_pool(), 509); - assert_eq!(CDPTreasuryModule::total_collaterals_not_in_auction(BTC), 89); - }); -} - -#[test] -fn swap_exact_collateral_to_stable_work() { - ExtBuilder::default().build().execute_with(|| { assert_ok!(DEXModule::add_liquidity( Origin::signed(ALICE), BTC, - AUSD, - 100, - 1000, - 0, - false - )); - assert_ok!(DEXModule::add_liquidity( - Origin::signed(ALICE), - BTC, - DOT, - 900, - 1000, - 0, - false - )); - assert_ok!(DEXModule::add_liquidity( - Origin::signed(BOB), DOT, - AUSD, - 1000, + 100, 1000, 0, false )); - assert_ok!(CDPTreasuryModule::deposit_collateral(&BOB, BTC, 200)); - assert_eq!(CDPTreasuryModule::surplus_pool(), 0); - assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 200); - assert_noop!( - CDPTreasuryModule::swap_exact_collateral_to_stable(BTC, 200, 100, &[BTC, AUSD], true), - Error::::CollateralNotEnough, + assert_eq!( + CDPTreasuryModule::swap_collateral_to_stable(BTC, SwapLimit::ExactTarget(200, 399), false).unwrap(), + (198, 399) ); - - assert_ok!(CDPTreasuryModule::create_collateral_auctions( - BTC, 200, 1000, ALICE, true - )); - assert_eq!(TOTAL_COLLATERAL_IN_AUCTION.with(|v| *v.borrow_mut()), 200); - - assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 200); - assert_eq!(MockAuctionManager::get_total_collateral_in_auction(BTC), 200); - - assert_ok!(CDPTreasuryModule::swap_exact_collateral_to_stable( - BTC, - 100, - 400, - &[BTC, AUSD], - true - )); - assert_eq!(CDPTreasuryModule::surplus_pool(), 500); - assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 100); + assert_eq!(CDPTreasuryModule::surplus_pool(), 399); + assert_eq!(CDPTreasuryModule::total_collaterals_not_in_auction(BTC), 2); assert_noop!( - CDPTreasuryModule::swap_exact_collateral_to_stable(BTC, 100, 199, &[BTC], true), - Error::::InvalidSwapPath - ); - assert_noop!( - CDPTreasuryModule::swap_exact_collateral_to_stable(BTC, 100, 199, &[BTC, DOT], true), - Error::::InvalidSwapPath - ); - assert_noop!( - CDPTreasuryModule::swap_exact_collateral_to_stable(BTC, 100, 199, &[DOT, AUSD], true), - Error::::InvalidSwapPath + CDPTreasuryModule::swap_collateral_to_stable(DOT, SwapLimit::ExactSupply(1000, 1000), false), + Error::::NoSwapPath, ); - assert_ok!(CDPTreasuryModule::swap_exact_collateral_to_stable( - BTC, - 100, - 10, - &[BTC, DOT, AUSD], - true - )); - assert_eq!(CDPTreasuryModule::surplus_pool(), 590); - assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 0); + assert_eq!( + CDPTreasuryModule::swap_collateral_to_stable(DOT, SwapLimit::ExactSupply(1000, 0), false).unwrap(), + (1000, 225) + ); + assert_eq!(CDPTreasuryModule::surplus_pool(), 624); + assert_eq!(CDPTreasuryModule::total_collaterals_not_in_auction(DOT), 0); }); } diff --git a/modules/dex/src/lib.rs b/modules/dex/src/lib.rs index 748b6c7583..7b94ec8ad9 100644 --- a/modules/dex/src/lib.rs +++ b/modules/dex/src/lib.rs @@ -45,7 +45,7 @@ use sp_runtime::{ ArithmeticError, DispatchError, DispatchResult, FixedPointNumber, RuntimeDebug, SaturatedConversion, }; use sp_std::{prelude::*, vec}; -use support::{DEXIncentives, DEXManager, Erc20InfoMapping, ExchangeRate, Ratio}; +use support::{DEXIncentives, DEXManager, Erc20InfoMapping, ExchangeRate, Ratio, SwapLimit}; mod mock; mod tests; @@ -1227,34 +1227,87 @@ impl DEXManager for Pallet { T::Erc20InfoMapping::encode_evm_address(trading_pair.dex_share_currency_id()) } - fn get_swap_target_amount(path: &[CurrencyId], supply_amount: Balance) -> Option { - Self::get_target_amounts(path, supply_amount) - .ok() - .map(|amounts| amounts[amounts.len() - 1]) + fn get_swap_amount(path: &[CurrencyId], limit: SwapLimit) -> Option<(Balance, Balance)> { + match limit { + SwapLimit::ExactSupply(exact_supply_amount, minimum_target_amount) => { + Self::get_target_amounts(path, exact_supply_amount) + .ok() + .and_then(|amounts| { + if amounts[amounts.len() - 1] >= minimum_target_amount { + Some((exact_supply_amount, amounts[amounts.len() - 1])) + } else { + None + } + }) + } + SwapLimit::ExactTarget(maximum_supply_amount, exact_target_amount) => { + Self::get_supply_amounts(path, exact_target_amount) + .ok() + .and_then(|amounts| { + if amounts[0] <= maximum_supply_amount { + Some((amounts[0], exact_target_amount)) + } else { + None + } + }) + } + } } - fn get_swap_supply_amount(path: &[CurrencyId], target_amount: Balance) -> Option { - Self::get_supply_amounts(path, target_amount) - .ok() - .map(|amounts| amounts[0]) - } + fn get_best_price_swap_path( + supply_currency_id: CurrencyId, + target_currency_id: CurrencyId, + limit: SwapLimit, + alternative_path_joint_list: Vec>, + ) -> Option> { + let default_swap_path = vec![supply_currency_id, target_currency_id]; + let mut maybe_best = Self::get_swap_amount(&default_swap_path, limit) + .map(|(supply_amout, target_amount)| (default_swap_path, supply_amout, target_amount)); + + for path_joint in alternative_path_joint_list { + if !path_joint.is_empty() { + let mut swap_path = vec![]; + + if supply_currency_id != path_joint[0] { + swap_path.extend(vec![supply_currency_id]); + } - fn swap_with_exact_supply( - who: &T::AccountId, - path: &[CurrencyId], - supply_amount: Balance, - min_target_amount: Balance, - ) -> sp_std::result::Result { - Self::do_swap_with_exact_supply(who, path, supply_amount, min_target_amount) + swap_path.extend(path_joint.clone()); + + if target_currency_id != path_joint[path_joint.len() - 1] { + swap_path.extend(vec![target_currency_id]); + } + + if let Some((supply_amount, target_amount)) = Self::get_swap_amount(&swap_path, limit) { + if let Some((_, previous_supply, previous_target)) = maybe_best { + if supply_amount > previous_supply || target_amount < previous_target { + continue; + } + } + + maybe_best = Some((swap_path, supply_amount, target_amount)); + } + } + } + + maybe_best.map(|(path, _, _)| path) } - fn swap_with_exact_target( + fn swap_with_specific_path( who: &T::AccountId, path: &[CurrencyId], - target_amount: Balance, - max_supply_amount: Balance, - ) -> sp_std::result::Result { - Self::do_swap_with_exact_target(who, path, target_amount, max_supply_amount) + limit: SwapLimit, + ) -> sp_std::result::Result<(Balance, Balance), DispatchError> { + match limit { + SwapLimit::ExactSupply(exact_supply_amount, minimum_target_amount) => { + Self::do_swap_with_exact_supply(who, path, exact_supply_amount, minimum_target_amount) + .map(|actual_target_amount| (exact_supply_amount, actual_target_amount)) + } + SwapLimit::ExactTarget(maximum_supply_amount, exact_target_amount) => { + Self::do_swap_with_exact_target(who, path, exact_target_amount, maximum_supply_amount) + .map(|actual_supply_amount| (actual_supply_amount, exact_target_amount)) + } + } } // `do_add_liquidity` is used in genesis_build, diff --git a/modules/dex/src/tests.rs b/modules/dex/src/tests.rs index dd03d26460..5e9c64de5a 100644 --- a/modules/dex/src/tests.rs +++ b/modules/dex/src/tests.rs @@ -23,8 +23,8 @@ use super::*; use frame_support::{assert_noop, assert_ok}; use mock::{ - AUSDBTCPair, AUSDDOTPair, DexModule, Event, ExtBuilder, ListingOrigin, Origin, Runtime, System, Tokens, ACA, ALICE, - AUSD, BOB, BTC, DOT, + AUSDBTCPair, AUSDDOTPair, DOTBTCPair, DexModule, Event, ExtBuilder, ListingOrigin, Origin, Runtime, System, Tokens, + ACA, ALICE, AUSD, BOB, BTC, DOT, }; use orml_traits::MultiReservableCurrency; use sp_runtime::traits::BadOrigin; @@ -1338,3 +1338,166 @@ fn initialize_added_liquidity_pools_genesis_work() { ); }); } + +#[test] +fn get_swap_amount_work() { + ExtBuilder::default() + .initialize_enabled_trading_pairs() + .build() + .execute_with(|| { + LiquidityPool::::insert(AUSDDOTPair::get(), (50000, 10000)); + assert_eq!( + DexModule::get_swap_amount(&vec![DOT, AUSD], SwapLimit::ExactSupply(10000, 0)), + Some((10000, 24874)) + ); + assert_eq!( + DexModule::get_swap_amount(&vec![DOT, AUSD], SwapLimit::ExactSupply(10000, 24875)), + None + ); + assert_eq!( + DexModule::get_swap_amount(&vec![DOT, AUSD], SwapLimit::ExactTarget(Balance::max_value(), 24874)), + Some((10000, 24874)) + ); + assert_eq!( + DexModule::get_swap_amount(&vec![DOT, AUSD], SwapLimit::ExactTarget(9999, 24874)), + None + ); + }); +} + +#[test] +fn get_best_price_swap_path_work() { + ExtBuilder::default() + .initialize_enabled_trading_pairs() + .build() + .execute_with(|| { + LiquidityPool::::insert(AUSDDOTPair::get(), (300000, 100000)); + LiquidityPool::::insert(AUSDBTCPair::get(), (50000, 10000)); + LiquidityPool::::insert(DOTBTCPair::get(), (10000, 10000)); + + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactSupply(10, 0), vec![]), + Some(vec![DOT, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactSupply(10, 30), vec![]), + None + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactSupply(0, 0), vec![]), + None + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactSupply(10, 0), vec![vec![ACA]]), + Some(vec![DOT, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactSupply(10, 0), vec![vec![DOT]]), + Some(vec![DOT, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactSupply(10, 0), vec![vec![AUSD]]), + Some(vec![DOT, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactSupply(10, 0), vec![vec![BTC]]), + Some(vec![DOT, BTC, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactSupply(10000, 0), vec![vec![BTC]]), + Some(vec![DOT, AUSD]) + ); + + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactTarget(20, 30), vec![]), + Some(vec![DOT, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactTarget(10, 30), vec![]), + None + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactTarget(0, 0), vec![]), + None + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactTarget(20, 30), vec![vec![ACA]]), + Some(vec![DOT, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactTarget(20, 30), vec![vec![DOT]]), + Some(vec![DOT, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactTarget(20, 30), vec![vec![AUSD]]), + Some(vec![DOT, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactTarget(20, 30), vec![vec![BTC]]), + Some(vec![DOT, BTC, AUSD]) + ); + assert_eq!( + DexModule::get_best_price_swap_path(DOT, AUSD, SwapLimit::ExactTarget(100000, 20000), vec![vec![BTC]]), + Some(vec![DOT, AUSD]) + ); + }); +} + +#[test] +fn swap_with_specific_path_work() { + ExtBuilder::default() + .initialize_enabled_trading_pairs() + .build() + .execute_with(|| { + System::set_block_number(1); + assert_ok!(DexModule::add_liquidity( + Origin::signed(ALICE), + AUSD, + DOT, + 500_000_000_000_000, + 100_000_000_000_000, + 0, + false, + )); + + assert_noop!( + DexModule::swap_with_specific_path( + &BOB, + &vec![DOT, AUSD], + SwapLimit::ExactSupply(100_000_000_000_000, 248_743_718_592_965) + ), + Error::::InsufficientTargetAmount + ); + + assert_ok!(DexModule::swap_with_specific_path( + &BOB, + &vec![DOT, AUSD], + SwapLimit::ExactSupply(100_000_000_000_000, 200_000_000_000_000) + )); + System::assert_last_event(Event::DexModule(crate::Event::Swap( + BOB, + vec![DOT, AUSD], + vec![100_000_000_000_000, 248_743_718_592_964], + ))); + + assert_noop!( + DexModule::swap_with_specific_path( + &BOB, + &vec![AUSD, DOT], + SwapLimit::ExactTarget(253_794_223_643_470, 100_000_000_000_000) + ), + Error::::ExcessiveSupplyAmount + ); + + assert_ok!(DexModule::swap_with_specific_path( + &BOB, + &vec![AUSD, DOT], + SwapLimit::ExactTarget(300_000_000_000_000, 100_000_000_000_000) + )); + System::assert_last_event(Event::DexModule(crate::Event::Swap( + BOB, + vec![AUSD, DOT], + vec![253_794_223_643_471, 100_000_000_000_000], + ))); + }); +} diff --git a/modules/emergency-shutdown/src/mock.rs b/modules/emergency-shutdown/src/mock.rs index e4c4db6fd4..4008a5b767 100644 --- a/modules/emergency-shutdown/src/mock.rs +++ b/modules/emergency-shutdown/src/mock.rs @@ -199,6 +199,7 @@ parameter_types! { pub const MaxAuctionsCount: u32 = 10_000; pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub TreasuryAccount: AccountId = PalletId(*b"aca/hztr").into_account(); + pub AlternativeSwapPathJointList: Vec> = vec![]; } impl cdp_treasury::Config for Runtime { @@ -211,6 +212,7 @@ impl cdp_treasury::Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = TreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = (); } diff --git a/modules/honzon/src/lib.rs b/modules/honzon/src/lib.rs index dc9bd579c7..087926e777 100644 --- a/modules/honzon/src/lib.rs +++ b/modules/honzon/src/lib.rs @@ -36,7 +36,6 @@ use sp_runtime::{ traits::{StaticLookup, Zero}, DispatchResult, }; -use sp_std::vec::Vec; use support::EmergencyShutdown; mod mock; @@ -153,28 +152,16 @@ pub mod module { /// - `currency_id`: collateral currency id. /// - `max_collateral_amount`: the max collateral amount which is used to swap enough /// stable token to clear debit. - /// - `maybe_path`: the custom swap path. - #[pallet::weight( - match maybe_path { - Some(path) => ::WeightInfo::close_loan_has_debit_by_dex(path.len() as u32), - None => ::WeightInfo::close_loan_has_debit_by_dex_no_path(), - } - )] + #[pallet::weight(::WeightInfo::close_loan_has_debit_by_dex())] #[transactional] pub fn close_loan_has_debit_by_dex( origin: OriginFor, currency_id: CurrencyId, #[pallet::compact] max_collateral_amount: Balance, - maybe_path: Option>, ) -> DispatchResult { let who = ensure_signed(origin)?; ensure!(!T::EmergencyShutdown::is_shutdown(), Error::::AlreadyShutdown); - >::close_cdp_has_debit_by_dex( - who, - currency_id, - max_collateral_amount, - maybe_path.as_deref(), - )?; + >::close_cdp_has_debit_by_dex(who, currency_id, max_collateral_amount)?; Ok(()) } diff --git a/modules/honzon/src/mock.rs b/modules/honzon/src/mock.rs index 2bd761da94..ef1837e792 100644 --- a/modules/honzon/src/mock.rs +++ b/modules/honzon/src/mock.rs @@ -209,6 +209,9 @@ parameter_types! { pub const MaxAuctionsCount: u32 = 10_000; pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub TreasuryAccount: AccountId = PalletId(*b"aca/hztr").into_account(); + pub AlternativeSwapPathJointList: Vec> = vec![ + vec![AUSD], + ]; } impl cdp_treasury::Config for Runtime { @@ -221,6 +224,7 @@ impl cdp_treasury::Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = TreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = (); } @@ -242,9 +246,6 @@ parameter_types! { pub const MinimumDebitValue: Balance = 2; pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(50, 100); pub const UnsignedPriority: u64 = 1 << 20; - pub DefaultSwapParitalPathList: Vec> = vec![ - vec![AUSD], - ]; } impl cdp_engine::Config for Runtime { @@ -262,7 +263,6 @@ impl cdp_engine::Config for Runtime { type UnsignedPriority = UnsignedPriority; type EmergencyShutdown = MockEmergencyShutdown; type UnixTime = Timestamp; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = (); } diff --git a/modules/honzon/src/tests.rs b/modules/honzon/src/tests.rs index e5bf1a0d38..ca51757d2f 100644 --- a/modules/honzon/src/tests.rs +++ b/modules/honzon/src/tests.rs @@ -148,7 +148,7 @@ fn on_emergency_shutdown_should_work() { Error::::AlreadyShutdown, ); assert_noop!( - HonzonModule::close_loan_has_debit_by_dex(Origin::signed(ALICE), BTC, 100, None), + HonzonModule::close_loan_has_debit_by_dex(Origin::signed(ALICE), BTC, 100), Error::::AlreadyShutdown, ); }); @@ -174,7 +174,6 @@ fn close_loan_has_debit_by_dex_work() { Origin::signed(ALICE), BTC, 100, - None )); assert_eq!(LoansModule::positions(BTC, ALICE).collateral, 0); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 0); diff --git a/modules/honzon/src/weights.rs b/modules/honzon/src/weights.rs index 6955edd43f..46246d3a9d 100644 --- a/modules/honzon/src/weights.rs +++ b/modules/honzon/src/weights.rs @@ -52,8 +52,7 @@ pub trait WeightInfo { fn unauthorize_all(c: u32, ) -> Weight; fn adjust_loan() -> Weight; fn transfer_loan_from() -> Weight; - fn close_loan_has_debit_by_dex(u: u32, ) -> Weight; - fn close_loan_has_debit_by_dex_no_path() -> Weight; + fn close_loan_has_debit_by_dex() -> Weight; } /// Weights for module_honzon using the Acala node and recommended hardware. @@ -86,16 +85,7 @@ impl WeightInfo for AcalaWeight { .saturating_add(T::DbWeight::get().reads(21 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } - fn close_loan_has_debit_by_dex(u: u32, ) -> Weight { - (335_528_000 as Weight) - // Standard Error: 778_000 - .saturating_add((15_559_000 as Weight).saturating_mul(u as Weight)) - .saturating_add(T::DbWeight::get().reads(26 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(u as Weight))) - .saturating_add(T::DbWeight::get().writes(12 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(u as Weight))) - } - fn close_loan_has_debit_by_dex_no_path() -> Weight { + fn close_loan_has_debit_by_dex() -> Weight { (369_989_000 as Weight) .saturating_add(T::DbWeight::get().reads(32 as Weight)) .saturating_add(T::DbWeight::get().writes(14 as Weight)) @@ -131,16 +121,7 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(21 as Weight)) .saturating_add(RocksDbWeight::get().writes(7 as Weight)) } - fn close_loan_has_debit_by_dex(u: u32, ) -> Weight { - (335_528_000 as Weight) - // Standard Error: 778_000 - .saturating_add((15_559_000 as Weight).saturating_mul(u as Weight)) - .saturating_add(RocksDbWeight::get().reads(26 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(u as Weight))) - .saturating_add(RocksDbWeight::get().writes(12 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(u as Weight))) - } - fn close_loan_has_debit_by_dex_no_path() -> Weight { + fn close_loan_has_debit_by_dex() -> Weight { (369_989_000 as Weight) .saturating_add(RocksDbWeight::get().reads(32 as Weight)) .saturating_add(RocksDbWeight::get().writes(14 as Weight)) diff --git a/modules/incentives/src/mock.rs b/modules/incentives/src/mock.rs index b223b244fa..90b68002f6 100644 --- a/modules/incentives/src/mock.rs +++ b/modules/incentives/src/mock.rs @@ -34,7 +34,7 @@ use primitives::{DexShare, TokenSymbol}; use sp_core::{H160, H256}; use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; use sp_std::cell::RefCell; -pub use support::{CDPTreasury, DEXManager, Price, Ratio}; +pub use support::{CDPTreasury, DEXManager, Price, Ratio, SwapLimit}; pub type AccountId = AccountId32; pub type BlockNumber = u64; @@ -175,29 +175,24 @@ impl DEXManager for MockDEX { unimplemented!() } - fn get_swap_target_amount(_: &[CurrencyId], _: Balance) -> Option { + fn get_swap_amount(_: &[CurrencyId], _: SwapLimit) -> Option<(Balance, Balance)> { unimplemented!() } - fn get_swap_supply_amount(_: &[CurrencyId], _: Balance) -> Option { - unimplemented!() - } - - fn swap_with_exact_supply( - _: &AccountId, - _: &[CurrencyId], - _: Balance, - _: Balance, - ) -> sp_std::result::Result { + fn get_best_price_swap_path( + _: CurrencyId, + _: CurrencyId, + _: SwapLimit, + _: Vec>, + ) -> Option> { unimplemented!() } - fn swap_with_exact_target( + fn swap_with_specific_path( _: &AccountId, _: &[CurrencyId], - _: Balance, - _: Balance, - ) -> sp_std::result::Result { + _: SwapLimit, + ) -> sp_std::result::Result<(Balance, Balance), DispatchError> { unimplemented!() } diff --git a/modules/loans/src/mock.rs b/modules/loans/src/mock.rs index 3e410ff761..92ab52c204 100644 --- a/modules/loans/src/mock.rs +++ b/modules/loans/src/mock.rs @@ -167,6 +167,7 @@ parameter_types! { pub const MaxAuctionsCount: u32 = 10_000; pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt"); pub TreasuryAccount: AccountId = PalletId(*b"aca/hztr").into_account(); + pub AlternativeSwapPathJointList: Vec> = vec![]; } impl cdp_treasury::Config for Runtime { @@ -179,6 +180,7 @@ impl cdp_treasury::Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = TreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = (); } diff --git a/modules/prices/src/mock.rs b/modules/prices/src/mock.rs index c557a0bbaa..b3c59aa6d3 100644 --- a/modules/prices/src/mock.rs +++ b/modules/prices/src/mock.rs @@ -35,7 +35,7 @@ use sp_runtime::{ DispatchError, FixedPointNumber, }; use sp_std::cell::RefCell; -use support::{mocks::MockErc20InfoMapping, ExchangeRate}; +use support::{mocks::MockErc20InfoMapping, ExchangeRate, SwapLimit}; pub type AccountId = u128; pub type BlockNumber = u64; @@ -146,29 +146,24 @@ impl DEXManager for MockDEX { unimplemented!() } - fn get_swap_target_amount(_path: &[CurrencyId], _supply_amount: Balance) -> Option { + fn get_swap_amount(_: &[CurrencyId], _: SwapLimit) -> Option<(Balance, Balance)> { unimplemented!() } - fn get_swap_supply_amount(_path: &[CurrencyId], _target_amount: Balance) -> Option { + fn get_best_price_swap_path( + _: CurrencyId, + _: CurrencyId, + _: SwapLimit, + _: Vec>, + ) -> Option> { unimplemented!() } - fn swap_with_exact_supply( - _who: &AccountId, - _path: &[CurrencyId], - _supply_amount: Balance, - _min_target_amount: Balance, - ) -> sp_std::result::Result { - unimplemented!() - } - - fn swap_with_exact_target( - _who: &AccountId, - _path: &[CurrencyId], - _target_amount: Balance, - _max_supply_amount: Balance, - ) -> sp_std::result::Result { + fn swap_with_specific_path( + _: &AccountId, + _: &[CurrencyId], + _: SwapLimit, + ) -> sp_std::result::Result<(Balance, Balance), DispatchError> { unimplemented!() } diff --git a/modules/support/src/lib.rs b/modules/support/src/lib.rs index c1de5b1b6d..0e2b9a49aa 100644 --- a/modules/support/src/lib.rs +++ b/modules/support/src/lib.rs @@ -103,28 +103,33 @@ pub trait AuctionManager { fn get_total_target_in_auction() -> Self::Balance; } +#[derive(RuntimeDebug, Clone, Copy, PartialEq)] +pub enum SwapLimit { + /// use exact amount supply amount to swap. (exact_supply_amount, minimum_target_amount) + ExactSupply(Balance, Balance), + /// swap to get exact amount target. (maximum_supply_amount, exact_target_amount) + ExactTarget(Balance, Balance), +} + pub trait DEXManager { fn get_liquidity_pool(currency_id_a: CurrencyId, currency_id_b: CurrencyId) -> (Balance, Balance); fn get_liquidity_token_address(currency_id_a: CurrencyId, currency_id_b: CurrencyId) -> Option; - fn get_swap_target_amount(path: &[CurrencyId], supply_amount: Balance) -> Option; + fn get_swap_amount(path: &[CurrencyId], limit: SwapLimit) -> Option<(Balance, Balance)>; - fn get_swap_supply_amount(path: &[CurrencyId], target_amount: Balance) -> Option; + fn get_best_price_swap_path( + supply_currency_id: CurrencyId, + target_currency_id: CurrencyId, + limit: SwapLimit, + alternative_path_joint_list: Vec>, + ) -> Option>; - fn swap_with_exact_supply( + fn swap_with_specific_path( who: &AccountId, path: &[CurrencyId], - supply_amount: Balance, - min_target_amount: Balance, - ) -> sp_std::result::Result; - - fn swap_with_exact_target( - who: &AccountId, - path: &[CurrencyId], - target_amount: Balance, - max_supply_amount: Balance, - ) -> sp_std::result::Result; + limit: SwapLimit, + ) -> sp_std::result::Result<(Balance, Balance), DispatchError>; fn add_liquidity( who: &AccountId, @@ -160,29 +165,24 @@ where Some(Default::default()) } - fn get_swap_target_amount(_path: &[CurrencyId], _supply_amount: Balance) -> Option { + fn get_swap_amount(_path: &[CurrencyId], _limit: SwapLimit) -> Option<(Balance, Balance)> { Some(Default::default()) } - fn get_swap_supply_amount(_path: &[CurrencyId], _target_amount: Balance) -> Option { + fn get_best_price_swap_path( + _supply_currency_id: CurrencyId, + _target_currency_id: CurrencyId, + _limit: SwapLimit, + _alternative_path_joint_list: Vec>, + ) -> Option> { Some(Default::default()) } - fn swap_with_exact_supply( + fn swap_with_specific_path( _who: &AccountId, _path: &[CurrencyId], - _supply_amount: Balance, - _min_target_amount: Balance, - ) -> sp_std::result::Result { - Ok(Default::default()) - } - - fn swap_with_exact_target( - _who: &AccountId, - _path: &[CurrencyId], - _target_amount: Balance, - _max_supply_amount: Balance, - ) -> sp_std::result::Result { + _limit: SwapLimit, + ) -> sp_std::result::Result<(Balance, Balance), DispatchError> { Ok(Default::default()) } @@ -253,21 +253,11 @@ pub trait CDPTreasury { } pub trait CDPTreasuryExtended: CDPTreasury { - fn swap_exact_collateral_to_stable( - currency_id: Self::CurrencyId, - supply_amount: Self::Balance, - min_target_amount: Self::Balance, - swap_path: &[Self::CurrencyId], - collateral_in_auction: bool, - ) -> sp_std::result::Result; - - fn swap_collateral_to_exact_stable( + fn swap_collateral_to_stable( currency_id: Self::CurrencyId, - max_supply_amount: Self::Balance, - target_amount: Self::Balance, - swap_path: &[Self::CurrencyId], + limit: SwapLimit, collateral_in_auction: bool, - ) -> sp_std::result::Result; + ) -> sp_std::result::Result<(Self::Balance, Self::Balance), DispatchError>; fn create_collateral_auctions( currency_id: Self::CurrencyId, diff --git a/modules/transaction-payment/src/lib.rs b/modules/transaction-payment/src/lib.rs index 383d35b1b2..5b098257e7 100644 --- a/modules/transaction-payment/src/lib.rs +++ b/modules/transaction-payment/src/lib.rs @@ -52,7 +52,7 @@ use sp_runtime::{ FixedPointNumber, FixedPointOperand, FixedU128, Perquintill, }; use sp_std::{prelude::*, vec}; -use support::{DEXManager, PriceProvider, Ratio, TransactionPayment}; +use support::{DEXManager, PriceProvider, Ratio, SwapLimit, TransactionPayment}; mod mock; mod tests; @@ -614,12 +614,14 @@ where PalletBalanceOf::::max_value() }; - if T::DEX::swap_with_exact_target( + if T::DEX::swap_with_specific_path( who, &trading_path, - amount.unique_saturated_into(), - ::MultiCurrency::free_balance(supply_currency_id, who) - .min(max_supply_limit.unique_saturated_into()), + SwapLimit::ExactTarget( + ::MultiCurrency::free_balance(supply_currency_id, who) + .min(max_supply_limit.unique_saturated_into()), + amount.unique_saturated_into(), + ), ) .is_ok() { diff --git a/modules/transaction-payment/src/tests.rs b/modules/transaction-payment/src/tests.rs index 478365ccb8..f37aaf4548 100644 --- a/modules/transaction-payment/src/tests.rs +++ b/modules/transaction-payment/src/tests.rs @@ -278,8 +278,14 @@ fn charges_fee_failed_by_slippage_limit() { // pool is enough, but slippage limit the swap MockPriceSource::set_relative_price(Some(Price::saturating_from_rational(252, 4020))); - assert_eq!(DEXModule::get_swap_supply_amount(&[AUSD, ACA], 2010), Some(252)); - assert_eq!(DEXModule::get_swap_target_amount(&[AUSD, ACA], 1000), Some(5000)); + assert_eq!( + DEXModule::get_swap_amount(&vec![AUSD, ACA], SwapLimit::ExactTarget(Balance::MAX, 2010)), + Some((252, 2010)) + ); + assert_eq!( + DEXModule::get_swap_amount(&vec![AUSD, ACA], SwapLimit::ExactSupply(1000, 0)), + Some((1000, 5000)) + ); assert_noop!( ChargeTransactionPayment::::from(0).validate(&BOB, CALL2, &INFO, 500), diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index e571b55b77..784dfe3641 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -907,10 +907,6 @@ parameter_types! { pub MinimumIncrementSize: Rate = Rate::saturating_from_rational(2, 100); pub const AuctionTimeToClose: BlockNumber = 15 * MINUTES; pub const AuctionDurationSoftCap: BlockNumber = 2 * HOURS; - pub DefaultSwapParitalPathList: Vec> = vec![ - vec![AUSD], - vec![DOT, AUSD], - ]; } impl module_auction_manager::Config for Runtime { @@ -922,11 +918,9 @@ impl module_auction_manager::Config for Runtime { type AuctionDurationSoftCap = AuctionDurationSoftCap; type GetStableCurrencyId = GetStableCurrencyId; type CDPTreasury = CdpTreasury; - type DEX = Dex; type PriceSource = module_prices::PriorityLockedPriceProvider; type UnsignedPriority = runtime_common::AuctionManagerUnsignedPriority; type EmergencyShutdown = EmergencyShutdown; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = weights::module_auction_manager::WeightInfo; } @@ -1022,7 +1016,6 @@ impl module_cdp_engine::Config for Runtime { type UnsignedPriority = runtime_common::CdpEngineUnsignedPriority; type EmergencyShutdown = EmergencyShutdown; type UnixTime = Timestamp; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = weights::module_cdp_engine::WeightInfo; } @@ -1067,6 +1060,10 @@ impl module_dex::Config for Runtime { parameter_types! { pub const MaxAuctionsCount: u32 = 50; pub HonzonTreasuryAccount: AccountId = HonzonTreasuryPalletId::get().into_account(); + pub AlternativeSwapPathJointList: Vec> = vec![ + vec![DOT], + vec![LDOT], + ]; } impl module_cdp_treasury::Config for Runtime { @@ -1079,6 +1076,7 @@ impl module_cdp_treasury::Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = HonzonTreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = weights::module_cdp_treasury::WeightInfo; } diff --git a/runtime/acala/src/weights/module_honzon.rs b/runtime/acala/src/weights/module_honzon.rs index 4acbc1370e..a829b20761 100644 --- a/runtime/acala/src/weights/module_honzon.rs +++ b/runtime/acala/src/weights/module_honzon.rs @@ -74,16 +74,7 @@ impl module_honzon::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(15 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } - fn close_loan_has_debit_by_dex(u: u32, ) -> Weight { - (333_176_000 as Weight) - // Standard Error: 1_020_000 - .saturating_add((15_067_000 as Weight).saturating_mul(u as Weight)) - .saturating_add(T::DbWeight::get().reads(20 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(u as Weight))) - .saturating_add(T::DbWeight::get().writes(12 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(u as Weight))) - } - fn close_loan_has_debit_by_dex_no_path() -> Weight { + fn close_loan_has_debit_by_dex() -> Weight { (396_996_000 as Weight) .saturating_add(T::DbWeight::get().reads(29 as Weight)) .saturating_add(T::DbWeight::get().writes(15 as Weight)) diff --git a/runtime/common/src/precompile/dex.rs b/runtime/common/src/precompile/dex.rs index 877ea1d712..6c648c29be 100644 --- a/runtime/common/src/precompile/dex.rs +++ b/runtime/common/src/precompile/dex.rs @@ -20,7 +20,7 @@ use super::input::{Input, InputT, Output}; use crate::precompile::PrecompileOutput; use frame_support::log; use module_evm::{Context, ExitError, ExitSucceed, Precompile}; -use module_support::DEXManager; +use module_support::{DEXManager, SwapLimit}; use num_enum::{IntoPrimitive, TryFromPrimitive}; use primitives::{Balance, CurrencyId}; use sp_runtime::RuntimeDebug; @@ -121,7 +121,8 @@ where path, supply_amount ); - let value = as DEXManager>::get_swap_target_amount(&path, supply_amount) + let value = as DEXManager>::get_swap_amount(&path, SwapLimit::ExactSupply(supply_amount, Balance::MIN)) + .map(|(_, target)| target) .ok_or_else(|| ExitError::Other("Dex get_swap_target_amount failed".into()))?; Ok(PrecompileOutput { @@ -145,7 +146,8 @@ where path, target_amount ); - let value = as DEXManager>::get_swap_supply_amount(&path, target_amount) + let value = as DEXManager>::get_swap_amount(&path, SwapLimit::ExactTarget(Balance::MAX, target_amount)) + .map(|(supply, _)| supply) .ok_or_else(|| ExitError::Other("Dex get_swap_supply_amount failed".into()))?; Ok(PrecompileOutput { @@ -171,8 +173,8 @@ where who, path, supply_amount, min_target_amount ); - let value = - as DEXManager>::swap_with_exact_supply(&who, &path, supply_amount, min_target_amount).map_err(|e| { + let (_, value) = + as DEXManager>::swap_with_specific_path(&who, &path, SwapLimit::ExactSupply(supply_amount, min_target_amount)).map_err(|e| { let err_msg: &str = e.into(); ExitError::Other(err_msg.into()) })?; @@ -200,8 +202,8 @@ where who, path, target_amount, max_supply_amount ); - let value = - as DEXManager>::swap_with_exact_target(&who, &path, target_amount, max_supply_amount).map_err(|e| { + let (value, _) = + as DEXManager>::swap_with_specific_path(&who, &path, SwapLimit::ExactTarget(max_supply_amount, target_amount)).map_err(|e| { let err_msg: &str = e.into(); ExitError::Other(err_msg.into()) })?; diff --git a/runtime/integration-tests/src/honzon.rs b/runtime/integration-tests/src/honzon.rs index 4537ef7802..84642a71ec 100644 --- a/runtime/integration-tests/src/honzon.rs +++ b/runtime/integration-tests/src/honzon.rs @@ -548,7 +548,6 @@ fn cdp_treasury_handles_honzon_surplus_correctly() { Origin::signed(AccountId::from(ALICE)), RELAY_CHAIN_CURRENCY, 5 * dollar(RELAY_CHAIN_CURRENCY), - None )); // Just over 50 dollar(USD_CURRENCY), due to interest on loan assert_eq!(CdpTreasury::get_debit_pool(), 50165264273004); diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 53012946c2..f8325659e9 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -917,10 +917,6 @@ parameter_types! { pub MinimumIncrementSize: Rate = Rate::saturating_from_rational(2, 100); pub const AuctionTimeToClose: BlockNumber = 15 * MINUTES; pub const AuctionDurationSoftCap: BlockNumber = 2 * HOURS; - pub DefaultSwapParitalPathList: Vec> = vec![ - vec![KUSD], - vec![KSM, KUSD], - ]; } impl module_auction_manager::Config for Runtime { @@ -932,11 +928,9 @@ impl module_auction_manager::Config for Runtime { type AuctionDurationSoftCap = AuctionDurationSoftCap; type GetStableCurrencyId = GetStableCurrencyId; type CDPTreasury = CdpTreasury; - type DEX = Dex; type PriceSource = module_prices::PriorityLockedPriceProvider; type UnsignedPriority = runtime_common::AuctionManagerUnsignedPriority; type EmergencyShutdown = EmergencyShutdown; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = weights::module_auction_manager::WeightInfo; } @@ -1033,7 +1027,6 @@ impl module_cdp_engine::Config for Runtime { type UnsignedPriority = runtime_common::CdpEngineUnsignedPriority; type EmergencyShutdown = EmergencyShutdown; type UnixTime = Timestamp; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = weights::module_cdp_engine::WeightInfo; } @@ -1078,6 +1071,10 @@ impl module_dex::Config for Runtime { parameter_types! { pub const MaxAuctionsCount: u32 = 50; pub HonzonTreasuryAccount: AccountId = HonzonTreasuryPalletId::get().into_account(); + pub AlternativeSwapPathJointList: Vec> = vec![ + vec![KSM], + vec![LKSM], + ]; } impl module_cdp_treasury::Config for Runtime { @@ -1090,6 +1087,7 @@ impl module_cdp_treasury::Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = HonzonTreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = weights::module_cdp_treasury::WeightInfo; } diff --git a/runtime/karura/src/weights/module_honzon.rs b/runtime/karura/src/weights/module_honzon.rs index 28fd6e7578..f0ddef36c1 100644 --- a/runtime/karura/src/weights/module_honzon.rs +++ b/runtime/karura/src/weights/module_honzon.rs @@ -74,16 +74,7 @@ impl module_honzon::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(15 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } - fn close_loan_has_debit_by_dex(u: u32, ) -> Weight { - (337_786_000 as Weight) - // Standard Error: 390_000 - .saturating_add((17_942_000 as Weight).saturating_mul(u as Weight)) - .saturating_add(T::DbWeight::get().reads(22 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(u as Weight))) - .saturating_add(T::DbWeight::get().writes(13 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(u as Weight))) - } - fn close_loan_has_debit_by_dex_no_path() -> Weight { + fn close_loan_has_debit_by_dex() -> Weight { (419_954_000 as Weight) .saturating_add(T::DbWeight::get().reads(31 as Weight)) .saturating_add(T::DbWeight::get().writes(16 as Weight)) diff --git a/runtime/mandala/src/benchmarking/cdp_engine.rs b/runtime/mandala/src/benchmarking/cdp_engine.rs index 727d304a4c..73f000fa7f 100644 --- a/runtime/mandala/src/benchmarking/cdp_engine.rs +++ b/runtime/mandala/src/benchmarking/cdp_engine.rs @@ -18,9 +18,9 @@ use crate::{ dollar, AccountId, Address, Amount, Balance, CdpEngine, CdpTreasury, CollateralCurrencyIds, CurrencyId, - DefaultDebitExchangeRate, DefaultSwapParitalPathList, Dex, EmergencyShutdown, ExistentialDeposits, - GetLiquidCurrencyId, GetStableCurrencyId, GetStakingCurrencyId, MaxAuctionsCount, MinimumDebitValue, Price, Rate, - Ratio, Runtime, Timestamp, MILLISECS_PER_BLOCK, + DefaultDebitExchangeRate, Dex, EmergencyShutdown, ExistentialDeposits, GetLiquidCurrencyId, GetStableCurrencyId, + GetStakingCurrencyId, MaxAuctionsCount, MinimumDebitValue, Price, Rate, Ratio, Runtime, Timestamp, + MILLISECS_PER_BLOCK, }; use super::utils::{feed_price, set_balance}; @@ -187,8 +187,6 @@ runtime_benchmarks! { let owner: AccountId = account("owner", 0, SEED); let owner_lookup = AccountIdLookup::unlookup(owner.clone()); let funder: AccountId = account("funder", 0, SEED); - let mut path: Vec = DefaultSwapParitalPathList::get().last().unwrap().clone(); - let debit_value = 100 * dollar(STABLECOIN); let debit_exchange_rate = CdpEngine::get_debit_exchange_rate(LIQUID); let debit_amount = debit_exchange_rate.reciprocal().unwrap().saturating_mul_int(debit_value); @@ -197,14 +195,8 @@ 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 - path.insert(0, LIQUID); - for i in 0..path.len() { - if i != 0 { - inject_liquidity(funder.clone(), path[i], path[i-1], 10_000 * dollar(path[i]), 10_000 * dollar(path[i-1]))?; - } - } - set_balance(LIQUID, &owner, (10 * collateral_amount) + ExistentialDeposits::get(&LIQUID)); + inject_liquidity(funder, LIQUID, STABLECOIN, 10_000 * dollar(LIQUID), 10_000 * dollar(STABLECOIN))?; // feed price feed_price(vec![(STAKING, collateral_price)])?; diff --git a/runtime/mandala/src/benchmarking/honzon.rs b/runtime/mandala/src/benchmarking/honzon.rs index c2a2d987c8..6b819188df 100644 --- a/runtime/mandala/src/benchmarking/honzon.rs +++ b/runtime/mandala/src/benchmarking/honzon.rs @@ -18,9 +18,8 @@ use crate::{ dollar, AccountId, Amount, Balance, CdpEngine, CollateralCurrencyIds, Currencies, CurrencyId, - DefaultSwapParitalPathList, DepositPerAuthorization, Dex, ExistentialDeposits, GetLiquidCurrencyId, - GetNativeCurrencyId, GetStableCurrencyId, GetStakingCurrencyId, Honzon, Price, Rate, Ratio, Runtime, - TradingPathLimit, + DepositPerAuthorization, Dex, ExistentialDeposits, GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, + GetStakingCurrencyId, Honzon, Price, Rate, Ratio, Runtime, TradingPathLimit, }; use super::utils::{feed_price, set_balance}; @@ -204,69 +203,7 @@ runtime_benchmarks! { }: _(RawOrigin::Signed(receiver), currency_id, sender_lookup) close_loan_has_debit_by_dex { - let u in 2 .. TradingPathLimit::get() as u32; - let currency_id: CurrencyId = CollateralCurrencyIds::get()[0]; - let sender: AccountId = whitelisted_caller(); - let maker: AccountId = account("maker", 0, SEED); - let debit_value = 100 * dollar(STABLECOIN); - let debit_exchange_rate = CdpEngine::get_debit_exchange_rate(currency_id); - let debit_amount = debit_exchange_rate.reciprocal().unwrap().saturating_mul_int(debit_value); - let debit_amount: Amount = debit_amount.unique_saturated_into(); - let collateral_value = 10 * debit_value; - let collateral_amount = Price::saturating_from_rational(dollar(currency_id), dollar(STABLECOIN)).saturating_mul_int(collateral_value); - - // set balance - set_balance(currency_id, &sender, collateral_amount + ExistentialDeposits::get(¤cy_id)); - - let mut path = vec![currency_id]; - for i in 2 .. u { - inject_liquidity( - maker.clone(), - CURRENCY_LIST[i as usize - 2], - *path.last().unwrap(), - 10_000 * dollar(CURRENCY_LIST[i as usize - 2]), - 10_000 * dollar(*path.last().unwrap()), - false, - )?; - path.push(CURRENCY_LIST[i as usize - 2]); - } - inject_liquidity( - maker.clone(), - *path.last().unwrap(), - STABLECOIN, - 10_000 * dollar(*path.last().unwrap()), - debit_value * 100, - false, - )?; - path.push(STABLECOIN); - - // feed price - feed_price(vec![(currency_id, Price::one())])?; - - // set risk params - CdpEngine::set_collateral_params( - RawOrigin::Root.into(), - currency_id, - Change::NoChange, - Change::NewValue(Some(Ratio::saturating_from_rational(150, 100))), - Change::NewValue(Some(Rate::saturating_from_rational(10, 100))), - Change::NewValue(Some(Ratio::saturating_from_rational(150, 100))), - Change::NewValue(debit_value * 100), - )?; - - // initialize sender's loan - Honzon::adjust_loan( - RawOrigin::Signed(sender.clone()).into(), - currency_id, - collateral_amount.try_into().unwrap(), - debit_amount, - )?; - }: _(RawOrigin::Signed(sender), currency_id, collateral_amount, Some(path)) - - close_loan_has_debit_by_dex_no_path { let currency_id: CurrencyId = LIQUID; - let mut default_path: Vec = DefaultSwapParitalPathList::get().last().unwrap().clone(); - let sender: AccountId = whitelisted_caller(); let maker: AccountId = account("maker", 0, SEED); let debit_value = 100 * dollar(STABLECOIN); @@ -275,15 +212,10 @@ runtime_benchmarks! { let debit_amount: Amount = debit_amount.unique_saturated_into(); let collateral_value = 10 * debit_value; let collateral_amount = Price::saturating_from_rational(dollar(currency_id), dollar(STABLECOIN)).saturating_mul_int(collateral_value); - // set balance and trading path - set_balance(currency_id, &sender, (10 * collateral_amount) + ExistentialDeposits::get(¤cy_id)); - default_path.insert(0, currency_id); - for i in 0..default_path.len() { - if i != 0 { - inject_liquidity(maker.clone(), default_path[i], default_path[i-1], 10_000 * dollar(default_path[i]), 10_000 * dollar(default_path[i-1]), false)?; - } - } + // set balance and inject liquidity + set_balance(currency_id, &sender, (10 * collateral_amount) + ExistentialDeposits::get(¤cy_id)); + inject_liquidity(maker.clone(), currency_id, STABLECOIN, 10_000 * dollar(currency_id), 10_000 * dollar(STABLECOIN), false)?; feed_price(vec![(STAKING, Price::one())])?; @@ -306,7 +238,7 @@ runtime_benchmarks! { debit_amount, )?; - }: close_loan_has_debit_by_dex(RawOrigin::Signed(sender), currency_id, collateral_amount, None) + }: _(RawOrigin::Signed(sender), currency_id, collateral_amount) } #[cfg(test)] diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index 01006a9516..f80636a50c 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -934,9 +934,6 @@ parameter_types! { pub MinimumIncrementSize: Rate = Rate::saturating_from_rational(2, 100); pub const AuctionTimeToClose: BlockNumber = 15 * MINUTES; pub const AuctionDurationSoftCap: BlockNumber = 2 * HOURS; - pub DefaultSwapParitalPathList: Vec> = vec![ - vec![GetStableCurrencyId::get()], - ]; } impl module_auction_manager::Config for Runtime { @@ -948,11 +945,9 @@ impl module_auction_manager::Config for Runtime { type AuctionDurationSoftCap = AuctionDurationSoftCap; type GetStableCurrencyId = GetStableCurrencyId; type CDPTreasury = CdpTreasury; - type DEX = Dex; type PriceSource = module_prices::PriorityLockedPriceProvider; type UnsignedPriority = runtime_common::AuctionManagerUnsignedPriority; type EmergencyShutdown = EmergencyShutdown; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = weights::module_auction_manager::WeightInfo; } @@ -1049,7 +1044,6 @@ impl module_cdp_engine::Config for Runtime { type UnsignedPriority = runtime_common::CdpEngineUnsignedPriority; type EmergencyShutdown = EmergencyShutdown; type UnixTime = Timestamp; - type DefaultSwapParitalPathList = DefaultSwapParitalPathList; type WeightInfo = weights::module_cdp_engine::WeightInfo; } @@ -1100,6 +1094,7 @@ impl module_dex::Config for Runtime { parameter_types! { pub const MaxAuctionsCount: u32 = 50; pub HonzonTreasuryAccount: AccountId = HonzonTreasuryPalletId::get().into_account(); + pub AlternativeSwapPathJointList: Vec> = vec![]; } impl module_cdp_treasury::Config for Runtime { @@ -1112,6 +1107,7 @@ impl module_cdp_treasury::Config for Runtime { type MaxAuctionsCount = MaxAuctionsCount; type PalletId = CDPTreasuryPalletId; type TreasuryAccount = HonzonTreasuryAccount; + type AlternativeSwapPathJointList = AlternativeSwapPathJointList; type WeightInfo = weights::module_cdp_treasury::WeightInfo; } diff --git a/runtime/mandala/src/weights/module_honzon.rs b/runtime/mandala/src/weights/module_honzon.rs index 16e306482c..c9eaa50f39 100644 --- a/runtime/mandala/src/weights/module_honzon.rs +++ b/runtime/mandala/src/weights/module_honzon.rs @@ -74,16 +74,7 @@ impl module_honzon::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(21 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } - fn close_loan_has_debit_by_dex(u: u32, ) -> Weight { - (370_110_000 as Weight) - // Standard Error: 16_001_000 - .saturating_add((15_535_000 as Weight).saturating_mul(u as Weight)) - .saturating_add(T::DbWeight::get().reads(26 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(u as Weight))) - .saturating_add(T::DbWeight::get().writes(12 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(u as Weight))) - } - fn close_loan_has_debit_by_dex_no_path() -> Weight { + fn close_loan_has_debit_by_dex() -> Weight { (385_507_000 as Weight) .saturating_add(T::DbWeight::get().reads(32 as Weight)) .saturating_add(T::DbWeight::get().writes(14 as Weight)) From 4724ccf4cd22491592166a4969a6e7776bcaf950 Mon Sep 17 00:00:00 2001 From: wangjj9219 <183318287@qq.com> Date: Thu, 16 Dec 2021 00:40:34 +0800 Subject: [PATCH 02/10] update --- modules/cdp-treasury/src/lib.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/modules/cdp-treasury/src/lib.rs b/modules/cdp-treasury/src/lib.rs index 5a0b82ecb1..8e99fb303e 100644 --- a/modules/cdp-treasury/src/lib.rs +++ b/modules/cdp-treasury/src/lib.rs @@ -86,9 +86,8 @@ pub mod module { #[pallet::constant] type PalletId: Get; - /// The default parital path list for DEX to directly take auction, - /// Note: the path is parital, the whole swap path is collateral currency id concat - /// the partial path. And the list is sorted, DEX try to take auction by order. + /// The alternative swap path joint list, which can be concated to + /// alternative swap path when cdp treasury swap collateral to stable. #[pallet::constant] type AlternativeSwapPathJointList: Get>>; From 9c51477a7117e9f8bacd02bed839c0accdffe6e7 Mon Sep 17 00:00:00 2001 From: wangjj9219 <183318287@qq.com> Date: Fri, 17 Dec 2021 13:53:11 +0800 Subject: [PATCH 03/10] update --- modules/cdp-engine/src/lib.rs | 6 +----- modules/cdp-engine/src/tests.rs | 2 +- modules/cdp-treasury/src/lib.rs | 6 +++--- modules/cdp-treasury/src/tests.rs | 4 ++-- .../mandala/src/benchmarking/cdp_engine.rs | 3 ++- runtime/mandala/src/benchmarking/honzon.rs | 20 +++++++++---------- runtime/mandala/src/lib.rs | 2 +- 7 files changed, 19 insertions(+), 24 deletions(-) diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 48944efc80..f534435b35 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -219,8 +219,6 @@ pub mod module { AlreadyShutdown, /// Must after system shutdown MustAfterShutdown, - /// Failed to swap debit by default path list - SwapDebitFailed, } #[pallet::event] @@ -831,13 +829,11 @@ impl Pallet { let debit_value = Self::get_debit_value(currency_id, debit); let collateral_supply = collateral.min(max_collateral_amount); - // if specify swap path let (actual_supply_collateral, _) = ::CDPTreasury::swap_collateral_to_stable( currency_id, SwapLimit::ExactTarget(collateral_supply, debit_value), false, - ) - .map_err(|_| Error::::SwapDebitFailed)?; + )?; // refund remain collateral to CDP owner let refund_collateral_amount = collateral diff --git a/modules/cdp-engine/src/tests.rs b/modules/cdp-engine/src/tests.rs index a1e07bcef7..59113dc012 100644 --- a/modules/cdp-engine/src/tests.rs +++ b/modules/cdp-engine/src/tests.rs @@ -858,7 +858,7 @@ fn close_cdp_has_debit_by_dex_work() { // max collateral amount limit swap assert_noop!( CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 5), - Error::::SwapDebitFailed + cdp_treasury::Error::::CannotSwap, ); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (100, 1000)); diff --git a/modules/cdp-treasury/src/lib.rs b/modules/cdp-treasury/src/lib.rs index 8e99fb303e..a534631a1b 100644 --- a/modules/cdp-treasury/src/lib.rs +++ b/modules/cdp-treasury/src/lib.rs @@ -103,8 +103,8 @@ pub mod module { SurplusPoolNotEnough, /// The debit pool of CDP treasury is not enough DebitPoolNotEnough, - /// There's no swap path for collateral to swap stable - NoSwapPath, + /// Cannot use collateral to swap stable + CannotSwap, } #[pallet::event] @@ -353,7 +353,7 @@ impl CDPTreasuryExtended for Pallet { limit, T::AlternativeSwapPathJointList::get(), ) - .ok_or(Error::::NoSwapPath)?; + .ok_or(Error::::CannotSwap)?; T::DEX::swap_with_specific_path(&Self::account_id(), &swap_path, limit) } diff --git a/modules/cdp-treasury/src/tests.rs b/modules/cdp-treasury/src/tests.rs index bc8de40b05..e1976e14c2 100644 --- a/modules/cdp-treasury/src/tests.rs +++ b/modules/cdp-treasury/src/tests.rs @@ -215,7 +215,7 @@ fn swap_collateral_to_stable_work() { assert_noop!( CDPTreasuryModule::swap_collateral_to_stable(BTC, SwapLimit::ExactTarget(200, 399), false), - Error::::NoSwapPath + Error::::CannotSwap ); assert_ok!(DEXModule::add_liquidity( Origin::signed(ALICE), @@ -236,7 +236,7 @@ fn swap_collateral_to_stable_work() { assert_noop!( CDPTreasuryModule::swap_collateral_to_stable(DOT, SwapLimit::ExactSupply(1000, 1000), false), - Error::::NoSwapPath, + Error::::CannotSwap, ); assert_eq!( diff --git a/runtime/mandala/src/benchmarking/cdp_engine.rs b/runtime/mandala/src/benchmarking/cdp_engine.rs index 73f000fa7f..3094e50596 100644 --- a/runtime/mandala/src/benchmarking/cdp_engine.rs +++ b/runtime/mandala/src/benchmarking/cdp_engine.rs @@ -196,7 +196,8 @@ runtime_benchmarks! { let collateral_price = Price::one(); // 1 USD set_balance(LIQUID, &owner, (10 * collateral_amount) + ExistentialDeposits::get(&LIQUID)); - inject_liquidity(funder, LIQUID, STABLECOIN, 10_000 * dollar(LIQUID), 10_000 * dollar(STABLECOIN))?; + 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))?; // feed price feed_price(vec![(STAKING, collateral_price)])?; diff --git a/runtime/mandala/src/benchmarking/honzon.rs b/runtime/mandala/src/benchmarking/honzon.rs index 6b819188df..4c1ec5df20 100644 --- a/runtime/mandala/src/benchmarking/honzon.rs +++ b/runtime/mandala/src/benchmarking/honzon.rs @@ -19,7 +19,7 @@ use crate::{ dollar, AccountId, Amount, Balance, CdpEngine, CollateralCurrencyIds, Currencies, CurrencyId, DepositPerAuthorization, Dex, ExistentialDeposits, GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, - GetStakingCurrencyId, Honzon, Price, Rate, Ratio, Runtime, TradingPathLimit, + GetStakingCurrencyId, Honzon, Price, Rate, Ratio, Runtime, }; use super::utils::{feed_price, set_balance}; @@ -27,7 +27,6 @@ use frame_benchmarking::{account, whitelisted_caller}; use frame_system::RawOrigin; use orml_benchmarking::runtime_benchmarks; use orml_traits::{Change, GetByKey, MultiCurrencyExtended}; -use runtime_common::{BNC, RENBTC, VSKSM}; use sp_runtime::{ traits::{AccountIdLookup, One, StaticLookup, UniqueSaturatedInto}, FixedPointNumber, @@ -41,8 +40,6 @@ const STABLECOIN: CurrencyId = GetStableCurrencyId::get(); const STAKING: CurrencyId = GetStakingCurrencyId::get(); const LIQUID: CurrencyId = GetLiquidCurrencyId::get(); -const CURRENCY_LIST: [CurrencyId; 5] = [NATIVE, LIQUID, BNC, VSKSM, RENBTC]; - fn inject_liquidity( maker: AccountId, currency_id_a: CurrencyId, @@ -207,22 +204,23 @@ runtime_benchmarks! { let sender: AccountId = whitelisted_caller(); let maker: AccountId = account("maker", 0, SEED); let debit_value = 100 * dollar(STABLECOIN); - let debit_exchange_rate = CdpEngine::get_debit_exchange_rate(currency_id); + let debit_exchange_rate = CdpEngine::get_debit_exchange_rate(LIQUID); let debit_amount = debit_exchange_rate.reciprocal().unwrap().saturating_mul_int(debit_value); let debit_amount: Amount = debit_amount.unique_saturated_into(); let collateral_value = 10 * debit_value; - let collateral_amount = Price::saturating_from_rational(dollar(currency_id), dollar(STABLECOIN)).saturating_mul_int(collateral_value); + let collateral_amount = Price::saturating_from_rational(dollar(LIQUID), dollar(STABLECOIN)).saturating_mul_int(collateral_value); // set balance and inject liquidity - set_balance(currency_id, &sender, (10 * collateral_amount) + ExistentialDeposits::get(¤cy_id)); - inject_liquidity(maker.clone(), currency_id, STABLECOIN, 10_000 * dollar(currency_id), 10_000 * dollar(STABLECOIN), false)?; + set_balance(LIQUID, &sender, (10 * collateral_amount) + ExistentialDeposits::get(&LIQUID)); + inject_liquidity(maker.clone(), LIQUID, STAKING, 10_000 * dollar(LIQUID), 10_000 * dollar(STAKING), false)?; + inject_liquidity(maker, STAKING, STABLECOIN, 10_000 * dollar(STAKING), 10_000 * dollar(STABLECOIN), false)?; feed_price(vec![(STAKING, Price::one())])?; // set risk params CdpEngine::set_collateral_params( RawOrigin::Root.into(), - currency_id, + LIQUID, Change::NoChange, Change::NewValue(Some(Ratio::saturating_from_rational(150, 100))), Change::NewValue(Some(Rate::saturating_from_rational(10, 100))), @@ -233,12 +231,12 @@ runtime_benchmarks! { // initialize sender's loan Honzon::adjust_loan( RawOrigin::Signed(sender.clone()).into(), - currency_id, + LIQUID, (10 * collateral_amount).try_into().unwrap(), debit_amount, )?; - }: _(RawOrigin::Signed(sender), currency_id, collateral_amount) + }: _(RawOrigin::Signed(sender), LIQUID, collateral_amount) } #[cfg(test)] diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index f80636a50c..b2a8fc1100 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -1094,7 +1094,7 @@ impl module_dex::Config for Runtime { parameter_types! { pub const MaxAuctionsCount: u32 = 50; pub HonzonTreasuryAccount: AccountId = HonzonTreasuryPalletId::get().into_account(); - pub AlternativeSwapPathJointList: Vec> = vec![]; + pub AlternativeSwapPathJointList: Vec> = vec![vec![GetStakingCurrencyId::get()]]; } impl module_cdp_treasury::Config for Runtime { From e8f7883fd5745f094850c4d80def23dd7e02833d Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Fri, 17 Dec 2021 06:10:23 +0000 Subject: [PATCH 04/10] cargo run --release --color=never --bin=acala --features=runtime-benchmarks --features=with-acala-runtime -- benchmark --chain=acala-latest --steps=50 --repeat=20 --pallet=module_honzon --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_honzon.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/runtime/acala/src/weights/module_honzon.rs b/runtime/acala/src/weights/module_honzon.rs index a829b20761..21ffdb6239 100644 --- a/runtime/acala/src/weights/module_honzon.rs +++ b/runtime/acala/src/weights/module_honzon.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for module_honzon //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-10, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-17, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("acala-latest"), DB CACHE: 128 // Executed Command: @@ -36,7 +36,6 @@ // --template=./templates/runtime-weight-template.hbs // --output=./runtime/acala/src/weights/ - #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] @@ -48,34 +47,34 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl module_honzon::WeightInfo for WeightInfo { fn authorize() -> Weight { - (53_777_000 as Weight) + (56_967_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } fn unauthorize() -> Weight { - (56_016_000 as Weight) + (58_393_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } fn unauthorize_all(c: u32, ) -> Weight { - (28_455_000 as Weight) - // Standard Error: 109_000 - .saturating_add((31_156_000 as Weight).saturating_mul(c as Weight)) + (29_024_000 as Weight) + // Standard Error: 159_000 + .saturating_add((32_836_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) } fn adjust_loan() -> Weight { - (256_082_000 as Weight) + (256_781_000 as Weight) .saturating_add(T::DbWeight::get().reads(24 as Weight)) .saturating_add(T::DbWeight::get().writes(11 as Weight)) } fn transfer_loan_from() -> Weight { - (153_284_000 as Weight) + (152_977_000 as Weight) .saturating_add(T::DbWeight::get().reads(15 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } fn close_loan_has_debit_by_dex() -> Weight { - (396_996_000 as Weight) + (419_711_000 as Weight) .saturating_add(T::DbWeight::get().reads(29 as Weight)) .saturating_add(T::DbWeight::get().writes(15 as Weight)) } From 761f2d1a21cd7a6b453f4dd499718dac6f4cd2a0 Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Fri, 17 Dec 2021 06:23:52 +0000 Subject: [PATCH 05/10] cargo run --release --color=never --bin=acala --features=runtime-benchmarks --features=with-karura-runtime -- benchmark --chain=karura-dev --steps=50 --repeat=20 --pallet=module_honzon --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_honzon.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/runtime/karura/src/weights/module_honzon.rs b/runtime/karura/src/weights/module_honzon.rs index f0ddef36c1..e4d51d3e2e 100644 --- a/runtime/karura/src/weights/module_honzon.rs +++ b/runtime/karura/src/weights/module_honzon.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for module_honzon //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-10, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-17, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("karura-dev"), DB CACHE: 128 // Executed Command: @@ -36,7 +36,6 @@ // --template=./templates/runtime-weight-template.hbs // --output=./runtime/karura/src/weights/ - #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] @@ -48,34 +47,34 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl module_honzon::WeightInfo for WeightInfo { fn authorize() -> Weight { - (51_462_000 as Weight) + (52_346_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } fn unauthorize() -> Weight { - (53_632_000 as Weight) + (53_729_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } fn unauthorize_all(c: u32, ) -> Weight { - (26_878_000 as Weight) - // Standard Error: 113_000 - .saturating_add((30_194_000 as Weight).saturating_mul(c as Weight)) + (31_703_000 as Weight) + // Standard Error: 1_461_000 + .saturating_add((16_116_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) } fn adjust_loan() -> Weight { - (250_173_000 as Weight) + (445_526_000 as Weight) .saturating_add(T::DbWeight::get().reads(24 as Weight)) .saturating_add(T::DbWeight::get().writes(11 as Weight)) } fn transfer_loan_from() -> Weight { - (142_636_000 as Weight) + (140_062_000 as Weight) .saturating_add(T::DbWeight::get().reads(15 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } fn close_loan_has_debit_by_dex() -> Weight { - (419_954_000 as Weight) + (422_166_000 as Weight) .saturating_add(T::DbWeight::get().reads(31 as Weight)) .saturating_add(T::DbWeight::get().writes(16 as Weight)) } From 8326c308a463047c5516bd6560b0bd262af606d7 Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Fri, 17 Dec 2021 06:33:23 +0000 Subject: [PATCH 06/10] cargo run --release --color=never --bin=acala --features=runtime-benchmarks --features=with-mandala-runtime -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=module_honzon --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_honzon.rs | 27 ++++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/runtime/mandala/src/weights/module_honzon.rs b/runtime/mandala/src/weights/module_honzon.rs index c9eaa50f39..535ba81347 100644 --- a/runtime/mandala/src/weights/module_honzon.rs +++ b/runtime/mandala/src/weights/module_honzon.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for module_honzon //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-10, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-17, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 // Executed Command: @@ -36,7 +36,6 @@ // --template=./templates/runtime-weight-template.hbs // --output=./runtime/mandala/src/weights/ - #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] @@ -48,35 +47,35 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl module_honzon::WeightInfo for WeightInfo { fn authorize() -> Weight { - (54_304_000 as Weight) + (52_407_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } fn unauthorize() -> Weight { - (55_756_000 as Weight) + (54_414_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } fn unauthorize_all(c: u32, ) -> Weight { - (33_131_000 as Weight) - // Standard Error: 1_556_000 - .saturating_add((16_829_000 as Weight).saturating_mul(c as Weight)) + (31_904_000 as Weight) + // Standard Error: 1_582_000 + .saturating_add((16_667_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) } fn adjust_loan() -> Weight { - (254_592_000 as Weight) - .saturating_add(T::DbWeight::get().reads(26 as Weight)) + (220_676_000 as Weight) + .saturating_add(T::DbWeight::get().reads(21 as Weight)) .saturating_add(T::DbWeight::get().writes(11 as Weight)) } fn transfer_loan_from() -> Weight { - (168_398_000 as Weight) - .saturating_add(T::DbWeight::get().reads(21 as Weight)) + (140_250_000 as Weight) + .saturating_add(T::DbWeight::get().reads(15 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } fn close_loan_has_debit_by_dex() -> Weight { - (385_507_000 as Weight) - .saturating_add(T::DbWeight::get().reads(32 as Weight)) - .saturating_add(T::DbWeight::get().writes(14 as Weight)) + (385_594_000 as Weight) + .saturating_add(T::DbWeight::get().reads(30 as Weight)) + .saturating_add(T::DbWeight::get().writes(15 as Weight)) } } From 0ac85999e759d9bc19b22a8c2ef393393b810aa5 Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Fri, 17 Dec 2021 06:39:51 +0000 Subject: [PATCH 07/10] cargo run --release --color=never --bin=acala --features=runtime-benchmarks --features=with-acala-runtime -- benchmark --chain=acala-latest --steps=50 --repeat=20 --pallet=module_cdp_engine --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --template=./templates/runtime-weight-template.hbs --output=./runtime/acala/src/weights/ --- .../acala/src/weights/module_cdp_engine.rs | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/runtime/acala/src/weights/module_cdp_engine.rs b/runtime/acala/src/weights/module_cdp_engine.rs index 9374e5780b..fdf308dc9f 100644 --- a/runtime/acala/src/weights/module_cdp_engine.rs +++ b/runtime/acala/src/weights/module_cdp_engine.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for module_cdp_engine //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-16, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-17, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("acala-latest"), DB CACHE: 128 // Executed Command: @@ -36,7 +36,6 @@ // --template=./templates/runtime-weight-template.hbs // --output=./runtime/acala/src/weights/ - #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] @@ -48,36 +47,36 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl module_cdp_engine::WeightInfo for WeightInfo { fn on_initialize(c: u32, ) -> Weight { - (34_203_000 as Weight) - // Standard Error: 88_000 - .saturating_add((4_625_000 as Weight).saturating_mul(c as Weight)) + (32_772_000 as Weight) + // Standard Error: 304_000 + .saturating_add((4_915_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } fn set_collateral_params() -> Weight { - (56_501_000 as Weight) + (55_923_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } fn set_global_params() -> Weight { - (19_612_000 as Weight) + (19_010_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } fn liquidate_by_auction(b: u32, ) -> Weight { - (275_714_000 as Weight) - // Standard Error: 118_000 - .saturating_add((30_172_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(22 as Weight)) + (264_886_000 as Weight) + // Standard Error: 53_000 + .saturating_add((27_918_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().reads(23 as Weight)) .saturating_add(T::DbWeight::get().writes(15 as Weight)) .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(b as Weight))) } fn liquidate_by_dex() -> Weight { - (428_772_000 as Weight) + (415_605_000 as Weight) .saturating_add(T::DbWeight::get().reads(30 as Weight)) .saturating_add(T::DbWeight::get().writes(16 as Weight)) } fn settle() -> Weight { - (170_663_000 as Weight) + (165_954_000 as Weight) .saturating_add(T::DbWeight::get().reads(13 as Weight)) .saturating_add(T::DbWeight::get().writes(8 as Weight)) } From 55c6c8da60a67b8b4916f5c4a905c32c49fa4922 Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Fri, 17 Dec 2021 06:56:38 +0000 Subject: [PATCH 08/10] cargo run --release --color=never --bin=acala --features=runtime-benchmarks --features=with-karura-runtime -- benchmark --chain=karura-dev --steps=50 --repeat=20 --pallet=module_cdp_engine --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --template=./templates/runtime-weight-template.hbs --output=./runtime/karura/src/weights/ --- .../karura/src/weights/module_cdp_engine.rs | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/runtime/karura/src/weights/module_cdp_engine.rs b/runtime/karura/src/weights/module_cdp_engine.rs index ba8f582b3b..0f38210423 100644 --- a/runtime/karura/src/weights/module_cdp_engine.rs +++ b/runtime/karura/src/weights/module_cdp_engine.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for module_cdp_engine //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-16, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-17, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("karura-dev"), DB CACHE: 128 // Executed Command: @@ -36,7 +36,6 @@ // --template=./templates/runtime-weight-template.hbs // --output=./runtime/karura/src/weights/ - #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] @@ -48,36 +47,36 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl module_cdp_engine::WeightInfo for WeightInfo { fn on_initialize(c: u32, ) -> Weight { - (31_633_000 as Weight) - // Standard Error: 42_000 - .saturating_add((3_968_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) + (39_130_000 as Weight) + // Standard Error: 131_000 + .saturating_add((4_457_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(9 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } fn set_collateral_params() -> Weight { - (54_999_000 as Weight) + (56_905_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } fn set_global_params() -> Weight { - (18_644_000 as Weight) + (18_526_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } fn liquidate_by_auction(b: u32, ) -> Weight { - (268_468_000 as Weight) - // Standard Error: 50_000 - .saturating_add((30_206_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(24 as Weight)) + (295_131_000 as Weight) + // Standard Error: 177_000 + .saturating_add((28_136_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().reads(25 as Weight)) .saturating_add(T::DbWeight::get().writes(16 as Weight)) .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(b as Weight))) } fn liquidate_by_dex() -> Weight { - (432_287_000 as Weight) + (436_708_000 as Weight) .saturating_add(T::DbWeight::get().reads(32 as Weight)) .saturating_add(T::DbWeight::get().writes(17 as Weight)) } fn settle() -> Weight { - (157_473_000 as Weight) + (155_126_000 as Weight) .saturating_add(T::DbWeight::get().reads(13 as Weight)) .saturating_add(T::DbWeight::get().writes(8 as Weight)) } From 264fe6a28c267d860392c136d5c26d1b503a1070 Mon Sep 17 00:00:00 2001 From: Acala Benchmarking Bot Date: Fri, 17 Dec 2021 07:02:09 +0000 Subject: [PATCH 09/10] cargo run --release --color=never --bin=acala --features=runtime-benchmarks --features=with-mandala-runtime -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=module_cdp_engine --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --template=./templates/runtime-weight-template.hbs --output=./runtime/mandala/src/weights/ --- .../mandala/src/weights/module_cdp_engine.rs | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/runtime/mandala/src/weights/module_cdp_engine.rs b/runtime/mandala/src/weights/module_cdp_engine.rs index ab9558c201..3442cabf7a 100644 --- a/runtime/mandala/src/weights/module_cdp_engine.rs +++ b/runtime/mandala/src/weights/module_cdp_engine.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for module_cdp_engine //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-16, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-17, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 // Executed Command: @@ -36,7 +36,6 @@ // --template=./templates/runtime-weight-template.hbs // --output=./runtime/mandala/src/weights/ - #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] @@ -48,38 +47,38 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl module_cdp_engine::WeightInfo for WeightInfo { fn on_initialize(c: u32, ) -> Weight { - (48_807_000 as Weight) - // Standard Error: 1_035_000 - .saturating_add((46_350_000 as Weight).saturating_mul(c as Weight)) + (48_181_000 as Weight) + // Standard Error: 991_000 + .saturating_add((46_210_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(9 as Weight)) .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) } fn set_collateral_params() -> Weight { - (56_882_000 as Weight) + (57_130_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } fn set_global_params() -> Weight { - (19_257_000 as Weight) + (19_644_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } fn liquidate_by_auction(b: u32, ) -> Weight { - (233_927_000 as Weight) - // Standard Error: 161_000 - .saturating_add((30_664_000 as Weight).saturating_mul(b as Weight)) + (295_312_000 as Weight) + // Standard Error: 170_000 + .saturating_add((27_764_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(23 as Weight)) .saturating_add(T::DbWeight::get().writes(15 as Weight)) .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(b as Weight))) } fn liquidate_by_dex() -> Weight { - (381_589_000 as Weight) - .saturating_add(T::DbWeight::get().reads(27 as Weight)) - .saturating_add(T::DbWeight::get().writes(15 as Weight)) + (408_674_000 as Weight) + .saturating_add(T::DbWeight::get().reads(31 as Weight)) + .saturating_add(T::DbWeight::get().writes(16 as Weight)) } fn settle() -> Weight { - (162_567_000 as Weight) + (160_596_000 as Weight) .saturating_add(T::DbWeight::get().reads(13 as Weight)) .saturating_add(T::DbWeight::get().writes(8 as Weight)) } From 68a9d2b5a4519f62202f188adb849b5ceafea2b3 Mon Sep 17 00:00:00 2001 From: wangjj9219 <183318287@qq.com> Date: Sat, 18 Dec 2021 13:18:00 +0800 Subject: [PATCH 10/10] update --- modules/dex/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/dex/src/lib.rs b/modules/dex/src/lib.rs index 7b94ec8ad9..229e166c45 100644 --- a/modules/dex/src/lib.rs +++ b/modules/dex/src/lib.rs @@ -1269,13 +1269,13 @@ impl DEXManager for Pallet { let mut swap_path = vec![]; if supply_currency_id != path_joint[0] { - swap_path.extend(vec![supply_currency_id]); + swap_path.push(supply_currency_id); } swap_path.extend(path_joint.clone()); if target_currency_id != path_joint[path_joint.len() - 1] { - swap_path.extend(vec![target_currency_id]); + swap_path.push(target_currency_id); } if let Some((supply_amount, target_amount)) = Self::get_swap_amount(&swap_path, limit) {