Skip to content

Commit

Permalink
add max auctions count to avoid too much iterations affecting block p…
Browse files Browse the repository at this point in the history
…roduce (#245)

* add weight to on_initialize on dex

* add max auctions count to avoid affecting block produce
  • Loading branch information
wangjj9219 authored May 25, 2020
1 parent 9fb9005 commit d71912c
Show file tree
Hide file tree
Showing 16 changed files with 183 additions and 7 deletions.
5 changes: 5 additions & 0 deletions modules/auction_manager/benchmarking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,18 @@ ord_parameter_types! {
pub const One: AccountId = 1;
}

parameter_types! {
pub const MaxAuctionsCount: u32 = 10_000;
}

impl cdp_treasury::Trait for Runtime {
type Event = ();
type Currency = Currencies;
type GetStableCurrencyId = GetStableCurrencyId;
type AuctionManagerHandler = AuctionManagerModule;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = ();
type MaxAuctionsCount = MaxAuctionsCount;
}
pub type CDPTreasuryModule = cdp_treasury::Module<Runtime>;

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 @@ -108,6 +108,7 @@ ord_parameter_types! {

parameter_types! {
pub const GetStableCurrencyId: CurrencyId = AUSD;
pub const MaxAuctionsCount: u32 = 10_000;
}

impl cdp_treasury::Trait for Runtime {
Expand All @@ -117,6 +118,7 @@ impl cdp_treasury::Trait for Runtime {
type AuctionManagerHandler = AuctionManagerModule;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = ();
type MaxAuctionsCount = MaxAuctionsCount;
}
pub type CDPTreasuryModule = cdp_treasury::Module<Runtime>;

Expand Down
2 changes: 2 additions & 0 deletions modules/cdp_engine/benchmarking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ ord_parameter_types! {

parameter_types! {
pub const GetStableCurrencyId: CurrencyId = AUSD;
pub const MaxAuctionsCount: u32 = 10_000;
}

impl cdp_treasury::Trait for Runtime {
Expand All @@ -168,6 +169,7 @@ impl cdp_treasury::Trait for Runtime {
type AuctionManagerHandler = MockAuctionManager;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = DexModule;
type MaxAuctionsCount = MaxAuctionsCount;
}
pub type CDPTreasuryModule = cdp_treasury::Module<Runtime>;

Expand Down
2 changes: 2 additions & 0 deletions modules/cdp_engine/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ impl AuctionManager<AccountId> for MockAuctionManager {

parameter_types! {
pub const GetStableCurrencyId: CurrencyId = AUSD;
pub const MaxAuctionsCount: u32 = 10_000;
}

impl cdp_treasury::Trait for Runtime {
Expand All @@ -206,6 +207,7 @@ impl cdp_treasury::Trait for Runtime {
type AuctionManagerHandler = MockAuctionManager;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = DEXModule;
type MaxAuctionsCount = MaxAuctionsCount;
}
pub type CDPTreasuryModule = cdp_treasury::Module<Runtime>;

Expand Down
30 changes: 28 additions & 2 deletions modules/cdp_treasury/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ pub trait Trait: system::Trait {

/// Dex manager is used to swap confiscated collateral assets to stable coin
type DEX: DEXManager<Self::AccountId, CurrencyId, Balance>;

/// 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.
type MaxAuctionsCount: Get<u32>;
}

decl_event!(
Expand Down Expand Up @@ -128,6 +133,9 @@ decl_module! {
/// Stablecoin currency id
const GetStableCurrencyId: CurrencyId = T::GetStableCurrencyId::get();

/// Lots cap when create auction
const MaxAuctionsCount: u32 = T::MaxAuctionsCount::get();

/// Update parameters related to surplus and debit auction
///
/// The dispatch origin of this call must be `UpdateOrigin` or _Root_.
Expand Down Expand Up @@ -203,6 +211,9 @@ decl_module! {

// Stop to create surplus auction and debit auction after emergency shutdown happend.
if !Self::is_shutdown() {
let max_auctions_count: u32 = T::MaxAuctionsCount::get();
let mut created_lots: u32 = 0;

let surplus_auction_fixed_size = Self::surplus_auction_fixed_size();
if !surplus_auction_fixed_size.is_zero() {
let mut remain_surplus_pool = Self::surplus_pool();
Expand All @@ -212,7 +223,11 @@ decl_module! {
// create surplus auction requires:
// surplus_pool >= total_surplus_in_auction + surplus_buffer_size + surplus_auction_fixed_size
while remain_surplus_pool >= total_surplus_in_auction + surplus_buffer_size + surplus_auction_fixed_size {
if max_auctions_count != 0 && created_lots >= max_auctions_count {
break
}
T::AuctionManagerHandler::new_surplus_auction(surplus_auction_fixed_size);
created_lots += 1;
remain_surplus_pool -= surplus_auction_fixed_size;
}
}
Expand All @@ -227,7 +242,11 @@ decl_module! {
// create debit auction requires:
// debit_pool > total_debit_in_auction + total_target_in_auction + debit_auction_fixed_size
while remain_debit_pool >= total_debit_in_auction + total_target_in_auction + debit_auction_fixed_size {
if max_auctions_count != 0 && created_lots >= max_auctions_count {
break
}
T::AuctionManagerHandler::new_debit_auction(initial_amount_per_debit_auction, debit_auction_fixed_size);
created_lots += 1;
remain_debit_pool -= debit_auction_fixed_size;
}
}
Expand Down Expand Up @@ -385,14 +404,21 @@ impl<T: Trait> CDPTreasuryExtended<T::AccountId> for Module<T> {
let collateral_auction_maximum_size = Self::collateral_auction_maximum_size(currency_id);
let mut unhandled_collateral_amount = amount;
let mut unhandled_target = target;
let max_auctions_count: u32 = T::MaxAuctionsCount::get();
let mut created_lots: u32 = 0;

while !unhandled_collateral_amount.is_zero() {
let (lot_collateral_amount, lot_target) = if unhandled_collateral_amount
> collateral_auction_maximum_size
&& !collateral_auction_maximum_size.is_zero()
{
let proportion = Ratio::from_rational(collateral_auction_maximum_size, amount);
(collateral_auction_maximum_size, proportion.saturating_mul_int(&target))
if max_auctions_count != 0 && created_lots >= max_auctions_count {
(unhandled_collateral_amount, unhandled_target)
} else {
created_lots += 1;
let proportion = Ratio::from_rational(collateral_auction_maximum_size, amount);
(collateral_auction_maximum_size, proportion.saturating_mul_int(&target))
}
} else {
(unhandled_collateral_amount, unhandled_target)
};
Expand Down
18 changes: 16 additions & 2 deletions modules/cdp_treasury/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use frame_support::{impl_outer_event, impl_outer_origin, ord_parameter_types, pa
use frame_system::EnsureSignedBy;
use sp_core::H256;
use sp_runtime::{testing::Header, traits::IdentityLookup, Perbill};
use sp_std::cell::RefCell;
use support::Rate;

pub type AccountId = u64;
Expand Down Expand Up @@ -129,6 +130,12 @@ impl dex::Trait for Runtime {
}
pub type DEXModule = dex::Module<Runtime>;

thread_local! {
pub static TOTAL_COLLATERAL_AUCTION: RefCell<u32> = RefCell::new(0);
pub static TOTAL_DEBIT_AUCTION: RefCell<u32> = RefCell::new(0);
pub static TOTAL_SURPLUS_AUCTION: RefCell<u32> = RefCell::new(0);
}

pub struct MockAuctionManager;
impl AuctionManager<AccountId> for MockAuctionManager {
type CurrencyId = CurrencyId;
Expand All @@ -141,11 +148,16 @@ impl AuctionManager<AccountId> for MockAuctionManager {
_amount: Self::Balance,
_target: Self::Balance,
) {
TOTAL_COLLATERAL_AUCTION.with(|v| *v.borrow_mut() += 1);
}

fn new_debit_auction(_amount: Self::Balance, _fix: Self::Balance) {}
fn new_debit_auction(_amount: Self::Balance, _fix: Self::Balance) {
TOTAL_DEBIT_AUCTION.with(|v| *v.borrow_mut() += 1);
}

fn new_surplus_auction(_amount: Self::Balance) {}
fn new_surplus_auction(_amount: Self::Balance) {
TOTAL_SURPLUS_AUCTION.with(|v| *v.borrow_mut() += 1);
}

fn cancel_auction(_id: Self::AuctionId) -> DispatchResult {
Ok(())
Expand All @@ -170,6 +182,7 @@ impl AuctionManager<AccountId> for MockAuctionManager {

ord_parameter_types! {
pub const One: AccountId = 1;
pub const MaxAuctionsCount: u32 = 5;
}

impl Trait for Runtime {
Expand All @@ -179,6 +192,7 @@ impl Trait for Runtime {
type AuctionManagerHandler = MockAuctionManager;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = DEXModule;
type MaxAuctionsCount = MaxAuctionsCount;
}
pub type CDPTreasuryModule = Module<Runtime>;

Expand Down
74 changes: 74 additions & 0 deletions modules/cdp_treasury/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use super::*;
use frame_support::{assert_noop, assert_ok, traits::OnFinalize};
use mock::{
CDPTreasuryModule, Currencies, DEXModule, ExtBuilder, Origin, Runtime, System, TestEvent, ALICE, AUSD, BOB, BTC,
TOTAL_COLLATERAL_AUCTION, TOTAL_DEBIT_AUCTION, TOTAL_SURPLUS_AUCTION,
};
use sp_runtime::traits::BadOrigin;

Expand Down Expand Up @@ -248,3 +249,76 @@ fn swap_collateral_to_stable_work() {
assert_eq!(CDPTreasuryModule::surplus_pool(), 500);
});
}

#[test]
fn create_collateral_auctions_work() {
ExtBuilder::default().build().execute_with(|| {
TotalCollaterals::mutate(BTC, |balance| *balance += 10000);
assert_eq!(CDPTreasuryModule::collateral_auction_maximum_size(BTC), 0);

// without collateral auction maximum size
CDPTreasuryModule::create_collateral_auctions(BTC, 1000, 1000, ALICE);
assert_eq!(TOTAL_COLLATERAL_AUCTION.with(|v| *v.borrow_mut()), 1);

// set collateral auction maximum size
assert_ok!(CDPTreasuryModule::set_collateral_auction_maximum_size(
Origin::signed(1),
BTC,
300
));

// not exceed lots cap
CDPTreasuryModule::create_collateral_auctions(BTC, 1000, 1000, ALICE);
assert_eq!(TOTAL_COLLATERAL_AUCTION.with(|v| *v.borrow_mut()), 5);

// exceed lots cap
CDPTreasuryModule::create_collateral_auctions(BTC, 2000, 1000, ALICE);
assert_eq!(TOTAL_COLLATERAL_AUCTION.with(|v| *v.borrow_mut()), 11);
});
}

#[test]
fn create_surplus_auction_when_on_finalize() {
ExtBuilder::default().build().execute_with(|| {
SurplusPool::put(1000);
assert_ok!(CDPTreasuryModule::set_debit_and_surplus_handle_params(
Origin::ROOT,
Some(300),
None,
None,
None,
));

// not exceed lots cap
CDPTreasuryModule::on_finalize(1);
assert_eq!(TOTAL_SURPLUS_AUCTION.with(|v| *v.borrow_mut()), 3);

// exceed lots cap
SurplusPool::put(2000);
CDPTreasuryModule::on_finalize(1);
assert_eq!(TOTAL_SURPLUS_AUCTION.with(|v| *v.borrow_mut()), 8);
});
}

#[test]
fn create_debit_auction_when_on_finalize() {
ExtBuilder::default().build().execute_with(|| {
DebitPool::put(1000);
assert_ok!(CDPTreasuryModule::set_debit_and_surplus_handle_params(
Origin::ROOT,
None,
None,
Some(100),
Some(300),
));

// not exceed lots cap
CDPTreasuryModule::on_finalize(1);
assert_eq!(TOTAL_DEBIT_AUCTION.with(|v| *v.borrow_mut()), 3);

// exceed lots cap
DebitPool::put(2000);
CDPTreasuryModule::on_finalize(1);
assert_eq!(TOTAL_DEBIT_AUCTION.with(|v| *v.borrow_mut()), 8);
});
}
17 changes: 17 additions & 0 deletions modules/dex/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,23 @@ benchmarks! {

}: _(RawOrigin::Signed(maker), currency_id)

accumulate_interest {
let u in 0 .. 1000;

let maker: T::AccountId = account("maker", u, SEED);
let currency_id = T::EnabledCurrencyIds::get()[0];
inject_liquidity::<T>(maker.clone(), currency_id, dollar(100), dollar(10000))?;

// set incentive rate
Dex::<T>::set_liquidity_incentive_rate(
RawOrigin::Root.into(),
currency_id,
Rate::from_rational(1, 10),
)?;
}: {
Dex::<T>::accumulate_interest(currency_id);
}

// `swap_currency`, best case:
// swap other currency to base currency
swap_other_to_base {
Expand Down
20 changes: 18 additions & 2 deletions modules/dex/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,14 +409,30 @@ decl_module! {
}

/// Accumalte liquidity incentive interest to respective reward pool when block end
///
/// # <weight>
/// - Complexity: `O(N)` where `N` is the number of currency_ids
/// - Db reads: `IsShutdown`, `TotalInterest`, 2 items in cdp_treasury
/// - Db writes: `TotalInterest`, 2 items in cdp_treasury
/// - Db reads per currency_id: , `LiquidityPool`, `LiquidityIncentiveRate`
/// -------------------
/// Base Weight: 35.45 * N µs
/// # </weight>
fn on_initialize(_n: T::BlockNumber) -> Weight {
let mut consumed_weight = 0;
let mut add_weight = |reads, writes, weight| {
consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
consumed_weight += weight;
};

if !Self::is_shutdown() {
add_weight(4, 3, 0);
for currency_id in T::EnabledCurrencyIds::get() {
Self::accumulate_interest(currency_id);
add_weight(2, 0, 36_000_000);
}
}

0
consumed_weight
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions modules/dex/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ ord_parameter_types! {

parameter_types! {
pub const GetStableCurrencyId: CurrencyId = AUSD;
pub const MaxAuctionsCount: u32 = 10_000;
}

impl cdp_treasury::Trait for Runtime {
Expand All @@ -100,6 +101,7 @@ impl cdp_treasury::Trait for Runtime {
type AuctionManagerHandler = MockAuctionManagerHandler;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = ();
type MaxAuctionsCount = MaxAuctionsCount;
}
pub type CDPTreasuryModule = cdp_treasury::Module<Runtime>;

Expand Down
2 changes: 2 additions & 0 deletions modules/emergency_shutdown/benchmarking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ ord_parameter_types! {

parameter_types! {
pub const GetStableCurrencyId: CurrencyId = AUSD;
pub const MaxAuctionsCount: u32 = 10_000;
}

impl cdp_treasury::Trait for Runtime {
Expand All @@ -167,6 +168,7 @@ impl cdp_treasury::Trait for Runtime {
type AuctionManagerHandler = MockAuctionManager;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = ();
type MaxAuctionsCount = MaxAuctionsCount;
}
pub type CDPTreasuryModule = cdp_treasury::Module<Runtime>;

Expand Down
2 changes: 2 additions & 0 deletions modules/emergency_shutdown/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ ord_parameter_types! {

parameter_types! {
pub const GetStableCurrencyId: CurrencyId = AUSD;
pub const MaxAuctionsCount: u32 = 10_000;
}

impl cdp_treasury::Trait for Runtime {
Expand All @@ -205,6 +206,7 @@ impl cdp_treasury::Trait for Runtime {
type AuctionManagerHandler = MockAuctionManager;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = ();
type MaxAuctionsCount = MaxAuctionsCount;
}
pub type CDPTreasuryModule = cdp_treasury::Module<Runtime>;

Expand Down
Loading

0 comments on commit d71912c

Please sign in to comment.