Skip to content

Commit

Permalink
fix: trade logic to handle insufficient liquidity errors (#75)
Browse files Browse the repository at this point in the history
Updated trade and pool logic to better handle insufficient liquidity scenarios by checking for remaining amounts and integrating new error handling. Adjusted tests to reflect these changes and ensure correct behavior.
  • Loading branch information
shuhuiluo committed Sep 9, 2024
1 parent 84c7139 commit 01439b6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 35 deletions.
39 changes: 28 additions & 11 deletions src/entities/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,11 +286,22 @@ impl<TP: TickDataProvider> Pool<TP> {

let zero_for_one = input_amount.currency.equals(&self.token0);

let (output_amount, sqrt_ratio_x96, liquidity, _) = self._swap(
let SwapState {
amount_specified_remaining,
amount_calculated: output_amount,
sqrt_price_x96,
liquidity,
..
} = self._swap(
zero_for_one,
I256::from_big_int(input_amount.quotient()),
sqrt_price_limit_x96,
)?;

if !amount_specified_remaining.is_zero() && sqrt_price_limit_x96.is_none() {
return Err(Error::InsufficientLiquidity);
}

let output_token = if zero_for_one {
self.token1.clone()
} else {
Expand All @@ -302,7 +313,7 @@ impl<TP: TickDataProvider> Pool<TP> {
self.token0.clone(),
self.token1.clone(),
self.fee,
sqrt_ratio_x96,
sqrt_price_x96,
liquidity,
self.tick_data_provider.clone(),
)?,
Expand Down Expand Up @@ -330,11 +341,22 @@ impl<TP: TickDataProvider> Pool<TP> {

let zero_for_one = output_amount.currency.equals(&self.token1);

let (input_amount, sqrt_ratio_x96, liquidity, _) = self._swap(
let SwapState {
amount_specified_remaining,
amount_calculated: input_amount,
sqrt_price_x96,
liquidity,
..
} = self._swap(
zero_for_one,
I256::from_big_int(-output_amount.quotient()),
sqrt_price_limit_x96,
)?;

if !amount_specified_remaining.is_zero() && sqrt_price_limit_x96.is_none() {
return Err(Error::InsufficientLiquidity);
}

let input_token = if zero_for_one {
self.token0.clone()
} else {
Expand All @@ -346,7 +368,7 @@ impl<TP: TickDataProvider> Pool<TP> {
self.token0.clone(),
self.token1.clone(),
self.fee,
sqrt_ratio_x96,
sqrt_price_x96,
liquidity,
self.tick_data_provider.clone(),
)?,
Expand All @@ -358,7 +380,7 @@ impl<TP: TickDataProvider> Pool<TP> {
zero_for_one: bool,
amount_specified: I256,
sqrt_price_limit_x96: Option<U160>,
) -> Result<(I256, U160, u128, TP::Index), Error> {
) -> Result<SwapState<TP::Index>, Error> {
let sqrt_price_limit_x96 = sqrt_price_limit_x96.unwrap_or_else(|| {
if zero_for_one {
MIN_SQRT_RATIO + ONE
Expand Down Expand Up @@ -466,12 +488,7 @@ impl<TP: TickDataProvider> Pool<TP> {
}
}

Ok((
state.amount_calculated,
state.sqrt_price_x96,
state.liquidity,
state.tick,
))
Ok(state)
}
}

Expand Down
41 changes: 17 additions & 24 deletions src/entities/trade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,16 +669,17 @@ where
};
let token_out = currency_out.wrapped();
for pool in pools.iter() {
let current_token_out = if pool.token0.equals(&amount_in.currency) {
&pool.token1
} else if pool.token1.equals(&amount_in.currency) {
&pool.token0
} else {
// pool irrelevant
// pool irrelevant
if !pool.involves_token(&amount_in.currency) {
continue;
}
let amount_out = match pool.get_output_amount(&amount_in, None) {
Ok((amount_out, _)) => amount_out,
Err(Error::InsufficientLiquidity) => continue,
Err(e) => return Err(e),
};
// we have arrived at the output token, so this is the final trade of one of the paths
if !current_token_out.is_native() && current_token_out.equals(token_out) {
if !amount_out.currency.is_native() && amount_out.currency.equals(token_out) {
let mut next_pools = current_pools.clone();
next_pools.push(pool.clone());
let trade = Self::from_route(
Expand All @@ -701,8 +702,6 @@ where
// have not exceeded maxHops
let mut next_pools = current_pools.clone();
next_pools.push(pool.clone());

let (amount_out, _) = pool.get_output_amount(&amount_in, None)?;
Self::best_trade_exact_in(
pools_excluding_this_pool,
currency_amount_in.clone(),
Expand Down Expand Up @@ -758,19 +757,17 @@ where
};
let token_in = currency_in.wrapped();
for pool in pools.iter() {
let current_token_in = if pool.token0.equals(&amount_out.currency) {
&pool.token1
} else if pool.token1.equals(&amount_out.currency) {
&pool.token0
} else {
// pool irrelevant
continue;
};
// pool irrelevant
if !pool.involves_token(&amount_out.currency) {
continue;
}
let amount_in = match pool.get_input_amount(&amount_out, None) {
Ok((amount_in, _)) => amount_in,
Err(Error::InsufficientLiquidity) => continue,
Err(e) => return Err(e),
};
// we have arrived at the input token, so this is the first trade of one of the paths
if current_token_in.equals(token_in) {
if amount_in.currency.equals(token_in) {
let mut next_pools = vec![pool.clone()];
next_pools.extend(current_pools.clone());
let trade = Self::from_route(
Expand All @@ -793,8 +790,6 @@ where
// have not exceeded maxHops
let mut next_pools = vec![pool.clone()];
next_pools.extend(current_pools.clone());

let (amount_in, _) = pool.get_input_amount(&amount_out, None)?;
Self::best_trade_exact_out(
pools_excluding_this_pool,
currency_in.clone(),
Expand Down Expand Up @@ -2272,13 +2267,12 @@ mod tests {
}

#[test]
#[ignore]
fn insufficient_liquidity() {
let result = &mut vec![];
Trade::best_trade_exact_out(
vec![POOL_0_1.clone(), POOL_0_2.clone(), POOL_1_2.clone()],
TOKEN0.clone(),
CurrencyAmount::from_raw_amount(TOKEN2.clone(), 1200).unwrap(),
CurrencyAmount::from_raw_amount(TOKEN2.clone(), 120000).unwrap(),
BestTradeOptions::default(),
vec![],
None,
Expand All @@ -2289,13 +2283,12 @@ mod tests {
}

#[test]
#[ignore]
fn insufficient_liquidity_in_one_pool_but_not_the_other() {
let result = &mut vec![];
Trade::best_trade_exact_out(
vec![POOL_0_1.clone(), POOL_0_2.clone(), POOL_1_2.clone()],
TOKEN0.clone(),
CurrencyAmount::from_raw_amount(TOKEN2.clone(), 1050).unwrap(),
CurrencyAmount::from_raw_amount(TOKEN2.clone(), 105000).unwrap(),
BestTradeOptions::default(),
vec![],
None,
Expand Down

0 comments on commit 01439b6

Please sign in to comment.