use anyhow::{Context, Result};
use tracing::instrument;
use uniswap_sdk_core::prelude::{Currency, CurrencyAmount, Percent, TradeType};
#[inline]
#[instrument(skip(amount_in), fields(trade_type = ?trade_type, slippage_tolerance = ?slippage_tolerance, amount_in = ?amount_in))]
pub fn maximum_amount_in(
trade_type: TradeType,
slippage_tolerance: Percent,
amount_in: CurrencyAmount<Currency>,
) -> Result<CurrencyAmount<Currency>> {
assert!(slippage_tolerance >= Percent::default(), "SLIPPAGE_TOLERANCE");
if trade_type == TradeType::ExactInput {
return Ok(amount_in);
}
amount_in
.multiply(&(Percent::new(1, 1) + slippage_tolerance))
.context("Failed to calculate maximum amount in")
}
#[inline]
#[instrument(skip(amount_out), fields(trade_type = ?trade_type, slippage_tolerance = ?slippage_tolerance, amount_out = ?amount_out))]
pub fn minimum_amount_out(
trade_type: TradeType,
slippage_tolerance: Percent,
amount_out: CurrencyAmount<Currency>,
) -> Result<CurrencyAmount<Currency>> {
assert!(slippage_tolerance >= Percent::default(), "SLIPPAGE_TOLERANCE");
if trade_type == TradeType::ExactOutput {
return Ok(amount_out);
}
let denominator = Percent::new(1, 1) + slippage_tolerance;
amount_out.divide(&denominator).context("Failed to calculate minimum amount out")
}