Skip to content

Commit

Permalink
updating limit order cache also emit events.
Browse files Browse the repository at this point in the history
  • Loading branch information
syan095 committed Oct 3, 2023
1 parent 7188860 commit 36721f2
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 52 deletions.
9 changes: 3 additions & 6 deletions api/lib/src/lp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ pub struct LimitOrderReturn {
amount_total: AssetAmount,
collected_fees: AssetAmount,
bought_amount: AssetAmount,
increase_or_decrease: IncreaseOrDecrease,
amount_delta: AssetAmount,
position_delta: Option<(IncreaseOrDecrease, AssetAmount)>,
}

fn collect_limit_order_returns(
Expand All @@ -74,8 +73,7 @@ fn collect_limit_order_returns(
.filter_map(|event| match event {
state_chain_runtime::RuntimeEvent::LiquidityPools(
pallet_cf_pools::Event::LimitOrderUpdated {
increase_or_decrease,
amount_delta,
position_delta,
amount_total,
collected_fees,
bought_amount,
Expand All @@ -87,8 +85,7 @@ fn collect_limit_order_returns(
amount_total,
collected_fees,
bought_amount,
increase_or_decrease,
amount_delta,
position_delta,
}),
_ => None,
})
Expand Down
63 changes: 44 additions & 19 deletions state-chain/pallets/cf-pools/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ pub mod pallet {
}

impl<T: Config> Pool<T> {
/// Updates the position information in the Pool's cache.
pub fn update_limit_order_storage(
&mut self,
lp: &T::AccountId,
Expand Down Expand Up @@ -534,8 +535,7 @@ pub mod pallet {
buy_asset: Asset,
id: OrderId,
tick: Tick,
increase_or_decrease: IncreaseOrDecrease,
amount_delta: AssetAmount,
position_delta: Option<(IncreaseOrDecrease, AssetAmount)>,
amount_total: AssetAmount,
collected_fees: AssetAmount,
bought_amount: AssetAmount,
Expand Down Expand Up @@ -988,21 +988,47 @@ pub mod pallet {
PoolState::<(T::AccountId, OrderId)>::validate_fees(fee_hundredth_pips),
Error::<T>::InvalidFeeAmount
);
Self::try_mutate_enabled_pool(base_asset, pair_asset, |asset_pair, pool| {
pool.pool_state
.set_fees(fee_hundredth_pips)
.map_err(|_| Error::<T>::InvalidFeeAmount)?
.try_map(|side, collected_fees| {
for ((tick, (lp, order)), (collected, position_info)) in
collected_fees.into_iter()
{
asset_pair.try_credit_asset(&lp, !side, collected.fees)?;
asset_pair.try_credit_asset(&lp, !side, collected.bought_amount)?;
pool.update_limit_order_storage(&lp, side, order, tick, &position_info);
}
Result::<(), DispatchError>::Ok(())
})
})?;
Self::try_mutate_enabled_pool(
base_asset,
pair_asset,
|asset_pair: &AssetPair<T>, pool| {
pool.pool_state
.set_fees(fee_hundredth_pips)
.map_err(|_| Error::<T>::InvalidFeeAmount)?
.try_map(|side, collected_fees| {
for ((tick, (lp, order)), (collected, position_info)) in
collected_fees.into_iter()
{
let collected_fees =
asset_pair.try_credit_asset(&lp, !side, collected.fees)?;
let bought_amount = asset_pair.try_credit_asset(
&lp,
!side,
collected.bought_amount,
)?;
pool.update_limit_order_storage(
&lp,
side,
order,
tick,
&position_info,
);
Self::deposit_event(Event::<T>::LimitOrderUpdated {
lp: lp.clone(),
sell_asset: asset_pair.canonical_asset_pair.side_to_asset(side),
buy_asset: asset_pair.canonical_asset_pair.side_to_asset(!side),
id: order,
tick,
position_delta: None,
amount_total: position_info.amount.try_into()?,
collected_fees,
bought_amount,
});
}
Result::<(), DispatchError>::Ok(())
})
},
)?;

Self::deposit_event(Event::<T>::PoolFeeSet {
base_asset,
Expand Down Expand Up @@ -1201,8 +1227,7 @@ impl<T: Config> Pallet<T> {
buy_asset: asset_pair.canonical_asset_pair.side_to_asset(!asset_pair.base_side),
id,
tick,
increase_or_decrease,
amount_delta,
position_delta: Some((increase_or_decrease, amount_delta)),
amount_total: position_info.amount.try_into()?,
collected_fees,
bought_amount,
Expand Down
82 changes: 55 additions & 27 deletions state-chain/pallets/cf-pools/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::{
mock::*, utilities, AssetAmounts, AssetPair, AssetsMap, CanonicalAssetPair,
CollectedNetworkFee, Error, FlipBuyInterval, FlipToBurn, PoolInfo, PoolOrders, Pools,
CollectedNetworkFee, Error, Event, FlipBuyInterval, FlipToBurn, PoolInfo, PoolOrders, Pools,
RangeOrderSize, STABLE_ASSET,
};
use cf_amm::common::{price_at_tick, Tick};
use cf_primitives::{chains::assets::any::Asset, AssetAmount, SwapOutput};
use cf_test_utilities::assert_events_match;
use cf_test_utilities::{assert_events_match, assert_has_event};
use frame_support::{assert_noop, assert_ok, traits::Hooks};
use frame_system::pallet_prelude::BlockNumberFor;
use sp_runtime::Permill;
Expand Down Expand Up @@ -40,14 +40,12 @@ fn can_create_new_trading_pool() {
500_000u32,
default_price,
));
System::assert_last_event(RuntimeEvent::LiquidityPools(
crate::Event::<Test>::NewPoolCreated {
base_asset: unstable_asset,
pair_asset: STABLE_ASSET,
fee_hundredth_pips: 500_000u32,
initial_price: default_price,
},
));
System::assert_last_event(RuntimeEvent::LiquidityPools(Event::<Test>::NewPoolCreated {
base_asset: unstable_asset,
pair_asset: STABLE_ASSET,
fee_hundredth_pips: 500_000u32,
initial_price: default_price,
}));

// Cannot create duplicate pool
assert_noop!(
Expand Down Expand Up @@ -86,13 +84,11 @@ fn can_enable_disable_trading_pool() {
STABLE_ASSET,
false
));
System::assert_last_event(RuntimeEvent::LiquidityPools(
crate::Event::<Test>::PoolStateUpdated {
base_asset: unstable_asset,
pair_asset: STABLE_ASSET,
enabled: false,
},
));
System::assert_last_event(RuntimeEvent::LiquidityPools(Event::<Test>::PoolStateUpdated {
base_asset: unstable_asset,
pair_asset: STABLE_ASSET,
enabled: false,
}));

assert_noop!(
LiquidityPools::set_range_order(
Expand All @@ -113,13 +109,11 @@ fn can_enable_disable_trading_pool() {
STABLE_ASSET,
true
));
System::assert_last_event(RuntimeEvent::LiquidityPools(
crate::Event::<Test>::PoolStateUpdated {
base_asset: unstable_asset,
pair_asset: STABLE_ASSET,
enabled: true,
},
));
System::assert_last_event(RuntimeEvent::LiquidityPools(Event::<Test>::PoolStateUpdated {
base_asset: unstable_asset,
pair_asset: STABLE_ASSET,
enabled: true,
}));

assert_ok!(LiquidityPools::set_range_order(
RuntimeOrigin::signed(ALICE),
Expand Down Expand Up @@ -182,7 +176,7 @@ fn test_buy_back_flip_2() {
assert_events_match!(
Test,
RuntimeEvent::LiquidityPools(
crate::Event::RangeOrderUpdated {
Event::RangeOrderUpdated {
..
},
) => ()
Expand Down Expand Up @@ -275,7 +269,7 @@ fn test_network_fee_calculation() {
}

#[test]
fn can_update_pool_liquidity_fee() {
fn can_update_pool_liquidity_fee_and_collect_for_limit_order() {
new_test_ext().execute_with(|| {
let old_fee = 400_000u32;
let new_fee = 100_000u32;
Expand Down Expand Up @@ -382,7 +376,7 @@ fn can_update_pool_liquidity_fee() {
range_order_fee_hundredth_pips: new_fee,
})
);
System::assert_has_event(RuntimeEvent::LiquidityPools(crate::Event::<Test>::PoolFeeSet {
System::assert_has_event(RuntimeEvent::LiquidityPools(Event::<Test>::PoolFeeSet {
base_asset: Asset::Eth,
pair_asset: STABLE_ASSET,
fee_hundredth_pips: new_fee,
Expand Down Expand Up @@ -512,6 +506,40 @@ fn pallet_limit_order_is_in_sync_with_pool() {
Pools::<Test>::get(asset_pair.canonical_asset_pair).unwrap().limit_orders_cache;
assert_eq!(pallet_limit_orders.zero.get(&ALICE), None);
assert_eq!(pallet_limit_orders.zero.get(&BOB).unwrap().get(&0), Some(&100));

assert_has_event::<Test>(RuntimeEvent::LiquidityPools(Event::<Test>::LimitOrderUpdated {
lp: ALICE,
sell_asset: Asset::Eth,
buy_asset: STABLE_ASSET,
id: 0,
tick: 0,
position_delta: None,
amount_total: 0,
collected_fees: 100,
bought_amount: 100,
}));
assert_has_event::<Test>(RuntimeEvent::LiquidityPools(Event::<Test>::LimitOrderUpdated {
lp: BOB,
sell_asset: Asset::Eth,
buy_asset: STABLE_ASSET,
id: 0,
tick: 100,
position_delta: None,
amount_total: 5,
collected_fees: 100998,
bought_amount: 100998,
}));
assert_has_event::<Test>(RuntimeEvent::LiquidityPools(Event::<Test>::LimitOrderUpdated {
lp: BOB,
sell_asset: STABLE_ASSET,
buy_asset: Asset::Eth,
id: 1,
tick: 100,
position_delta: None,
amount_total: 910,
collected_fees: 8998,
bought_amount: 8998,
}));
});
}

Expand Down

0 comments on commit 36721f2

Please sign in to comment.