Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion ecosystem-modules/stable-asset
12 changes: 12 additions & 0 deletions modules/auction-manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,18 @@ impl<T: Config> Pallet<T> {
);
Self::try_refund_bid(&collateral_auction, last_bid);

// Note: for StableAsset, the swap of cdp treasury is always on `ExactSupply`
// regardless of this swap_limit params. There will be excess stablecoins that
// need to be returned to the refund_recipient from cdp treasury account.
if let SwapLimit::ExactTarget(_, target_limit) = swap_limit {
if actual_target_amount > target_limit {
let _ = T::CDPTreasury::withdraw_surplus(
&collateral_auction.refund_recipient,
actual_target_amount.saturating_sub(target_limit),
);
}
}

Self::deposit_event(Event::DEXTakeCollateralAuction {
auction_id,
collateral_type: collateral_auction.currency_id,
Expand Down
2 changes: 2 additions & 0 deletions modules/auction-manager/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use sp_runtime::{
traits::{AccountIdConversion, IdentityLookup, One as OneT},
};
use sp_std::cell::RefCell;
use support::mocks::MockStableAsset;
pub use support::Price;

pub type AccountId = u128;
Expand Down Expand Up @@ -136,6 +137,7 @@ impl cdp_treasury::Config for Runtime {
type TreasuryAccount = TreasuryAccount;
type AlternativeSwapPathJointList = AlternativeSwapPathJointList;
type WeightInfo = ();
type StableAsset = MockStableAsset<CurrencyId, Balance, AccountId, BlockNumber>;
}

thread_local! {
Expand Down
1 change: 1 addition & 0 deletions modules/cdp-engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ support = { package = "module-support", path = "../support", default-features =
loans = { package = "module-loans", path = "../loans", default-features = false }
primitives = { package = "acala-primitives", path = "../../primitives", default-features = false }
rand_chacha = { version = "0.2", default-features = false }
nutsfinance-stable-asset = { version = "0.1.0", default-features = false, path = "../../ecosystem-modules/stable-asset/lib/stable-asset", package = "nutsfinance-stable-asset" }

[dev-dependencies]
sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17" }
Expand Down
21 changes: 16 additions & 5 deletions modules/cdp-engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1238,11 +1238,12 @@ impl<T: Config> Pallet<T> {
let collateral_supply = amount.min(max_supply_limit);

// try swap collateral to stable to settle debit swap succeed.
if let Ok((actual_supply_collateral, _)) = <T as Config>::CDPTreasury::swap_collateral_to_stable(
currency_id,
SwapLimit::ExactTarget(collateral_supply, target_stable_amount),
false,
) {
if let Ok((actual_supply_collateral, actual_target_amount)) =
<T as Config>::CDPTreasury::swap_collateral_to_stable(
currency_id,
SwapLimit::ExactTarget(collateral_supply, target_stable_amount),
false,
) {
let refund_collateral_amount = amount
.checked_sub(actual_supply_collateral)
.expect("swap succecced means collateral >= actual_supply_collateral; qed");
Expand All @@ -1251,6 +1252,16 @@ impl<T: Config> Pallet<T> {
if !refund_collateral_amount.is_zero() {
<T as Config>::CDPTreasury::withdraw_collateral(who, currency_id, refund_collateral_amount)?;
}

// Note: for StableAsset, the swap of cdp treasury is always on `ExactSupply`
// regardless of this swap_limit params. There will be excess stablecoins that
// need to be returned to the `who` from cdp treasury account.
if actual_target_amount > target_stable_amount {
<T as Config>::CDPTreasury::withdraw_surplus(
who,
actual_target_amount.saturating_sub(target_stable_amount),
)?;
}
} else {
// if cannot liquidate by swap, create collateral auctions by cdp treasury
<T as Config>::CDPTreasury::create_collateral_auctions(
Expand Down
4 changes: 3 additions & 1 deletion modules/cdp-engine/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use sp_runtime::{
traits::{AccountIdConversion, IdentityLookup, One as OneT},
};
use sp_std::cell::RefCell;
use support::mocks::MockStableAsset;
use support::{AuctionManager, EmergencyShutdown};

pub type AccountId = u128;
Expand Down Expand Up @@ -196,7 +197,7 @@ impl AuctionManager<AccountId> for MockAuctionManager {
amount: Self::Balance,
target: Self::Balance,
) -> DispatchResult {
AUCTION.with(|v| *v.borrow_mut() = Some((refund_recipient.clone(), currency_id, amount, target)));
AUCTION.with(|v| *v.borrow_mut() = Some((*refund_recipient, currency_id, amount, target)));
Ok(())
}

Expand Down Expand Up @@ -242,6 +243,7 @@ impl cdp_treasury::Config for Runtime {
type TreasuryAccount = TreasuryAccount;
type AlternativeSwapPathJointList = AlternativeSwapPathJointList;
type WeightInfo = ();
type StableAsset = MockStableAsset<CurrencyId, Balance, AccountId, BlockNumber>;
}

parameter_types! {
Expand Down
4 changes: 2 additions & 2 deletions modules/cdp-engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -863,11 +863,11 @@ fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() {
// pool is enough, but slippage limit the swap
MockPriceSource::set_price(BTC, Some(Price::saturating_from_rational(2, 1)));
assert_eq!(
DEXModule::get_swap_amount(&vec![BTC, AUSD], SwapLimit::ExactTarget(Balance::MAX, 60)),
DEXModule::get_swap_amount(&[BTC, AUSD], SwapLimit::ExactTarget(Balance::MAX, 60)),
Some((99, 60))
);
assert_eq!(
DEXModule::get_swap_amount(&vec![BTC, AUSD], SwapLimit::ExactSupply(100, 0)),
DEXModule::get_swap_amount(&[BTC, AUSD], SwapLimit::ExactSupply(100, 0)),
Some((100, 60))
);
assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC));
Expand Down
1 change: 1 addition & 0 deletions modules/cdp-treasury/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v
orml-traits = { path = "../../orml/traits", default-features = false }
support = { package = "module-support", path = "../support", default-features = false }
primitives = { package = "acala-primitives", path = "../../primitives", default-features = false }
nutsfinance-stable-asset = { version = "0.1.0", default-features = false, path = "../../ecosystem-modules/stable-asset/lib/stable-asset", package = "nutsfinance-stable-asset" }

[dev-dependencies]
sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17" }
Expand Down
86 changes: 78 additions & 8 deletions modules/cdp-treasury/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
#![allow(clippy::needless_range_loop)]

use frame_support::{log, pallet_prelude::*, transactional, PalletId};
use frame_system::pallet_prelude::*;
use nutsfinance_stable_asset::traits::StableAsset;
use nutsfinance_stable_asset::RedeemProportionResult;
use orml_traits::{MultiCurrency, MultiCurrencyExtended};
use primitives::{Balance, CurrencyId};
use sp_runtime::{
Expand Down Expand Up @@ -72,6 +75,14 @@ pub mod module {
/// currency
type DEX: DEXManager<Self::AccountId, CurrencyId, Balance>;

type StableAsset: StableAsset<
AssetId = CurrencyId,
AtLeast64BitUnsigned = Balance,
Balance = Balance,
AccountId = Self::AccountId,
BlockNumber = Self::BlockNumber,
>;

/// The cap of lots number when create collateral auction on a
/// liquidation or to create debit/surplus auction on block end.
/// If set to 0, does not work.
Expand Down Expand Up @@ -357,6 +368,10 @@ impl<T: Config> CDPTreasury<T::AccountId> for Pallet<T> {
T::Currency::transfer(T::GetStableCurrencyId::get(), from, &Self::account_id(), surplus)
}

fn withdraw_surplus(to: &T::AccountId, surplus: Self::Balance) -> DispatchResult {
T::Currency::transfer(T::GetStableCurrencyId::get(), &Self::account_id(), to, surplus)
}

fn deposit_collateral(from: &T::AccountId, currency_id: Self::CurrencyId, amount: Self::Balance) -> DispatchResult {
T::Currency::transfer(currency_id, from, &Self::account_id(), amount)
}
Expand All @@ -367,6 +382,7 @@ impl<T: Config> CDPTreasury<T::AccountId> for Pallet<T> {
}

impl<T: Config> CDPTreasuryExtended<T::AccountId> for Pallet<T> {
#[transactional]
fn swap_collateral_to_stable(
currency_id: CurrencyId,
limit: SwapLimit<Balance>,
Expand All @@ -376,6 +392,11 @@ impl<T: Config> CDPTreasuryExtended<T::AccountId> for Pallet<T> {
SwapLimit::ExactSupply(supply_amount, _) => supply_amount,
SwapLimit::ExactTarget(max_supply_amount, _) => max_supply_amount,
};
let target_limit = match limit {
SwapLimit::ExactSupply(_, minimum_target_amount) => minimum_target_amount,
SwapLimit::ExactTarget(_, exact_target_amount) => exact_target_amount,
};

if collateral_in_auction {
ensure!(
Self::total_collaterals(currency_id) >= supply_limit
Expand All @@ -389,14 +410,63 @@ impl<T: Config> CDPTreasuryExtended<T::AccountId> for Pallet<T> {
);
}

let swap_path = T::DEX::get_best_price_swap_path(
currency_id,
T::GetStableCurrencyId::get(),
limit,
T::AlternativeSwapPathJointList::get(),
)
.ok_or(Error::<T>::CannotSwap)?;
T::DEX::swap_with_specific_path(&Self::account_id(), &swap_path, limit)
match currency_id {
CurrencyId::StableAssetPoolToken(stable_asset_id) => {
let pool_info = T::StableAsset::pool(stable_asset_id).ok_or(Error::<T>::CannotSwap)?;
let updated_balance_info =
T::StableAsset::get_balance_update_amount(&pool_info).ok_or(Error::<T>::CannotSwap)?;
let yield_info =
T::StableAsset::get_collect_yield_amount(&updated_balance_info).ok_or(Error::<T>::CannotSwap)?;
ensure!(
yield_info.total_supply >= pool_info.total_supply,
Error::<T>::CannotSwap,
);
let RedeemProportionResult { amounts, .. } =
T::StableAsset::get_redeem_proportion_amount(&yield_info, supply_limit)
.ok_or(Error::<T>::CannotSwap)?;
let mut swap_paths = Vec::with_capacity(amounts.len());
let mut redeem_limits = Vec::with_capacity(amounts.len());
let mut swap_limits = Vec::with_capacity(amounts.len());

for i in 0..amounts.len() {
let currency = pool_info.assets[i];
let amount = amounts[i];
let swap_limit = SwapLimit::ExactSupply(amount, 0);
swap_limits.push(swap_limit);
let swap_path = T::DEX::get_best_price_swap_path(
currency,
T::GetStableCurrencyId::get(),
swap_limit,
T::AlternativeSwapPathJointList::get(),
)
.ok_or(Error::<T>::CannotSwap)?;
swap_paths.push(swap_path);
redeem_limits.push(0);
}
T::StableAsset::redeem_proportion(&Self::account_id(), stable_asset_id, supply_limit, redeem_limits)?;

let mut supply_sum: Balance = Zero::zero();
let mut target_sum: Balance = Zero::zero();
for i in 0..amounts.len() {
let response =
T::DEX::swap_with_specific_path(&Self::account_id(), &swap_paths[i], swap_limits[i])?;
supply_sum = supply_sum.checked_add(response.0).ok_or(Error::<T>::CannotSwap)?;
target_sum = target_sum.checked_add(response.1).ok_or(Error::<T>::CannotSwap)?;
}
ensure!(target_sum >= target_limit, Error::<T>::CannotSwap,);
Ok((supply_sum, target_sum))
}
_ => {
let swap_path = T::DEX::get_best_price_swap_path(
currency_id,
T::GetStableCurrencyId::get(),
limit,
T::AlternativeSwapPathJointList::get(),
)
.ok_or(Error::<T>::CannotSwap)?;
T::DEX::swap_with_specific_path(&Self::account_id(), &swap_path, limit)
}
}
}

fn create_collateral_auctions(
Expand Down
Loading