diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 03ccd47743..04401ef8ae 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -129,10 +129,6 @@ pub mod module { /// always do this. type UpdateOrigin: EnsureOrigin; - /// The list of valid collateral currency types - #[pallet::constant] - type CollateralCurrencyIds: Get>; - /// The default liquidation ratio for all collateral types of CDP #[pallet::constant] type DefaultLiquidationRatio: Get; @@ -293,12 +289,12 @@ pub mod module { #[pallet::getter(fn debit_exchange_rate)] pub type DebitExchangeRate = StorageMap<_, Twox64Concat, CurrencyId, ExchangeRate, OptionQuery>; - /// Mapping from collateral type to its risk management params + /// Mapping from valid collateral type to its risk management params /// - /// CollateralParams: CurrencyId => RiskManagementParams + /// CollateralParams: CurrencyId => Option #[pallet::storage] #[pallet::getter(fn collateral_params)] - pub type CollateralParams = StorageMap<_, Twox64Concat, CurrencyId, RiskManagementParams, ValueQuery>; + pub type CollateralParams = StorageMap<_, Twox64Concat, CurrencyId, RiskManagementParams, OptionQuery>; /// Timestamp in seconds of the last interest accumulation /// @@ -438,8 +434,7 @@ pub mod module { /// The dispatch origin of this call must be `UpdateOrigin`. /// /// - `currency_id`: collateral type. - /// - `interest_rate_per_sec`: extra interest rate per sec, `None` means do not update, - /// `Some(None)` means update it to `None`. + /// - `interest_rate_per_sec`: Interest rate per sec, `None` means do not update, /// - `liquidation_ratio`: liquidation ratio, `None` means do not update, `Some(None)` means /// update it to `None`. /// - `liquidation_penalty`: liquidation penalty, `None` means do not update, `Some(None)` @@ -459,12 +454,8 @@ pub mod module { maximum_total_debit_value: ChangeBalance, ) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; - ensure!( - T::CollateralCurrencyIds::get().contains(¤cy_id), - Error::::InvalidCollateralType, - ); - let mut collateral_params = Self::collateral_params(currency_id); + let mut collateral_params = Self::collateral_params(currency_id).unwrap_or_default(); if let Change::NewValue(update) = interest_rate_per_sec { collateral_params.interest_rate_per_sec = update; Self::deposit_event(Event::InterestRatePerSecUpdated { @@ -556,7 +547,7 @@ impl Pallet { if !T::EmergencyShutdown::is_shutdown() && !now_secs.is_zero() { let interval_secs = now_secs.saturating_sub(last_accumulation_secs); - for currency_id in T::CollateralCurrencyIds::get() { + for currency_id in Self::get_collateral_currency_ids() { if let Ok(interest_rate) = Self::get_interest_rate_per_sec(currency_id) { let rate_to_accumulate = Self::compound_interest_rate(interest_rate, interval_secs); let total_debits = >::total_positions(currency_id).debit; @@ -626,7 +617,7 @@ impl Pallet { } fn _offchain_worker() -> Result<(), OffchainErr> { - let collateral_currency_ids = T::CollateralCurrencyIds::get(); + let collateral_currency_ids = Self::get_collateral_currency_ids(); if collateral_currency_ids.len().is_zero() { return Ok(()); } @@ -733,26 +724,34 @@ impl Pallet { if let Some(feed_price) = T::PriceSource::get_relative_price(currency_id, stable_currency_id) { let collateral_ratio = Self::calculate_collateral_ratio(currency_id, collateral_amount, debit_amount, feed_price); - if collateral_ratio < Self::get_liquidation_ratio(currency_id) { - CDPStatus::Unsafe - } else { - CDPStatus::Safe + match Self::get_liquidation_ratio(currency_id) { + Ok(liquidation_ratio) => { + if collateral_ratio < liquidation_ratio { + CDPStatus::Unsafe + } else { + CDPStatus::Safe + } + } + Err(e) => CDPStatus::ChecksFailed(e), } } else { CDPStatus::ChecksFailed(Error::::InvalidFeedPrice.into()) } } - pub fn maximum_total_debit_value(currency_id: CurrencyId) -> Balance { - Self::collateral_params(currency_id).maximum_total_debit_value + pub fn maximum_total_debit_value(currency_id: CurrencyId) -> Result { + let params = Self::collateral_params(currency_id).ok_or(Error::::InvalidCollateralType)?; + Ok(params.maximum_total_debit_value) } - pub fn required_collateral_ratio(currency_id: CurrencyId) -> Option { - Self::collateral_params(currency_id).required_collateral_ratio + pub fn required_collateral_ratio(currency_id: CurrencyId) -> Result, DispatchError> { + let params = Self::collateral_params(currency_id).ok_or(Error::::InvalidCollateralType)?; + Ok(params.required_collateral_ratio) } pub fn get_interest_rate_per_sec(currency_id: CurrencyId) -> Result { - Self::collateral_params(currency_id) + let params = Self::collateral_params(currency_id).ok_or(Error::::InvalidCollateralType)?; + params .interest_rate_per_sec .ok_or_else(|| Error::::InvalidCollateralType.into()) } @@ -764,16 +763,16 @@ impl Pallet { .saturating_sub(Rate::one()) } - pub fn get_liquidation_ratio(currency_id: CurrencyId) -> Ratio { - Self::collateral_params(currency_id) - .liquidation_ratio - .unwrap_or_else(T::DefaultLiquidationRatio::get) + pub fn get_liquidation_ratio(currency_id: CurrencyId) -> Result { + let params = Self::collateral_params(currency_id).ok_or(Error::::InvalidCollateralType)?; + Ok(params.liquidation_ratio.unwrap_or_else(T::DefaultLiquidationRatio::get)) } - pub fn get_liquidation_penalty(currency_id: CurrencyId) -> Rate { - Self::collateral_params(currency_id) + pub fn get_liquidation_penalty(currency_id: CurrencyId) -> Result { + let params = Self::collateral_params(currency_id).ok_or(Error::::InvalidCollateralType)?; + Ok(params .liquidation_penalty - .unwrap_or_else(T::DefaultLiquidationPenalty::get) + .unwrap_or_else(T::DefaultLiquidationPenalty::get)) } pub fn get_debit_exchange_rate(currency_id: CurrencyId) -> ExchangeRate { @@ -809,7 +808,7 @@ impl Pallet { debit_adjustment: Amount, ) -> DispatchResult { ensure!( - T::CollateralCurrencyIds::get().contains(¤cy_id), + CollateralParams::::contains_key(¤cy_id), Error::::InvalidCollateralType, ); >::adjust_position(who, currency_id, collateral_adjustment, debit_adjustment)?; @@ -829,7 +828,7 @@ impl Pallet { min_increase_collateral: Balance, ) -> DispatchResult { ensure!( - T::CollateralCurrencyIds::get().contains(¤cy_id), + CollateralParams::::contains_key(¤cy_id), Error::::InvalidCollateralType, ); let loans_module_account = >::account_id(); @@ -938,7 +937,7 @@ impl Pallet { min_decrease_debit_value: Balance, ) -> DispatchResult { ensure!( - T::CollateralCurrencyIds::get().contains(¤cy_id), + CollateralParams::::contains_key(¤cy_id), Error::::InvalidCollateralType, ); @@ -1133,7 +1132,8 @@ impl Pallet { >::confiscate_collateral_and_debit(&who, currency_id, collateral, debit)?; 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_penalty = Self::get_liquidation_penalty(currency_id)?; + let target_stable_amount = liquidation_penalty.saturating_mul_acc_int(bad_debt_value); match currency_id { CurrencyId::DexShare(dex_share_0, dex_share_1) => { @@ -1253,6 +1253,9 @@ impl Pallet { Ok(()) } + pub fn get_collateral_currency_ids() -> Vec { + CollateralParams::::iter_keys().collect() + } } impl RiskManager for Pallet { @@ -1275,7 +1278,7 @@ impl RiskManager for Pall // check the required collateral ratio if check_required_ratio { - if let Some(required_collateral_ratio) = Self::required_collateral_ratio(currency_id) { + if let Some(required_collateral_ratio) = Self::required_collateral_ratio(currency_id)? { ensure!( collateral_ratio >= required_collateral_ratio, Error::::BelowRequiredCollateralRatio @@ -1284,10 +1287,8 @@ impl RiskManager for Pall } // check the liquidation ratio - ensure!( - collateral_ratio >= Self::get_liquidation_ratio(currency_id), - Error::::BelowLiquidationRatio - ); + let liquidation_ratio = Self::get_liquidation_ratio(currency_id)?; + ensure!(collateral_ratio >= liquidation_ratio, Error::::BelowLiquidationRatio); // check the minimum_debit_value ensure!( @@ -1306,15 +1307,23 @@ impl RiskManager for Pall } fn check_debit_cap(currency_id: CurrencyId, total_debit_balance: Balance) -> DispatchResult { - let hard_cap = Self::maximum_total_debit_value(currency_id); + let hard_cap = Self::maximum_total_debit_value(currency_id)?; let total_debit_value = Self::get_debit_value(currency_id, total_debit_balance); - ensure!(total_debit_value <= hard_cap, Error::::ExceedDebitValueHardCap,); + ensure!(total_debit_value <= hard_cap, Error::::ExceedDebitValueHardCap); Ok(()) } } +pub struct CollateralCurrencyIds(PhantomData); +// Returns a list of currently supported/configured collateral currency +impl Get> for CollateralCurrencyIds { + fn get() -> Vec { + Pallet::::get_collateral_currency_ids() + } +} + /// Pick a new PRN, in the range [0, `max`) (exclusive). fn pick_u32(rng: &mut R, max: u32) -> u32 { rng.next_u32() % max diff --git a/modules/cdp-engine/src/mock.rs b/modules/cdp-engine/src/mock.rs index c4a5b9883d..1df7e596b8 100644 --- a/modules/cdp-engine/src/mock.rs +++ b/modules/cdp-engine/src/mock.rs @@ -302,13 +302,11 @@ parameter_types! { pub DefaultDebitExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10); pub DefaultLiquidationPenalty: Rate = Rate::saturating_from_rational(10, 100); pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(50, 100); - pub CollateralCurrencyIds: Vec = vec![BTC, DOT, LP_AUSD_DOT]; } impl Config for Runtime { type Event = Event; type PriceSource = MockPriceSource; - type CollateralCurrencyIds = CollateralCurrencyIds; type DefaultLiquidationRatio = DefaultLiquidationRatio; type DefaultDebitExchangeRate = DefaultDebitExchangeRate; type DefaultLiquidationPenalty = DefaultLiquidationPenalty; diff --git a/modules/cdp-engine/src/tests.rs b/modules/cdp-engine/src/tests.rs index 92f506137b..42d14fd7d2 100644 --- a/modules/cdp-engine/src/tests.rs +++ b/modules/cdp-engine/src/tests.rs @@ -46,6 +46,18 @@ fn run_to_block_offchain(n: u64) { } } +fn setup_default_collateral(currency_id: CurrencyId) { + assert_ok!(CDPEngineModule::set_collateral_params( + Origin::signed(1), + currency_id, + Change::NewValue(Some(Default::default())), + Change::NoChange, + Change::NoChange, + Change::NoChange, + Change::NewValue(10000), + )); +} + #[test] fn check_cdp_status_work() { ExtBuilder::default().build().execute_with(|| { @@ -97,9 +109,9 @@ fn get_debit_exchange_rate_work() { #[test] fn get_liquidation_penalty_work() { ExtBuilder::default().build().execute_with(|| { - assert_eq!( + assert_noop!( CDPEngineModule::get_liquidation_penalty(BTC), - DefaultLiquidationPenalty::get() + Error::::InvalidCollateralType ); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -112,7 +124,7 @@ fn get_liquidation_penalty_work() { )); assert_eq!( CDPEngineModule::get_liquidation_penalty(BTC), - Rate::saturating_from_rational(2, 10) + Ok(Rate::saturating_from_rational(2, 10)) ); }); } @@ -120,9 +132,9 @@ fn get_liquidation_penalty_work() { #[test] fn get_liquidation_ratio_work() { ExtBuilder::default().build().execute_with(|| { - assert_eq!( + assert_noop!( CDPEngineModule::get_liquidation_ratio(BTC), - DefaultLiquidationRatio::get() + Error::::InvalidCollateralType ); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -135,7 +147,7 @@ fn get_liquidation_ratio_work() { )); assert_eq!( CDPEngineModule::get_liquidation_ratio(BTC), - Ratio::saturating_from_rational(5, 2) + Ok(Ratio::saturating_from_rational(5, 2)) ); }); } @@ -143,19 +155,6 @@ fn get_liquidation_ratio_work() { #[test] fn set_collateral_params_work() { ExtBuilder::default().build().execute_with(|| { - assert_noop!( - CDPEngineModule::set_collateral_params( - Origin::signed(1), - ACA, - Change::NoChange, - Change::NoChange, - Change::NoChange, - Change::NoChange, - Change::NoChange, - ), - Error::::InvalidCollateralType - ); - System::set_block_number(1); assert_noop!( CDPEngineModule::set_collateral_params( @@ -209,7 +208,7 @@ fn set_collateral_params_work() { Change::NewValue(10000), )); - let new_collateral_params = CDPEngineModule::collateral_params(BTC); + let new_collateral_params = CDPEngineModule::collateral_params(BTC).unwrap(); assert_eq!( new_collateral_params.interest_rate_per_sec, @@ -355,15 +354,9 @@ fn check_position_valid_ratio_below_required_ratio() { #[test] fn adjust_position_work() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(CDPEngineModule::set_collateral_params( - Origin::signed(1), - BTC, - Change::NewValue(Some(Rate::saturating_from_rational(1, 100000))), - Change::NewValue(Some(Ratio::saturating_from_rational(3, 2))), - Change::NewValue(Some(Rate::saturating_from_rational(2, 10))), - Change::NewValue(Some(Ratio::saturating_from_rational(9, 5))), - Change::NewValue(10000), - )); + setup_default_collateral(BTC); + setup_default_collateral(AUSD); + assert_noop!( CDPEngineModule::adjust_position(&ALICE, ACA, 100, 500), Error::::InvalidCollateralType, @@ -390,6 +383,7 @@ fn adjust_position_work() { fn expand_position_collateral_work() { ExtBuilder::default().build().execute_with(|| { MockPriceSource::set_price(DOT, Some(Price::saturating_from_rational(10, 1))); + setup_default_collateral(AUSD); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), DOT, @@ -518,6 +512,9 @@ fn expand_position_collateral_for_lp_ausd_dot_work() { Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), Change::NewValue(10000), )); + setup_default_collateral(DOT); + setup_default_collateral(AUSD); + assert_ok!(CDPEngineModule::adjust_position(&ALICE, LP_AUSD_DOT, 1000, 2000)); assert_eq!( LoansModule::positions(LP_AUSD_DOT, ALICE), @@ -579,6 +576,7 @@ fn shrink_position_debit_work() { Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), Change::NewValue(10000), )); + setup_default_collateral(AUSD); assert_ok!(CDPEngineModule::adjust_position(&ALICE, DOT, 100, 5000)); assert_eq!( LoansModule::positions(DOT, ALICE), @@ -675,6 +673,8 @@ fn shrink_position_debit_for_lp_ausd_dot_work() { Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), Change::NewValue(10000), )); + setup_default_collateral(DOT); + setup_default_collateral(AUSD); assert_ok!(CDPEngineModule::adjust_position(&ALICE, LP_AUSD_DOT, 1000, 5000)); assert_eq!( LoansModule::positions(LP_AUSD_DOT, ALICE), @@ -770,6 +770,7 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { Change::NewValue(Some(Ratio::saturating_from_rational(9, 5))), Change::NewValue(10000), )); + setup_default_collateral(AUSD); assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 100, 500)); assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); @@ -824,6 +825,7 @@ fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { Change::NewValue(Some(Ratio::saturating_from_rational(9, 5))), Change::NewValue(10000), )); + setup_default_collateral(AUSD); assert_ok!(DEXModule::add_liquidity( Origin::signed(CAROL), BTC, @@ -892,6 +894,8 @@ fn liquidate_unsafe_cdp_by_swap() { Change::NewValue(Some(Ratio::saturating_from_rational(9, 5))), Change::NewValue(10000), )); + setup_default_collateral(DOT); + setup_default_collateral(AUSD); assert_ok!(DEXModule::add_liquidity( Origin::signed(CAROL), BTC, @@ -950,6 +954,9 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_swap_dot() { Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), Change::NewValue(10000), )); + setup_default_collateral(DOT); + setup_default_collateral(AUSD); + assert_ok!(DEXModule::add_liquidity( Origin::signed(CAROL), AUSD, @@ -1040,6 +1047,9 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_ausd_take_whole_target() { Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), Change::NewValue(10000), )); + setup_default_collateral(DOT); + setup_default_collateral(AUSD); + assert_ok!(DEXModule::add_liquidity( Origin::signed(CAROL), AUSD, @@ -1130,6 +1140,9 @@ fn liquidate_unsafe_cdp_of_lp_ausd_dot_and_create_dot_auction() { Change::NewValue(Some(Ratio::saturating_from_rational(2, 1))), Change::NewValue(10000), )); + setup_default_collateral(DOT); + setup_default_collateral(AUSD); + assert_ok!(DEXModule::add_liquidity( Origin::signed(CAROL), AUSD, @@ -1228,6 +1241,16 @@ fn get_interest_rate_per_sec_work() { Change::NewValue(Some(Ratio::saturating_from_rational(9, 5))), Change::NewValue(10000), )); + + assert_ok!(CDPEngineModule::set_collateral_params( + Origin::signed(1), + DOT, + Change::NoChange, + Change::NoChange, + Change::NoChange, + Change::NoChange, + Change::NoChange, + )); assert_eq!( CDPEngineModule::get_interest_rate_per_sec(BTC), Ok(Rate::saturating_from_rational(2, 100000)) @@ -1561,17 +1584,13 @@ fn offchain_worker_works_cdp() { ext.execute_with(|| { // number of currencies allowed as collateral (cycles through all of them) - let collateral_currencies_num = CollateralCurrencyIds::get().len() as u64; + setup_default_collateral(BTC); + setup_default_collateral(LP_AUSD_DOT); + setup_default_collateral(DOT); + + let collateral_currencies_num = CollateralCurrencyIds::::get().len() as u64; + System::set_block_number(1); - assert_ok!(CDPEngineModule::set_collateral_params( - Origin::signed(1), - BTC, - Change::NewValue(Some(Rate::saturating_from_rational(1, 100000))), - Change::NewValue(Some(Ratio::saturating_from_rational(3, 2))), - Change::NewValue(Some(Rate::saturating_from_rational(2, 10))), - Change::NewValue(Some(Ratio::saturating_from_rational(9, 5))), - Change::NewValue(10000), - )); // offchain worker will not liquidate alice assert_ok!(CDPEngineModule::adjust_position(&ALICE, BTC, 100, 500)); @@ -1580,7 +1599,8 @@ fn offchain_worker_works_cdp() { assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 500); assert_eq!(LoansModule::positions(BTC, ALICE).collateral, 100); - // jump 2 blocks at a time because code rotates through the different T::CollateralCurrencyIds + // jump 2 blocks at a time because code rotates through the different supported collateral + // currencies run_to_block_offchain(System::block_number() + collateral_currencies_num); // checks that offchain worker tx pool is empty (therefore tx to liquidate alice is not present) @@ -1716,7 +1736,6 @@ fn offchain_default_max_iterator_works() { ext.register_extension(OffchainDbExt::new(offchain.clone())); ext.execute_with(|| { - System::set_block_number(1); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), BTC, @@ -1726,6 +1745,9 @@ fn offchain_default_max_iterator_works() { Change::NewValue(Some(Ratio::saturating_from_rational(9, 5))), Change::NewValue(10000), )); + + System::set_block_number(1); + // checks that max iterations is stored as none assert!(offchain .local_storage_get(StorageKind::PERSISTENT, OFFCHAIN_WORKER_MAX_ITERATIONS) diff --git a/modules/emergency-shutdown/src/mock.rs b/modules/emergency-shutdown/src/mock.rs index 7bb67144e0..ed1dce8884 100644 --- a/modules/emergency-shutdown/src/mock.rs +++ b/modules/emergency-shutdown/src/mock.rs @@ -223,12 +223,12 @@ impl cdp_treasury::Config for Runtime { } ord_parameter_types! { - pub const CollateralCurrencyIds: Vec = vec![BTC, DOT]; + pub const MockCollateralCurrencyIds: Vec = vec![BTC, DOT]; } impl Config for Runtime { type Event = Event; - type CollateralCurrencyIds = CollateralCurrencyIds; + type CollateralCurrencyIds = MockCollateralCurrencyIds; type PriceSource = MockLockablePrice; type CDPTreasury = CDPTreasuryModule; type AuctionManagerHandler = MockAuctionManager; diff --git a/modules/honzon/src/lib.rs b/modules/honzon/src/lib.rs index 2c255a3dfe..76923ff0bc 100644 --- a/modules/honzon/src/lib.rs +++ b/modules/honzon/src/lib.rs @@ -36,6 +36,7 @@ use sp_runtime::{ traits::{StaticLookup, Zero}, DispatchResult, }; +use sp_std::prelude::*; use support::EmergencyShutdown; mod mock; @@ -66,6 +67,10 @@ pub mod module { #[pallet::constant] type DepositPerAuthorization: Get; + /// The list of valid collateral currency types + #[pallet::constant] + type CollateralCurrencyIds: Get>; + /// Weight information for the extrinsics in this module. type WeightInfo: WeightInfo; } @@ -252,7 +257,7 @@ pub mod module { } /// Cancel all authorization of caller - #[pallet::weight(::WeightInfo::unauthorize_all(::CollateralCurrencyIds::get().len() as u32))] + #[pallet::weight(::WeightInfo::unauthorize_all(T::CollateralCurrencyIds::get().len() as u32))] #[transactional] pub fn unauthorize_all(origin: OriginFor) -> DispatchResult { let from = ensure_signed(origin)?; diff --git a/modules/honzon/src/mock.rs b/modules/honzon/src/mock.rs index c6bc809e6d..3d630c0b16 100644 --- a/modules/honzon/src/mock.rs +++ b/modules/honzon/src/mock.rs @@ -21,6 +21,7 @@ #![cfg(test)] use super::*; +use cdp_engine::CollateralCurrencyIds; use frame_support::{ construct_runtime, ord_parameter_types, parameter_types, traits::{ConstU128, ConstU32, ConstU64, Everything, Nothing}, @@ -235,7 +236,6 @@ parameter_type_with_key! { } parameter_types! { - pub CollateralCurrencyIds: Vec = vec![BTC, DOT]; pub DefaultLiquidationRatio: Ratio = Ratio::saturating_from_rational(3, 2); pub DefaultDebitExchangeRate: ExchangeRate = ExchangeRate::one(); pub DefaultLiquidationPenalty: Rate = Rate::saturating_from_rational(10, 100); @@ -245,7 +245,6 @@ parameter_types! { impl cdp_engine::Config for Runtime { type Event = Event; type PriceSource = MockPriceSource; - type CollateralCurrencyIds = CollateralCurrencyIds; type DefaultLiquidationRatio = DefaultLiquidationRatio; type DefaultDebitExchangeRate = DefaultDebitExchangeRate; type DefaultLiquidationPenalty = DefaultLiquidationPenalty; @@ -271,6 +270,7 @@ impl Config for Runtime { type Event = Event; type Currency = PalletBalances; type DepositPerAuthorization = ConstU128<100>; + type CollateralCurrencyIds = CollateralCurrencyIds; type WeightInfo = (); } diff --git a/runtime/acala/src/benchmarking/mod.rs b/runtime/acala/src/benchmarking/mod.rs index 25ef22ca42..ec81dd2ba0 100644 --- a/runtime/acala/src/benchmarking/mod.rs +++ b/runtime/acala/src/benchmarking/mod.rs @@ -18,6 +18,9 @@ #![cfg(feature = "runtime-benchmarks")] +use super::{CurrencyId, ACA, DOT, LCDOT, LDOT}; +use sp_std::prelude::*; + pub mod utils { include!("../../../mandala/src/benchmarking/utils.rs"); } @@ -101,3 +104,7 @@ pub mod vesting { pub fn get_vesting_account() -> super::AccountId { super::AcalaFoundationAccounts::get()[0].clone() } + +pub fn get_benchmarking_collateral_currency_ids() -> Vec { + vec![ACA, DOT, LCDOT, LDOT] +} diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index bd629662c4..0576f76c93 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -51,6 +51,7 @@ use sp_version::RuntimeVersion; use frame_system::{EnsureRoot, RawOrigin}; use module_asset_registry::{AssetIdMaps, EvmErc20InfoMapping, FixedRateOfForeignAsset}; +use module_cdp_engine::CollateralCurrencyIds; use module_currencies::BasicCurrencyAdapter; use module_evm::{CallInfo, CreateInfo, EvmTask, Runner}; use module_evm_accounts::EvmAddressMapping; @@ -1030,7 +1031,6 @@ where } parameter_types! { - pub CollateralCurrencyIds: Vec = vec![ACA, DOT, LCDOT, LDOT, CurrencyId::StableAssetPoolToken(0)]; pub DefaultLiquidationRatio: Ratio = Ratio::saturating_from_rational(150, 100); pub DefaultDebitExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10); pub DefaultLiquidationPenalty: Rate = Rate::saturating_from_rational(8, 100); @@ -1041,7 +1041,6 @@ parameter_types! { impl module_cdp_engine::Config for Runtime { type Event = Event; type PriceSource = module_prices::PriorityLockedPriceProvider; - type CollateralCurrencyIds = CollateralCurrencyIds; type DefaultLiquidationRatio = DefaultLiquidationRatio; type DefaultDebitExchangeRate = DefaultDebitExchangeRate; type DefaultLiquidationPenalty = DefaultLiquidationPenalty; @@ -1069,12 +1068,13 @@ impl module_honzon::Config for Runtime { type Event = Event; type Currency = Balances; type DepositPerAuthorization = DepositPerAuthorization; + type CollateralCurrencyIds = CollateralCurrencyIds; type WeightInfo = weights::module_honzon::WeightInfo; } impl module_emergency_shutdown::Config for Runtime { type Event = Event; - type CollateralCurrencyIds = CollateralCurrencyIds; + type CollateralCurrencyIds = CollateralCurrencyIds; type PriceSource = Prices; type CDPTreasury = CdpTreasury; type AuctionManagerHandler = AuctionManager; diff --git a/runtime/integration-tests/src/honzon.rs b/runtime/integration-tests/src/honzon.rs index a4872ed9f4..0de827b68e 100644 --- a/runtime/integration-tests/src/honzon.rs +++ b/runtime/integration-tests/src/honzon.rs @@ -18,6 +18,18 @@ use crate::setup::*; +fn setup_default_collateral(currency_id: CurrencyId) { + assert_ok!(CdpEngine::set_collateral_params( + Origin::root(), + currency_id, + Change::NewValue(Some(Default::default())), + Change::NoChange, + Change::NoChange, + Change::NoChange, + Change::NewValue(10000), + )); +} + #[test] fn emergency_shutdown_and_cdp_treasury() { ExtBuilder::default() @@ -37,6 +49,10 @@ fn emergency_shutdown_and_cdp_treasury() { ]) .build() .execute_with(|| { + setup_default_collateral(RELAY_CHAIN_CURRENCY); + setup_default_collateral(LIQUID_CURRENCY); + setup_default_collateral(USD_CURRENCY); + assert_ok!(CdpTreasury::deposit_collateral( &AccountId::from(BOB), RELAY_CHAIN_CURRENCY, @@ -335,7 +351,9 @@ fn test_cdp_engine_module() { Change::NewValue(10_000 * dollar(USD_CURRENCY)), )); - let new_collateral_params = CdpEngine::collateral_params(RELAY_CHAIN_CURRENCY); + let maybe_new_collateral_params = CdpEngine::collateral_params(RELAY_CHAIN_CURRENCY); + assert!(maybe_new_collateral_params.is_some()); + let new_collateral_params = maybe_new_collateral_params.unwrap(); assert_eq!( new_collateral_params.interest_rate_per_sec, diff --git a/runtime/karura/src/benchmarking/mod.rs b/runtime/karura/src/benchmarking/mod.rs index 2942c30d4a..1a3252be2c 100644 --- a/runtime/karura/src/benchmarking/mod.rs +++ b/runtime/karura/src/benchmarking/mod.rs @@ -18,6 +18,9 @@ #![cfg(feature = "runtime-benchmarks")] +use super::{CurrencyId, KAR, KSM, LKSM}; +use sp_std::prelude::*; + pub mod utils { include!("../../../mandala/src/benchmarking/utils.rs"); } @@ -105,3 +108,7 @@ pub mod honzon_bridge; pub fn get_vesting_account() -> super::AccountId { super::KaruraFoundationAccounts::get()[0].clone() } + +pub fn get_benchmarking_collateral_currency_ids() -> Vec { + vec![KSM, LKSM, KAR, CurrencyId::StableAssetPoolToken(0)] +} diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index 09d8ad3621..1aae29665c 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -52,6 +52,7 @@ use sp_version::RuntimeVersion; use frame_support::pallet_prelude::InvalidTransaction; use frame_system::{EnsureRoot, RawOrigin}; use module_asset_registry::{AssetIdMaps, EvmErc20InfoMapping, FixedRateOfForeignAsset}; +use module_cdp_engine::CollateralCurrencyIds; use module_currencies::BasicCurrencyAdapter; use module_evm::{CallInfo, CreateInfo, EvmTask, Runner}; use module_evm_accounts::EvmAddressMapping; @@ -1040,7 +1041,6 @@ where } parameter_types! { - pub CollateralCurrencyIds: Vec = vec![KSM, LKSM, KAR, CurrencyId::StableAssetPoolToken(0)]; pub DefaultLiquidationRatio: Ratio = Ratio::saturating_from_rational(150, 100); pub DefaultDebitExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10); pub DefaultLiquidationPenalty: Rate = Rate::saturating_from_rational(8, 100); @@ -1051,7 +1051,6 @@ parameter_types! { impl module_cdp_engine::Config for Runtime { type Event = Event; type PriceSource = module_prices::PriorityLockedPriceProvider; - type CollateralCurrencyIds = CollateralCurrencyIds; type DefaultLiquidationRatio = DefaultLiquidationRatio; type DefaultDebitExchangeRate = DefaultDebitExchangeRate; type DefaultLiquidationPenalty = DefaultLiquidationPenalty; @@ -1079,12 +1078,13 @@ impl module_honzon::Config for Runtime { type Event = Event; type Currency = Balances; type DepositPerAuthorization = DepositPerAuthorization; + type CollateralCurrencyIds = CollateralCurrencyIds; type WeightInfo = weights::module_honzon::WeightInfo; } impl module_emergency_shutdown::Config for Runtime { type Event = Event; - type CollateralCurrencyIds = CollateralCurrencyIds; + type CollateralCurrencyIds = CollateralCurrencyIds; type PriceSource = Prices; type CDPTreasury = CdpTreasury; type AuctionManagerHandler = AuctionManager; diff --git a/runtime/mandala/src/benchmarking/cdp_engine.rs b/runtime/mandala/src/benchmarking/cdp_engine.rs index 6ee4f1934e..6c4559a6b7 100644 --- a/runtime/mandala/src/benchmarking/cdp_engine.rs +++ b/runtime/mandala/src/benchmarking/cdp_engine.rs @@ -17,13 +17,16 @@ // along with this program. If not, see . use crate::{ - AccountId, Address, Amount, Balance, CdpEngine, CdpTreasury, CollateralCurrencyIds, CurrencyId, - DefaultDebitExchangeRate, Dex, EmergencyShutdown, ExistentialDeposits, GetLiquidCurrencyId, GetNativeCurrencyId, - GetStableCurrencyId, GetStakingCurrencyId, MinimumDebitValue, NativeTokenExistentialDeposit, Price, Rate, Ratio, - Runtime, Timestamp, MILLISECS_PER_BLOCK, + AccountId, Address, Amount, Balance, CdpEngine, CdpTreasury, CurrencyId, DefaultDebitExchangeRate, Dex, + EmergencyShutdown, ExistentialDeposits, GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, + GetStakingCurrencyId, MinimumDebitValue, NativeTokenExistentialDeposit, Price, Rate, Ratio, Runtime, Timestamp, + MILLISECS_PER_BLOCK, }; -use super::utils::{dollar, feed_price, set_balance}; +use super::{ + get_benchmarking_collateral_currency_ids, + utils::{dollar, feed_price, set_balance}, +}; use frame_benchmarking::account; use frame_support::traits::{Get, OnInitialize}; use frame_system::RawOrigin; @@ -72,10 +75,10 @@ runtime_benchmarks! { { Runtime, module_cdp_engine } on_initialize { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; let owner: AccountId = account("owner", 0, SEED); let owner_lookup: Address = AccountIdLookup::unlookup(owner.clone()); - let currency_ids = CollateralCurrencyIds::get(); + let currency_ids = get_benchmarking_collateral_currency_ids(); let min_debit_value = MinimumDebitValue::get(); let debit_exchange_rate = DefaultDebitExchangeRate::get(); let min_debit_amount = debit_exchange_rate.reciprocal().unwrap().saturating_mul_int(min_debit_value); diff --git a/runtime/mandala/src/benchmarking/emergency_shutdown.rs b/runtime/mandala/src/benchmarking/emergency_shutdown.rs index 65443b99a9..2b45e2a0af 100644 --- a/runtime/mandala/src/benchmarking/emergency_shutdown.rs +++ b/runtime/mandala/src/benchmarking/emergency_shutdown.rs @@ -16,11 +16,12 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::{ - AccountId, CdpTreasury, CollateralCurrencyIds, CurrencyId, EmergencyShutdown, GetStableCurrencyId, Price, Runtime, -}; +use crate::{AccountId, CdpTreasury, CurrencyId, EmergencyShutdown, GetStableCurrencyId, Price, Runtime}; -use super::utils::{dollar, feed_price, set_balance}; +use super::{ + get_benchmarking_collateral_currency_ids, + utils::{dollar, feed_price, set_balance}, +}; use frame_benchmarking::{account, whitelisted_caller}; use frame_system::RawOrigin; use module_support::CDPTreasury; @@ -36,8 +37,8 @@ runtime_benchmarks! { { Runtime, module_emergency_shutdown } emergency_shutdown { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; - let currency_ids = CollateralCurrencyIds::get(); + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; + let currency_ids = get_benchmarking_collateral_currency_ids(); let mut values = vec![]; for i in 0 .. c { @@ -51,8 +52,8 @@ runtime_benchmarks! { }: _(RawOrigin::Root) refund_collaterals { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; - let currency_ids = CollateralCurrencyIds::get(); + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; + let currency_ids = get_benchmarking_collateral_currency_ids(); let funder: AccountId = account("funder", 0, SEED); let caller: AccountId = whitelisted_caller(); let mut values = vec![]; diff --git a/runtime/mandala/src/benchmarking/honzon.rs b/runtime/mandala/src/benchmarking/honzon.rs index a202ea23d3..fd0e42882e 100644 --- a/runtime/mandala/src/benchmarking/honzon.rs +++ b/runtime/mandala/src/benchmarking/honzon.rs @@ -17,12 +17,15 @@ // along with this program. If not, see . use crate::{ - AccountId, Amount, Balance, CdpEngine, CollateralCurrencyIds, Currencies, CurrencyId, DepositPerAuthorization, Dex, - ExistentialDeposits, GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, GetStakingCurrencyId, Honzon, - Price, Rate, Ratio, Runtime, + AccountId, Amount, Balance, CdpEngine, Currencies, CurrencyId, DepositPerAuthorization, Dex, ExistentialDeposits, + GetLiquidCurrencyId, GetNativeCurrencyId, GetStableCurrencyId, GetStakingCurrencyId, Honzon, Price, Rate, Ratio, + Runtime, }; -use super::utils::{dollar, feed_price, set_balance}; +use super::{ + get_benchmarking_collateral_currency_ids, + utils::{dollar, feed_price, set_balance}, +}; use frame_benchmarking::{account, whitelisted_caller}; use frame_system::RawOrigin; use orml_benchmarking::runtime_benchmarks; @@ -102,10 +105,10 @@ runtime_benchmarks! { }: _(RawOrigin::Signed(caller), STAKING, to_lookup) unauthorize_all { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; let caller: AccountId = whitelisted_caller(); - let currency_ids = CollateralCurrencyIds::get(); + let currency_ids = get_benchmarking_collateral_currency_ids(); let to: AccountId = account("to", 0, SEED); let to_lookup = AccountIdLookup::unlookup(to); @@ -124,7 +127,7 @@ runtime_benchmarks! { // adjust both collateral and debit adjust_loan { let caller: AccountId = whitelisted_caller(); - let currency_id: CurrencyId = CollateralCurrencyIds::get()[0]; + let currency_id: CurrencyId = get_benchmarking_collateral_currency_ids()[0]; let collateral_price = Price::one(); // 1 USD let debit_value = 100 * dollar(STABLECOIN); let debit_exchange_rate = CdpEngine::get_debit_exchange_rate(currency_id); @@ -152,7 +155,7 @@ runtime_benchmarks! { }: _(RawOrigin::Signed(caller), currency_id, collateral_amount.try_into().unwrap(), debit_amount) transfer_loan_from { - let currency_id: CurrencyId = CollateralCurrencyIds::get()[0]; + let currency_id: CurrencyId = get_benchmarking_collateral_currency_ids()[0]; let sender: AccountId = account("sender", 0, SEED); let sender_lookup = AccountIdLookup::unlookup(sender.clone()); let receiver: AccountId = whitelisted_caller(); diff --git a/runtime/mandala/src/benchmarking/incentives.rs b/runtime/mandala/src/benchmarking/incentives.rs index ba417c7dc5..c07e8f55e5 100644 --- a/runtime/mandala/src/benchmarking/incentives.rs +++ b/runtime/mandala/src/benchmarking/incentives.rs @@ -17,11 +17,14 @@ // along with this program. If not, see . use crate::{ - AccountId, AccumulatePeriod, CollateralCurrencyIds, Currencies, CurrencyId, GetNativeCurrencyId, - GetStableCurrencyId, GetStakingCurrencyId, Incentives, Rate, Rewards, Runtime, System, + AccountId, AccumulatePeriod, Currencies, CurrencyId, GetNativeCurrencyId, GetStableCurrencyId, + GetStakingCurrencyId, Incentives, Rate, Rewards, Runtime, System, }; -use super::utils::{dollar, set_balance}; +use super::{ + get_benchmarking_collateral_currency_ids, + utils::{dollar, set_balance}, +}; use frame_benchmarking::{account, whitelisted_caller, BenchmarkError}; use frame_support::traits::OnInitialize; use frame_system::RawOrigin; @@ -40,8 +43,8 @@ runtime_benchmarks! { { Runtime, module_incentives } on_initialize { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; - let currency_ids = CollateralCurrencyIds::get(); + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; + let currency_ids = get_benchmarking_collateral_currency_ids(); let block_number = AccumulatePeriod::get(); for i in 0 .. c { @@ -88,8 +91,8 @@ runtime_benchmarks! { }: _(RawOrigin::Signed(caller), pool_id) update_incentive_rewards { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; - let currency_ids = CollateralCurrencyIds::get(); + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; + let currency_ids = get_benchmarking_collateral_currency_ids(); let mut updates = vec![]; for i in 0 .. c { @@ -99,8 +102,8 @@ runtime_benchmarks! { }: _(RawOrigin::Root, updates) update_dex_saving_rewards { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; - let currency_ids = CollateralCurrencyIds::get(); + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; + let currency_ids = get_benchmarking_collateral_currency_ids(); let caller: AccountId = account("caller", 0, SEED); let mut updates = vec![]; let base_currency_id = GetStableCurrencyId::get(); @@ -119,8 +122,8 @@ runtime_benchmarks! { }: _(RawOrigin::Root, updates) update_claim_reward_deduction_rates { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; - let currency_ids = CollateralCurrencyIds::get(); + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; + let currency_ids = get_benchmarking_collateral_currency_ids(); let mut updates = vec![]; for i in 0 .. c { diff --git a/runtime/mandala/src/benchmarking/mod.rs b/runtime/mandala/src/benchmarking/mod.rs index b17701429d..0fcde88176 100644 --- a/runtime/mandala/src/benchmarking/mod.rs +++ b/runtime/mandala/src/benchmarking/mod.rs @@ -20,6 +20,9 @@ use sp_runtime::traits::AccountIdConversion; +use super::{CurrencyId, ACA, DOT, LDOT, RENBTC}; +use sp_std::prelude::*; + pub mod utils; // module benchmarking @@ -56,3 +59,7 @@ pub mod vesting; pub fn get_vesting_account() -> super::AccountId { super::TreasuryPalletId::get().into_account() } + +pub fn get_benchmarking_collateral_currency_ids() -> Vec { + vec![ACA, DOT, LDOT, RENBTC, CurrencyId::StableAssetPoolToken(0)] +} diff --git a/runtime/mandala/src/benchmarking/oracle.rs b/runtime/mandala/src/benchmarking/oracle.rs index d1bd0c3f75..2b21a778eb 100644 --- a/runtime/mandala/src/benchmarking/oracle.rs +++ b/runtime/mandala/src/benchmarking/oracle.rs @@ -16,8 +16,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::{AcalaDataProvider, AcalaOracle, CollateralCurrencyIds, Origin, Price, Runtime, System}; +use crate::{AcalaDataProvider, AcalaOracle, Origin, Price, Runtime, System}; +use super::get_benchmarking_collateral_currency_ids; use frame_support::traits::OnFinalize; use orml_benchmarking::runtime_benchmarks_instance; use sp_runtime::traits::One; @@ -28,8 +29,8 @@ runtime_benchmarks_instance! { // feed values feed_values { - let c in 0 .. CollateralCurrencyIds::get().len() as u32; - let currency_ids = CollateralCurrencyIds::get(); + let c in 0 .. get_benchmarking_collateral_currency_ids().len() as u32; + let currency_ids = get_benchmarking_collateral_currency_ids(); let mut values = vec![]; for i in 0 .. c { @@ -38,7 +39,7 @@ runtime_benchmarks_instance! { }: _(Origin::root(), values) on_finalize { - let currency_ids = CollateralCurrencyIds::get(); + let currency_ids = get_benchmarking_collateral_currency_ids(); let mut values = vec![]; for currency_id in currency_ids { diff --git a/runtime/mandala/src/lib.rs b/runtime/mandala/src/lib.rs index ae55ef0022..7db54191ec 100644 --- a/runtime/mandala/src/lib.rs +++ b/runtime/mandala/src/lib.rs @@ -50,6 +50,7 @@ pub use frame_support::{ use frame_system::{EnsureRoot, RawOrigin}; use hex_literal::hex; use module_asset_registry::{AssetIdMaps, EvmErc20InfoMapping, FixedRateOfForeignAsset}; +use module_cdp_engine::CollateralCurrencyIds; use module_currencies::{BasicCurrencyAdapter, Currency}; use module_evm::{CallInfo, CreateInfo, EvmTask, Runner}; use module_evm_accounts::EvmAddressMapping; @@ -1029,7 +1030,6 @@ where } parameter_types! { - pub CollateralCurrencyIds: Vec = vec![ACA, DOT, LDOT, RENBTC, CurrencyId::StableAssetPoolToken(0)]; pub DefaultLiquidationRatio: Ratio = Ratio::saturating_from_rational(110, 100); pub DefaultDebitExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10); pub DefaultLiquidationPenalty: Rate = Rate::saturating_from_rational(5, 100); @@ -1040,7 +1040,6 @@ parameter_types! { impl module_cdp_engine::Config for Runtime { type Event = Event; type PriceSource = module_prices::PriorityLockedPriceProvider; - type CollateralCurrencyIds = CollateralCurrencyIds; type DefaultLiquidationRatio = DefaultLiquidationRatio; type DefaultDebitExchangeRate = DefaultDebitExchangeRate; type DefaultLiquidationPenalty = DefaultLiquidationPenalty; @@ -1068,12 +1067,13 @@ impl module_honzon::Config for Runtime { type Event = Event; type Currency = Balances; type DepositPerAuthorization = DepositPerAuthorization; + type CollateralCurrencyIds = CollateralCurrencyIds; type WeightInfo = weights::module_honzon::WeightInfo; } impl module_emergency_shutdown::Config for Runtime { type Event = Event; - type CollateralCurrencyIds = CollateralCurrencyIds; + type CollateralCurrencyIds = CollateralCurrencyIds; type PriceSource = Prices; type CDPTreasury = CdpTreasury; type AuctionManagerHandler = AuctionManager;