Skip to content

Commit

Permalink
refactor: ♻️ renamed AssetsMap
Browse files Browse the repository at this point in the history
  • Loading branch information
Janislav committed Feb 13, 2024
1 parent 53b8957 commit 5aa4e57
Show file tree
Hide file tree
Showing 12 changed files with 119 additions and 111 deletions.
8 changes: 4 additions & 4 deletions api/bin/chainflip-lp-api/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use chainflip_api::{
self,
lp::{
types::{LimitOrder, RangeOrder},
ApiWaitForResult, AssetsMap, LpApi, Side, Tick,
ApiWaitForResult, LpApi, PoolPairsMap, Side, Tick,
},
primitives::{
chains::{Bitcoin, Ethereum, Polkadot},
Expand Down Expand Up @@ -47,7 +47,7 @@ pub mod rpc_types {
use super::*;
use anyhow::anyhow;
use cf_utilities::rpc::NumberOrHex;
use chainflip_api::{lp::AssetsMap, queries::SwapChannelInfo};
use chainflip_api::{lp::PoolPairsMap, queries::SwapChannelInfo};
use serde::{Deserialize, Serialize};

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
Expand All @@ -62,7 +62,7 @@ pub mod rpc_types {

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum RangeOrderSizeJson {
AssetAmounts { maximum: AssetsMap<NumberOrHex>, minimum: AssetsMap<NumberOrHex> },
AssetAmounts { maximum: PoolPairsMap<NumberOrHex>, minimum: PoolPairsMap<NumberOrHex> },
Liquidity { liquidity: NumberOrHex },
}
impl TryFrom<RangeOrderSizeJson> for RangeOrderSize {
Expand Down Expand Up @@ -242,7 +242,7 @@ pub enum OrderFilled {
quote_asset: Asset,
id: U256,
range: Range<Tick>,
fees: AssetsMap<U256>,
fees: PoolPairsMap<U256>,
liquidity: U256,
},
}
Expand Down
6 changes: 3 additions & 3 deletions api/lib/src/lp.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
pub use cf_amm::{
common::{Amount, AssetsMap, Side, Tick},
common::{Amount, PoolPairsMap, Side, Tick},
range_orders::Liquidity,
};
use cf_chains::address::EncodedAddress;
Expand Down Expand Up @@ -50,14 +50,14 @@ pub mod types {
pub id: U256,
pub tick_range: Range<Tick>,
pub liquidity_total: U256,
pub collected_fees: AssetsMap<U256>,
pub collected_fees: PoolPairsMap<U256>,
pub size_change: Option<IncreaseOrDecrease<RangeOrderChange>>,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct RangeOrderChange {
pub liquidity: U256,
pub amounts: AssetsMap<U256>,
pub amounts: PoolPairsMap<U256>,
}

#[derive(Serialize, Deserialize, Clone)]
Expand Down
49 changes: 26 additions & 23 deletions state-chain/amm/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,49 +104,52 @@ impl Pairs {
Serialize,
Deserialize,
)]
pub struct AssetsMap<T> {
pub struct PoolPairsMap<T> {
pub base: T,
pub quote: T,
}

impl<T> AssetsMap<T> {
impl<T> PoolPairsMap<T> {
pub fn from_array(array: [T; 2]) -> Self {
let [base, quote] = array;
Self { base, quote }
}

pub fn map<R, F: FnMut(T) -> R>(self, mut f: F) -> AssetsMap<R> {
AssetsMap { base: f(self.base), quote: f(self.quote) }
pub fn map<R, F: FnMut(T) -> R>(self, mut f: F) -> PoolPairsMap<R> {
PoolPairsMap { base: f(self.base), quote: f(self.quote) }
}

pub fn try_map<R, E, F: FnMut(T) -> Result<R, E>>(self, mut f: F) -> Result<AssetsMap<R>, E> {
Ok(AssetsMap { base: f(self.base)?, quote: f(self.quote)? })
pub fn try_map<R, E, F: FnMut(T) -> Result<R, E>>(
self,
mut f: F,
) -> Result<PoolPairsMap<R>, E> {
Ok(PoolPairsMap { base: f(self.base)?, quote: f(self.quote)? })
}

pub fn try_map_with_pair<R, E>(
self,
mut f: impl FnMut(Pairs, T) -> Result<R, E>,
) -> Result<AssetsMap<R>, E> {
Ok(AssetsMap { base: f(Pairs::Base, self.base)?, quote: f(Pairs::Quote, self.quote)? })
) -> Result<PoolPairsMap<R>, E> {
Ok(PoolPairsMap { base: f(Pairs::Base, self.base)?, quote: f(Pairs::Quote, self.quote)? })
}

pub fn as_ref(&self) -> AssetsMap<&T> {
AssetsMap { base: &self.base, quote: &self.quote }
pub fn as_ref(&self) -> PoolPairsMap<&T> {
PoolPairsMap { base: &self.base, quote: &self.quote }
}

pub fn as_mut(&mut self) -> AssetsMap<&mut T> {
AssetsMap { base: &mut self.base, quote: &mut self.quote }
pub fn as_mut(&mut self) -> PoolPairsMap<&mut T> {
PoolPairsMap { base: &mut self.base, quote: &mut self.quote }
}

pub fn zip<S>(self, other: AssetsMap<S>) -> AssetsMap<(T, S)> {
AssetsMap { base: (self.base, other.base), quote: (self.quote, other.quote) }
pub fn zip<S>(self, other: PoolPairsMap<S>) -> PoolPairsMap<(T, S)> {
PoolPairsMap { base: (self.base, other.base), quote: (self.quote, other.quote) }
}

pub fn map_with_pair<R, F: FnMut(Pairs, T) -> R>(self, mut f: F) -> AssetsMap<R> {
AssetsMap { base: f(Pairs::Base, self.base), quote: f(Pairs::Quote, self.quote) }
pub fn map_with_pair<R, F: FnMut(Pairs, T) -> R>(self, mut f: F) -> PoolPairsMap<R> {
PoolPairsMap { base: f(Pairs::Base, self.base), quote: f(Pairs::Quote, self.quote) }
}
}
impl<T> IntoIterator for AssetsMap<T> {
impl<T> IntoIterator for PoolPairsMap<T> {
type Item = (Pairs, T);

type IntoIter = core::array::IntoIter<(Pairs, T), 2>;
Expand All @@ -155,7 +158,7 @@ impl<T> IntoIterator for AssetsMap<T> {
[(Pairs::Base, self.base), (Pairs::Quote, self.quote)].into_iter()
}
}
impl<T> core::ops::Index<Pairs> for AssetsMap<T> {
impl<T> core::ops::Index<Pairs> for PoolPairsMap<T> {
type Output = T;
fn index(&self, side: Pairs) -> &T {
match side {
Expand All @@ -164,18 +167,18 @@ impl<T> core::ops::Index<Pairs> for AssetsMap<T> {
}
}
}
impl<T> core::ops::IndexMut<Pairs> for AssetsMap<T> {
impl<T> core::ops::IndexMut<Pairs> for PoolPairsMap<T> {
fn index_mut(&mut self, side: Pairs) -> &mut T {
match side {
Pairs::Base => &mut self.base,
Pairs::Quote => &mut self.quote,
}
}
}
impl<T: core::ops::Add<R>, R> core::ops::Add<AssetsMap<R>> for AssetsMap<T> {
type Output = AssetsMap<<T as core::ops::Add<R>>::Output>;
fn add(self, rhs: AssetsMap<R>) -> Self::Output {
AssetsMap { base: self.base + rhs.base, quote: self.quote + rhs.quote }
impl<T: core::ops::Add<R>, R> core::ops::Add<PoolPairsMap<R>> for PoolPairsMap<T> {
type Output = PoolPairsMap<<T as core::ops::Add<R>>::Output>;
fn add(self, rhs: PoolPairsMap<R>) -> Self::Output {
PoolPairsMap { base: self.base + rhs.base, quote: self.quote + rhs.quote }
}
}

Expand Down
23 changes: 12 additions & 11 deletions state-chain/amm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use core::convert::Infallible;
use codec::{Decode, Encode};
use common::{
is_sqrt_price_valid, price_to_sqrt_price, sqrt_price_to_price, tick_at_sqrt_price, Amount,
AssetsMap, BaseToQuote, Pairs, Price, QuoteToBase, SetFeesError, Side, SqrtPriceQ64F96,
BaseToQuote, Pairs, PoolPairsMap, Price, QuoteToBase, SetFeesError, Side, SqrtPriceQ64F96,
SwapDirection, Tick,
};
use limit_orders::{Collected, PositionInfo};
Expand Down Expand Up @@ -261,7 +261,7 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
pub fn collect_and_mint_range_order<
T,
E,
TryDebit: FnOnce(AssetsMap<Amount>) -> Result<T, E>,
TryDebit: FnOnce(PoolPairsMap<Amount>) -> Result<T, E>,
>(
&mut self,
lp: &LiquidityProvider,
Expand All @@ -283,7 +283,7 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
size: range_orders::Size,
) -> Result<
(
AssetsMap<Amount>,
PoolPairsMap<Amount>,
range_orders::Liquidity,
range_orders::Collected,
range_orders::PositionInfo,
Expand All @@ -297,15 +297,15 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
&self,
tick_range: core::ops::Range<Tick>,
liquidity: Liquidity,
) -> Result<AssetsMap<Amount>, range_orders::LiquidityToAmountsError> {
) -> Result<PoolPairsMap<Amount>, range_orders::LiquidityToAmountsError> {
self.range_orders
.liquidity_to_amounts::<true>(liquidity, tick_range.start, tick_range.end)
}

pub fn required_asset_ratio_for_range_order(
&self,
tick_range: core::ops::Range<Tick>,
) -> Result<AssetsMap<Amount>, range_orders::RequiredAssetRatioError> {
) -> Result<PoolPairsMap<Amount>, range_orders::RequiredAssetRatioError> {
self.range_orders
.required_asset_ratio::<false>(tick_range.start, tick_range.end)
}
Expand Down Expand Up @@ -396,8 +396,8 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
pub fn limit_order_depth(
&mut self,
range: core::ops::Range<Tick>,
) -> Result<AssetsMap<(Option<Price>, Amount)>, limit_orders::DepthError> {
Ok(AssetsMap {
) -> Result<PoolPairsMap<(Option<Price>, Amount)>, limit_orders::DepthError> {
Ok(PoolPairsMap {
base: (
self.limit_orders.current_sqrt_price::<QuoteToBase>(),
self.limit_orders.depth::<QuoteToBase>(range.clone())?,
Expand All @@ -412,8 +412,8 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
pub fn range_order_depth(
&self,
range: core::ops::Range<Tick>,
) -> Result<AssetsMap<(Option<Price>, Amount)>, range_orders::DepthError> {
self.range_orders.depth(range.start, range.end).map(|assets| AssetsMap {
) -> Result<PoolPairsMap<(Option<Price>, Amount)>, range_orders::DepthError> {
self.range_orders.depth(range.start, range.end).map(|assets| PoolPairsMap {
base: (
self.range_orders.current_sqrt_price::<QuoteToBase>().map(sqrt_price_to_price),
assets[Pairs::Base],
Expand All @@ -429,7 +429,8 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
pub fn set_fees(
&mut self,
fee_hundredth_pips: u32,
) -> Result<AssetsMap<Vec<(LiquidityProvider, Tick, Collected, PositionInfo)>>, SetFeesError> {
) -> Result<PoolPairsMap<Vec<(LiquidityProvider, Tick, Collected, PositionInfo)>>, SetFeesError>
{
self.range_orders.set_fees(fee_hundredth_pips)?;
self.limit_orders.set_fees(fee_hundredth_pips)
}
Expand All @@ -452,7 +453,7 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {

pub fn collect_all_limit_orders(
&mut self,
) -> AssetsMap<
) -> PoolPairsMap<
Vec<(LiquidityProvider, Tick, limit_orders::Collected, limit_orders::PositionInfo)>,
> {
self.limit_orders.collect_all()
Expand Down
32 changes: 17 additions & 15 deletions state-chain/amm/src/limit_orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use sp_std::vec::Vec;

use crate::common::{
is_tick_valid, mul_div_ceil, mul_div_floor, sqrt_price_at_tick, sqrt_price_to_price,
tick_at_sqrt_price, Amount, AssetsMap, BaseToQuote, Price, QuoteToBase, SetFeesError,
tick_at_sqrt_price, Amount, BaseToQuote, PoolPairsMap, Price, QuoteToBase, SetFeesError,
SqrtPriceQ64F96, Tick, MAX_LP_FEE, ONE_IN_HUNDREDTH_PIPS, PRICE_FRACTIONAL_BITS,
};

Expand Down Expand Up @@ -381,19 +381,20 @@ pub(super) struct PoolState<LiquidityProvider: Ord> {
/// The ID the next FixedPool that is created will use.
next_pool_instance: u128,
/// All the FixedPools that have some liquidity. They are grouped into all those that are
/// selling asset `Base` and all those that are selling asset `Quote` used the AssetsMap.
fixed_pools: AssetsMap<BTreeMap<SqrtPriceQ64F96, FixedPool>>,
/// selling asset `Base` and all those that are selling asset `Quote` used the PoolPairsMap.
fixed_pools: PoolPairsMap<BTreeMap<SqrtPriceQ64F96, FixedPool>>,
/// All the Positions that either are providing liquidity currently, or were providing
/// liquidity directly after the last time they where updated. They are grouped into all those
/// that are selling asset `Base` and all those that are selling asset `Quote` used the
/// AssetsMap. Therefore there can be positions stored here that don't provide any liquidity.
positions: AssetsMap<BTreeMap<(SqrtPriceQ64F96, LiquidityProvider), Position>>,
/// PoolPairsMap. Therefore there can be positions stored here that don't provide any
/// liquidity.
positions: PoolPairsMap<BTreeMap<(SqrtPriceQ64F96, LiquidityProvider), Position>>,
/// Total fees earned over all time
total_fees_earned: AssetsMap<Amount>,
total_fees_earned: PoolPairsMap<Amount>,
/// Total of all swap inputs over all time (not including fees)
total_swap_inputs: AssetsMap<Amount>,
total_swap_inputs: PoolPairsMap<Amount>,
/// Total of all swap outputs over all time
total_swap_outputs: AssetsMap<Amount>,
total_swap_outputs: PoolPairsMap<Amount>,
}

impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
Expand Down Expand Up @@ -441,18 +442,18 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
})
}

/// Runs collect for all positions in the pool. Returns a AssetsMap
/// Runs collect for all positions in the pool. Returns a PoolPairsMap
/// containing the state and fees collected from every position. The positions are grouped into
/// a AssetsMap by the asset they sell.
/// a PoolPairsMap by the asset they sell.
///
/// This function never panics.
#[allow(clippy::type_complexity)]
pub(super) fn collect_all(
&mut self,
) -> AssetsMap<Vec<(LiquidityProvider, Tick, Collected, PositionInfo)>> {
) -> PoolPairsMap<Vec<(LiquidityProvider, Tick, Collected, PositionInfo)>> {
// We must collect all positions before we can change the fee, otherwise the fee and swapped
// liquidity calculations would be wrong.
AssetsMap::from_array([
PoolPairsMap::from_array([
self.positions[!<QuoteToBase as crate::common::SwapDirection>::INPUT_SIDE]
.keys()
.cloned()
Expand Down Expand Up @@ -481,16 +482,17 @@ impl<LiquidityProvider: Clone + Ord> PoolState<LiquidityProvider> {
}

/// Sets the fee for the pool. This will apply to future swaps. The fee may not be set
/// higher than 50%. Also runs collect for all positions in the pool. Returns a AssetsMap
/// higher than 50%. Also runs collect for all positions in the pool. Returns a PoolPairsMap
/// containing the state and fees collected from every position as part of the set_fees
/// operation. The positions are grouped into a AssetsMap by the asset they sell.
/// operation. The positions are grouped into a PoolPairsMap by the asset they sell.
///
/// This function never panics.
#[allow(clippy::type_complexity)]
pub(super) fn set_fees(
&mut self,
fee_hundredth_pips: u32,
) -> Result<AssetsMap<Vec<(LiquidityProvider, Tick, Collected, PositionInfo)>>, SetFeesError> {
) -> Result<PoolPairsMap<Vec<(LiquidityProvider, Tick, Collected, PositionInfo)>>, SetFeesError>
{
Self::validate_fees(fee_hundredth_pips)
.then_some(())
.ok_or(SetFeesError::InvalidFeeAmount)?;
Expand Down
Loading

0 comments on commit 5aa4e57

Please sign in to comment.