use std::{any::Any, collections::HashMap};
use alloy::primitives::{Address, U256};
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
use tycho_common::{
dto::ProtocolStateDelta,
models::token::Token,
simulation::{
errors::{SimulationError, TransitionError},
protocol_sim::{
Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams,
SwapConstraint,
},
},
Bytes,
};
use crate::{
book::{
component::PairState,
sim::{self, SwapDirection},
},
evm::{
protocol::{
safe_math::{safe_add_u256, safe_mul_u256, safe_sub_u256},
u256_num::{biguint_to_uint, u256_to_biguint, u256_to_f64},
},
query_pool_swap::{calculate_trade_price, price_to_f64_with_decimals},
},
pamm::protocols::hanji::market::FillGas,
};
const RATE_DENOMINATOR: u64 = 1_000_000_000_000_000_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct Level {
pub price: U256,
pub shares: U256,
}
#[derive(Clone, derive_more::Debug, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "UncheckedHanjiState")]
pub struct HanjiState {
pub(super) orderbook: Address,
pub(super) base_token: Token,
pub(super) quote_token: Token,
pub(super) scaling_x: U256,
pub(super) scaling_y: U256,
pub(super) fee_rate: u64,
pub(super) gas: FillGas,
#[debug("{} levels", asks.len())]
pub(super) asks: Vec<Level>,
#[debug("{} levels", bids.len())]
pub(super) bids: Vec<Level>,
}
#[derive(Deserialize)]
struct UncheckedHanjiState {
orderbook: Address,
base_token: Token,
quote_token: Token,
scaling_x: U256,
scaling_y: U256,
fee_rate: u64,
gas: FillGas,
asks: Vec<Level>,
bids: Vec<Level>,
}
impl TryFrom<UncheckedHanjiState> for HanjiState {
type Error = SimulationError;
fn try_from(state: UncheckedHanjiState) -> Result<Self, SimulationError> {
let UncheckedHanjiState {
orderbook,
base_token,
quote_token,
scaling_x,
scaling_y,
fee_rate,
gas,
asks,
bids,
} = state;
HanjiState {
orderbook,
base_token,
quote_token,
scaling_x,
scaling_y,
fee_rate,
gas,
asks,
bids,
}
.validated()
}
}
struct Fill {
shares: U256,
value: U256,
levels: usize,
}
fn invalid(message: impl Into<String>) -> SimulationError {
SimulationError::InvalidInput(message.into(), None)
}
fn no_levels(direction: SwapDirection) -> SimulationError {
invalid(match direction {
SwapDirection::BaseToQuote => "the book has no bids",
SwapDirection::QuoteToBase => "the book has no asks",
})
}
impl HanjiState {
pub(super) fn validated(self) -> Result<Self, SimulationError> {
if self.scaling_x.is_zero() || self.scaling_y.is_zero() {
return Err(invalid("market has a zero scaling factor"));
}
if self.fee_rate >= RATE_DENOMINATOR {
return Err(invalid(format!("fee rate {} takes the whole value", self.fee_rate)));
}
for (name, side) in [("ask", &self.asks), ("bid", &self.bids)] {
if side
.iter()
.any(|level| level.price.is_zero() || level.shares.is_zero())
{
return Err(invalid(format!("{name} side holds an empty level")));
}
}
if self
.asks
.windows(2)
.any(|pair| pair[1].price < pair[0].price)
{
return Err(invalid("ask side is not ordered lowest price first"));
}
if self
.bids
.windows(2)
.any(|pair| pair[1].price > pair[0].price)
{
return Err(invalid("bid side is not ordered highest price first"));
}
Ok(self)
}
fn side(&self, direction: SwapDirection) -> &[Level] {
match direction {
SwapDirection::BaseToQuote => &self.bids,
SwapDirection::QuoteToBase => &self.asks,
}
}
fn fee_on(&self, value: U256) -> Result<U256, SimulationError> {
Ok(safe_mul_u256(value, U256::from(self.fee_rate))?.div_ceil(U256::from(RATE_DENOMINATOR)))
}
fn cost(&self, value: U256) -> Result<U256, SimulationError> {
safe_add_u256(value, self.fee_on(value)?)
}
fn affordable_value(&self, target: U256) -> Result<U256, SimulationError> {
let denominator = U256::from(RATE_DENOMINATOR);
Ok(safe_mul_u256(target, denominator)? / (denominator + U256::from(self.fee_rate)))
}
fn sell(&self, shares: U256) -> Result<Fill, SimulationError> {
let mut fill = Fill { shares: U256::ZERO, value: U256::ZERO, levels: 0 };
let mut left = shares;
for level in &self.bids {
if left.is_zero() {
break;
}
let take = left.min(level.shares);
fill.shares += take;
fill.value = safe_add_u256(fill.value, safe_mul_u256(take, level.price)?)?;
fill.levels += 1;
left -= take;
}
Ok(fill)
}
fn buy(&self, target: U256) -> Result<Fill, SimulationError> {
let budget = self.affordable_value(target)?;
let mut fill = Fill { shares: U256::ZERO, value: U256::ZERO, levels: 0 };
for level in &self.asks {
let take = ((budget - fill.value) / level.price).min(level.shares);
if take.is_zero() {
break;
}
fill.shares += take;
fill.value = safe_add_u256(fill.value, safe_mul_u256(take, level.price)?)?;
fill.levels += 1;
}
Ok(fill)
}
fn sale_proceeds(&self, value: U256) -> Result<U256, SimulationError> {
safe_mul_u256(safe_sub_u256(value, self.fee_on(value)?)?, self.scaling_y)
}
fn limits(&self, direction: SwapDirection) -> Result<(U256, U256), SimulationError> {
self.fill_of(direction, self.side(direction))
}
fn fill_of(
&self,
direction: SwapDirection,
levels: &[Level],
) -> Result<(U256, U256), SimulationError> {
let mut value = U256::ZERO;
let mut shares = U256::ZERO;
for level in levels {
value = safe_add_u256(value, safe_mul_u256(level.price, level.shares)?)?;
shares = safe_add_u256(shares, level.shares)?;
}
let (input, output) = match direction {
SwapDirection::BaseToQuote => {
(safe_mul_u256(shares, self.scaling_x)?, self.sale_proceeds(value)?)
}
SwapDirection::QuoteToBase => (
safe_mul_u256(self.cost(value)?, self.scaling_y)?,
safe_mul_u256(shares, self.scaling_x)?,
),
};
if output.is_zero() {
return Ok((U256::ZERO, U256::ZERO));
}
Ok((input, output))
}
}
impl HanjiState {
fn rate_at(
&self,
direction: SwapDirection,
level: &Level,
token_in: &Token,
token_out: &Token,
) -> Result<f64, SimulationError> {
let atomic =
u256_to_f64(level.price)? * u256_to_f64(self.scaling_y)? / u256_to_f64(self.scaling_x)?;
let rate = ProtocolSim::fee(self);
let decimals = 10f64.powf(f64::from(token_in.decimals) - f64::from(token_out.decimals));
Ok(match direction {
SwapDirection::BaseToQuote => atomic * decimals * (1.0 - rate),
SwapDirection::QuoteToBase => decimals / (atomic * (1.0 + rate)),
})
}
fn trade_limit_swap(
&self,
limit: f64,
token_in: &Token,
token_out: &Token,
) -> Result<PoolSwap, SimulationError> {
let direction = SwapDirection::require(
&self.base_token,
&self.quote_token,
&token_in.address,
&token_out.address,
)?;
let clears = |levels: &[Level]| -> Result<bool, SimulationError> {
let (input, output) = self.fill_of(direction, levels)?;
if input.is_zero() {
return Ok(false);
}
let rate = calculate_trade_price(
u256_to_f64(input)?,
u256_to_f64(output)?,
token_in.decimals,
token_out.decimals,
);
Ok(rate >= limit)
};
let side = self.side(direction);
let mut whole = 0;
while whole < side.len() && clears(&side[..=whole])? {
whole += 1;
}
let mut levels = side[..whole].to_vec();
if let Some(next) = side.get(whole) {
let (mut low, mut high) = (U256::ZERO, next.shares);
while high - low > U256::from(1) {
let middle = low + (high - low) / U256::from(2);
let mut probe = levels.clone();
probe.push(Level { price: next.price, shares: middle });
if clears(&probe)? {
low = middle;
} else {
high = middle;
}
}
if !low.is_zero() {
levels.push(Level { price: next.price, shares: low });
}
}
self.swap_filling(direction, &levels, token_in, token_out)
}
fn swap_filling(
&self,
direction: SwapDirection,
levels: &[Level],
token_in: &Token,
token_out: &Token,
) -> Result<PoolSwap, SimulationError> {
let (input, _) = self.fill_of(direction, levels)?;
if input.is_zero() {
return Ok(PoolSwap::new(BigUint::ZERO, BigUint::ZERO, self.clone_box(), None));
}
let amount_in = u256_to_biguint(input);
let result = self.get_amount_out(amount_in.clone(), token_in, token_out)?;
Ok(PoolSwap::new(amount_in, result.amount, result.new_state, None))
}
fn target_price_swap(
&self,
target: f64,
token_in: &Token,
token_out: &Token,
) -> Result<PoolSwap, SimulationError> {
let direction = SwapDirection::require(
&self.base_token,
&self.quote_token,
&token_in.address,
&token_out.address,
)?;
let side = self.side(direction);
let mut rates = Vec::with_capacity(side.len());
for level in side {
rates.push(self.rate_at(direction, level, token_in, token_out)?);
}
let (Some(best), Some(last)) = (rates.first(), rates.last()) else {
return Err(no_levels(direction));
};
if target > *best {
return Err(invalid(format!("target {target} is above the best level's {best}")));
}
if target < *last {
return Err(invalid(format!(
"target {target} is below the last level's {last}, past which the book is empty"
)));
}
let stop = rates
.iter()
.rposition(|rate| *rate >= target)
.unwrap_or(0);
self.swap_filling(direction, &side[..stop], token_in, token_out)
}
}
impl PairState for HanjiState {
fn base_token(&self) -> &Token {
&self.base_token
}
fn quote_token(&self) -> &Token {
&self.quote_token
}
fn directions(&self) -> Vec<(Bytes, Bytes)> {
sim::directions(
&self.base_token,
&self.quote_token,
!self.bids.is_empty(),
!self.asks.is_empty(),
)
}
}
#[typetag::serde]
impl ProtocolSim for HanjiState {
fn fee(&self) -> f64 {
self.fee_rate as f64 / RATE_DENOMINATOR as f64
}
fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
let direction = SwapDirection::require(
&self.base_token,
&self.quote_token,
&base.address,
"e.address,
)?;
let best = self
.side(direction)
.first()
.ok_or_else(|| no_levels(direction))?;
self.rate_at(direction, best, base, quote)
}
fn get_amount_out(
&self,
amount_in: BigUint,
token_in: &Token,
token_out: &Token,
) -> Result<GetAmountOutResult, SimulationError> {
sim::require_positive_amount(&amount_in)?;
let direction = SwapDirection::require(
&self.base_token,
&self.quote_token,
&token_in.address,
&token_out.address,
)?;
let input = biguint_to_uint(&amount_in)?;
if self.side(direction).is_empty() {
return Err(no_levels(direction));
}
let (limit, _) = self.limits(direction)?;
if input > limit {
return Err(invalid(format!("input {input} exceeds the book's {limit}")));
}
let (fill, output) = match direction {
SwapDirection::BaseToQuote => {
let shares = input / self.scaling_x;
if shares.is_zero() {
return Err(invalid("input is less than one share of the base token"));
}
let fill = self.sell(shares)?;
let output = self.sale_proceeds(fill.value)?;
(fill, output)
}
SwapDirection::QuoteToBase => {
let fill = self.buy(input / self.scaling_y)?;
let output = safe_mul_u256(fill.shares, self.scaling_x)?;
(fill, output)
}
};
if output.is_zero() {
return Err(invalid("input buys less than one unit of output"));
}
let gas = self.gas.of(fill.levels);
let mut next = self.clone();
match direction {
SwapDirection::BaseToQuote => next.bids.clear(),
SwapDirection::QuoteToBase => next.asks.clear(),
}
Ok(GetAmountOutResult::new(u256_to_biguint(output), BigUint::from(gas), Box::new(next)))
}
fn get_limits(
&self,
sell_token: Bytes,
buy_token: Bytes,
) -> Result<(BigUint, BigUint), SimulationError> {
let direction =
SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
let (input, output) = self.limits(direction)?;
Ok((u256_to_biguint(input), u256_to_biguint(output)))
}
fn delta_transition(
&mut self,
_delta: ProtocolStateDelta,
_tokens: &HashMap<Bytes, Token>,
_balances: &Balances,
) -> Result<(), TransitionError> {
Err(TransitionError::DecodeError(
"Hanji state is read whole every poll and does not take deltas".into(),
))
}
fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
let (token_in, token_out) = (params.token_in(), params.token_out());
match params.swap_constraint() {
SwapConstraint::TradeLimitPrice { limit, .. } => {
let limit =
price_to_f64_with_decimals(limit, token_in.decimals, token_out.decimals)?;
self.trade_limit_swap(limit, token_in, token_out)
}
SwapConstraint::PoolTargetPrice { target, .. } => {
let target =
price_to_f64_with_decimals(target, token_in.decimals, token_out.decimals)?;
self.target_price_swap(target, token_in, token_out)
}
}
}
fn clone_box(&self) -> Box<dyn ProtocolSim> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn eq(&self, other: &dyn ProtocolSim) -> bool {
other.as_any().downcast_ref::<Self>() == Some(self)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use num_traits::{FromPrimitive, ToPrimitive};
use rstest::rstest;
use tycho_common::simulation::protocol_sim::Price;
use super::*;
use crate::pamm::protocols::hanji::test_support::{
cbbtc, eth, fixture, state, usdc, Caller, CBBTC_ETH, CBBTC_USDC, ETH_USDC,
};
fn tokens(state: &HanjiState, direction: SwapDirection) -> (Token, Token) {
match direction {
SwapDirection::BaseToQuote => (state.base_token.clone(), state.quote_token.clone()),
SwapDirection::QuoteToBase => (state.quote_token.clone(), state.base_token.clone()),
}
}
fn quote(
state: &HanjiState,
amount_in: U256,
direction: SwapDirection,
) -> Result<GetAmountOutResult, SimulationError> {
let (token_in, token_out) = tokens(state, direction);
state.get_amount_out(u256_to_biguint(amount_in), &token_in, &token_out)
}
fn limits(state: &HanjiState, direction: SwapDirection) -> (U256, U256) {
let (token_in, token_out) = tokens(state, direction);
let (input, output) = state
.get_limits(token_in.address, token_out.address)
.unwrap();
(biguint_to_uint(&input).unwrap(), biguint_to_uint(&output).unwrap())
}
#[test]
fn test_quotes_match_recorded_fills() {
let fixture = fixture();
let (mut priced, mut refused) = (0, 0);
for orderbook in [ETH_USDC, CBBTC_USDC, CBBTC_ETH] {
for case in &fixture.market(orderbook).cases {
let state = state(orderbook, case.caller);
let amount_in = case.amount_in;
let (limit, limit_out) = limits(&state, case.direction());
let result = quote(&state, amount_in, case.direction());
if amount_in > limit {
assert!(result.is_err(), "{case:?} is past the book");
assert_eq!(limit_out, case.amount_out, "{case:?}");
refused += 1;
continue;
}
let shares = match case.direction() {
SwapDirection::BaseToQuote => amount_in / state.scaling_x,
SwapDirection::QuoteToBase => case.amount_out / state.scaling_x,
};
assert_eq!(shares, case.shares, "{case:?}");
assert_eq!(
biguint_to_uint(&result.unwrap().amount).unwrap(),
case.amount_out,
"{case:?}"
);
priced += 1;
}
}
assert_eq!((priced, refused), (90, 18));
}
#[test]
fn test_gas_covers_every_recorded_contract_fill() {
let fixture = fixture();
let mut checked = 0;
for orderbook in [ETH_USDC, CBBTC_USDC, CBBTC_ETH] {
for case in fixture
.market(orderbook)
.cases
.iter()
.filter(|case| case.caller != Caller::Direct)
{
let state = state(orderbook, case.caller);
let (limit, _) = limits(&state, case.direction());
if case.amount_in > limit {
continue;
}
let result = quote(&state, case.amount_in, case.direction()).unwrap();
let gas = u64::try_from(result.gas).unwrap();
assert!((case.gas - case.net_gas) * 5 < case.gas, "{case:?}: refund over a fifth");
assert!(gas >= case.net_gas, "{case:?}: modelled {gas}");
assert!(gas * 4 <= case.net_gas * 5, "{case:?}: modelled {gas}");
checked += 1;
}
}
assert_eq!(checked, 60, "the recording's contract fills within the book");
}
#[rstest]
fn test_limit_is_largest_fillable_input(
#[values(ETH_USDC, CBBTC_USDC, CBBTC_ETH)] orderbook: Address,
#[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
) {
let state = state(orderbook, Caller::Contract);
let (input, output) = limits(&state, direction);
let at_limit = quote(&state, input, direction).unwrap();
let past_limit = quote(&state, input + U256::from(1), direction);
assert_eq!(biguint_to_uint::<256, 4>(&at_limit.amount).unwrap(), output);
let next = at_limit
.new_state
.as_any()
.downcast_ref::<HanjiState>()
.unwrap();
assert!(next.side(direction).is_empty());
assert!(matches!(past_limit, Err(SimulationError::InvalidInput(..))));
}
#[test]
fn test_input_below_one_share() {
let state = state(ETH_USDC, Caller::Contract);
let selling = quote(&state, state.scaling_x - U256::from(1), SwapDirection::BaseToQuote);
let buying = quote(&state, U256::from(1000), SwapDirection::QuoteToBase);
assert!(matches!(selling, Err(SimulationError::InvalidInput(..))));
assert!(matches!(buying, Err(SimulationError::InvalidInput(..))));
}
#[test]
fn test_zero_input_and_foreign_token() {
let state = state(CBBTC_USDC, Caller::Contract);
let zero = state.get_amount_out(BigUint::ZERO, &cbbtc(), &usdc());
let foreign = state.get_amount_out(BigUint::from(1_000_000u64), ð(), &usdc());
assert!(matches!(zero, Err(SimulationError::InvalidInput(..))));
assert!(matches!(foreign, Err(SimulationError::InvalidInput(..))));
}
#[test]
fn test_swap_empties_walked_side() {
let state = state(CBBTC_USDC, Caller::Contract);
let amount = U256::from(10) * state.scaling_x;
let result = quote(&state, amount, SwapDirection::BaseToQuote).unwrap();
let next = result
.new_state
.as_any()
.downcast_ref::<HanjiState>()
.unwrap();
assert!(next.bids.is_empty());
assert_eq!(next.asks, state.asks);
assert!(matches!(
quote(next, amount, SwapDirection::BaseToQuote),
Err(SimulationError::InvalidInput(..))
));
}
#[test]
fn test_fee_rounds_up() {
let state = state(CBBTC_USDC, Caller::Contract);
assert_eq!(state.fee_rate, 100_000_000_000_000);
assert_eq!(
state
.fee_on(U256::from(12_345))
.unwrap(),
U256::from(2)
);
assert_eq!(
state
.fee_on(U256::from(10_000))
.unwrap(),
U256::from(1)
);
assert_eq!(state.fee_on(U256::ZERO).unwrap(), U256::ZERO);
}
#[rstest]
#[case::one_fee_step_short(10_000, 9_999)]
#[case::exactly_one_fee_step(10_001, 10_000)]
#[case::between_fee_steps(10_002, 10_000)]
#[case::exactly_two_fee_steps(20_002, 20_000)]
#[case::two_fee_steps_and_one_over(20_004, 20_001)]
fn test_affordable_value(#[case] target: u64, #[case] value: u64) {
let state = state(CBBTC_USDC, Caller::Contract);
let affordable = state
.affordable_value(U256::from(target))
.unwrap();
assert_eq!(affordable, U256::from(value));
assert!(state.cost(affordable).unwrap() <= U256::from(target));
assert!(
state
.cost(affordable + U256::from(1))
.unwrap() >
U256::from(target)
);
}
#[test]
fn test_spot_price() {
let state = state(ETH_USDC, Caller::Contract);
let best_bid = f64::from(u32::try_from(state.bids[0].price).unwrap()) / 100.0;
let best_ask = f64::from(u32::try_from(state.asks[0].price).unwrap()) / 100.0;
let selling = state
.spot_price(ð(), &usdc())
.unwrap();
let buying = state
.spot_price(&usdc(), ð())
.unwrap();
assert!((selling - best_bid * 0.9999).abs() < 1e-9 * best_bid);
assert!((buying - 1.0 / (best_ask * 1.0001)).abs() < 1e-12);
}
#[test]
fn test_one_sided_book() {
let mut state = state(CBBTC_USDC, Caller::Contract);
state.asks.clear();
let directions = state.directions();
let (input, output) = limits(&state, SwapDirection::QuoteToBase);
let buying = quote(&state, U256::from(1_000_000), SwapDirection::QuoteToBase);
assert_eq!(directions, vec![(cbbtc().address, usdc().address)]);
assert_eq!((input, output), (U256::ZERO, U256::ZERO));
assert!(matches!(buying, Err(SimulationError::InvalidInput(..))));
assert!(state
.spot_price(&usdc(), &cbbtc())
.is_err());
}
#[rstest]
#[case::zero_scaling(|state: &mut HanjiState| state.scaling_x = U256::ZERO)]
#[case::whole_value_fee(|state: &mut HanjiState| state.fee_rate = RATE_DENOMINATOR)]
#[case::empty_level(|state: &mut HanjiState| state.bids[1].shares = U256::ZERO)]
#[case::asks_out_of_order(|state: &mut HanjiState| state.asks.swap(0, 1))]
#[case::bids_out_of_order(|state: &mut HanjiState| state.bids.swap(0, 1))]
fn test_malformed_book(#[case] break_it: fn(&mut HanjiState)) {
let mut state = state(CBBTC_USDC, Caller::Contract);
break_it(&mut state);
assert!(state.validated().is_err());
}
#[test]
fn test_malformed_serialized_state() {
let mut state = state(CBBTC_ETH, Caller::Contract);
state.asks[0].price = U256::ZERO;
let json = serde_json::to_string(&state).unwrap();
let restored = serde_json::from_str::<HanjiState>(&json);
assert!(restored.is_err());
}
#[test]
fn test_overflowing_book() {
let mut state = state(CBBTC_USDC, Caller::Contract);
state.scaling_y = U256::MAX;
let selling = quote(&state, U256::from(1_000_000), SwapDirection::BaseToQuote);
let limits = state.get_limits(cbbtc().address, usdc().address);
assert!(selling.is_err());
assert!(limits.is_err());
}
#[test]
fn test_side_worth_only_its_fee() {
let mut state = state(CBBTC_USDC, Caller::Contract);
state.bids = vec![Level { price: U256::from(1), shares: U256::from(1) }];
let (input, output) = limits(&state, SwapDirection::BaseToQuote);
let selling = quote(&state, state.scaling_x, SwapDirection::BaseToQuote);
assert_eq!((input, output), (U256::ZERO, U256::ZERO));
assert!(matches!(selling, Err(SimulationError::InvalidInput(..))));
}
fn price_of(rate: f64, token_in: &Token, token_out: &Token) -> Price {
let decimals = f64::from(token_out.decimals) - f64::from(token_in.decimals);
let numerator = BigUint::from_f64(rate * 10f64.powf(decimals) * 1e30).unwrap();
Price::new(numerator, BigUint::from(10u8).pow(30))
}
fn target_swap(
state: &HanjiState,
direction: SwapDirection,
target: f64,
) -> Result<PoolSwap, SimulationError> {
let (token_in, token_out) = tokens(state, direction);
let target = price_of(target, &token_in, &token_out);
let constraint = SwapConstraint::PoolTargetPrice {
target,
tolerance: 0.0,
min_amount_in: None,
max_amount_in: None,
};
state.query_pool_swap(&QueryPoolSwapParams::new(token_in, token_out, constraint))
}
fn rates(state: &HanjiState, direction: SwapDirection) -> Vec<f64> {
let (token_in, token_out) = tokens(state, direction);
let mut rates = Vec::new();
for level in state.side(direction) {
rates.push(
state
.rate_at(direction, level, &token_in, &token_out)
.unwrap(),
);
}
rates
}
#[rstest]
fn test_target_price_between_levels(
#[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
) {
let state = state(ETH_USDC, Caller::Direct);
let rates = rates(&state, direction);
assert!(rates.len() >= 3, "{rates:?}");
let mut first_level_only = state.clone();
match direction {
SwapDirection::BaseToQuote => first_level_only.bids.truncate(1),
SwapDirection::QuoteToBase => first_level_only.asks.truncate(1),
}
let (first_level_in, first_level_out) = limits(&first_level_only, direction);
let swap = target_swap(&state, direction, (rates[1] + rates[2]) / 2.0).unwrap();
assert_eq!(biguint_to_uint::<256, 4>(swap.amount_in()).unwrap(), first_level_in);
assert_eq!(biguint_to_uint::<256, 4>(swap.amount_out()).unwrap(), first_level_out);
let (token_in, token_out) = tokens(&state, direction);
assert!(swap
.new_state()
.spot_price(&token_in, &token_out)
.is_err());
}
#[rstest]
fn test_target_price_above_second_level(
#[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
) {
let state = state(ETH_USDC, Caller::Direct);
let rates = rates(&state, direction);
let swap = target_swap(&state, direction, (rates[0] + rates[1]) / 2.0).unwrap();
assert_eq!(swap.amount_in(), &BigUint::ZERO);
assert!(swap.new_state().eq(&state));
}
#[rstest]
#[case::above_the_best_level(|rates: &[f64]| rates[0] * 1.001)]
#[case::below_the_last_level(|rates: &[f64]| rates[rates.len() - 1] * 0.999)]
fn test_target_price_unreachable(
#[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
#[case] target: fn(&[f64]) -> f64,
) {
let state = state(ETH_USDC, Caller::Direct);
let target = target(&rates(&state, direction));
let swap = target_swap(&state, direction, target);
assert!(matches!(swap, Err(SimulationError::InvalidInput(..))), "{swap:?}");
}
fn trade_limit_swap(
state: &HanjiState,
direction: SwapDirection,
limit: f64,
) -> Result<PoolSwap, SimulationError> {
let (token_in, token_out) = tokens(state, direction);
let constraint = SwapConstraint::TradeLimitPrice {
limit: price_of(limit, &token_in, &token_out),
tolerance: 0.0,
min_amount_in: None,
max_amount_in: None,
};
state.query_pool_swap(&QueryPoolSwapParams::new(token_in, token_out, constraint))
}
#[rstest]
fn test_trade_limit_cleared_by_whole_side(
#[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
) {
let state = state(ETH_USDC, Caller::Direct);
let rates = rates(&state, direction);
let swap = trade_limit_swap(&state, direction, rates[rates.len() - 1]).unwrap();
let (limit_in, limit_out) = limits(&state, direction);
assert_eq!(biguint_to_uint::<256, 4>(swap.amount_in()).unwrap(), limit_in);
assert_eq!(biguint_to_uint::<256, 4>(swap.amount_out()).unwrap(), limit_out);
}
#[rstest]
fn test_trade_limit_inside_book(
#[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
) {
let state = state(ETH_USDC, Caller::Direct);
let rates = rates(&state, direction);
let limit = rates[1];
let swap = trade_limit_swap(&state, direction, limit).unwrap();
let (token_in, token_out) = tokens(&state, direction);
let (limit_in, _) = limits(&state, direction);
let amount_in = biguint_to_uint::<256, 4>(swap.amount_in()).unwrap();
assert!(amount_in > U256::ZERO && amount_in < limit_in, "{amount_in}");
let price = calculate_trade_price(
swap.amount_in().to_f64().unwrap(),
swap.amount_out().to_f64().unwrap(),
token_in.decimals,
token_out.decimals,
);
assert!(price >= limit, "{price} < {limit}");
let shares = match direction {
SwapDirection::BaseToQuote => amount_in / state.scaling_x,
SwapDirection::QuoteToBase => {
biguint_to_uint::<256, 4>(swap.amount_out()).unwrap() / state.scaling_x
}
};
let (more_in, more_out) = fill_of_shares(&state, direction, shares + U256::from(1));
let more_price = calculate_trade_price(
u256_to_f64(more_in).unwrap(),
u256_to_f64(more_out).unwrap(),
token_in.decimals,
token_out.decimals,
);
assert!(more_price < limit, "{more_price} >= {limit}");
}
fn fill_of_shares(state: &HanjiState, direction: SwapDirection, shares: U256) -> (U256, U256) {
let mut levels = Vec::new();
let mut left = shares;
for level in state.side(direction) {
let take = left.min(level.shares);
if take.is_zero() {
break;
}
levels.push(Level { price: level.price, shares: take });
left -= take;
}
state
.fill_of(direction, &levels)
.unwrap()
}
#[test]
fn test_state_serialization_roundtrip() {
let state = state(CBBTC_ETH, Caller::Contract);
let json = serde_json::to_string(&state).unwrap();
let restored: HanjiState = serde_json::from_str(&json).unwrap();
assert_eq!(restored, state);
assert_eq!(ProtocolSim::fee(&restored), f64::from_str("0.0001").unwrap());
}
}