1use std::{any::Any, collections::HashMap};
2
3use alloy::primitives::{address, Address, U256};
4use num_bigint::BigUint;
5use serde::{Deserialize, Serialize};
6use tycho_common::{
7 dto::ProtocolStateDelta,
8 models::token::Token,
9 simulation::{
10 errors::{SimulationError, TransitionError},
11 protocol_sim::{Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams},
12 },
13 Bytes,
14};
15
16use crate::{
17 book::{
18 component::PairState,
19 sim::{self, SwapDirection},
20 },
21 evm::protocol::{
22 u256_num::{biguint_to_uint, u256_to_biguint},
23 utils::solidity_math::mul_div,
24 },
25 pamm::protocols::baibai::math::{invalid, Curve, Side},
26};
27
28const BASE_SWAP_GAS: u64 = 115_400;
39const GAS_PER_KNOT_BELOW_CURSOR: u64 = 1_550;
40const GAS_PER_KNOT_BOUGHT_THROUGH: u64 = 1_360;
41
42const BASE_TRANSFER_GAS: [(Address, u64, u64); 1] =
48 [(address!("cbB7C0000aB88B473b1f5aFd9ef808440eed33Bf"), 17_100, 15_400)];
49
50const FEE_DENOMINATOR: u32 = 1_000_000;
52
53#[derive(Clone, derive_more::Debug, PartialEq, Serialize, Deserialize)]
62pub struct BaibaiState {
63 pub(super) base_token: Token,
64 pub(super) quote_token: Token,
65 pub(super) mid: U256,
67 pub(super) q_unit: U256,
68 pub(super) c_unit: U256,
69 #[debug("{{ filled: {}, {} knots }}", ask.filled, ask.knots.len())]
70 pub(super) ask: Side,
71 #[debug("{{ filled: {}, {} knots }}", bid.filled, bid.knots.len())]
72 pub(super) bid: Side,
73 pub(super) available: [U256; 2],
75 pub(super) fee_pips: u32,
76}
77
78impl BaibaiState {
79 pub(super) fn validated(self) -> Result<Self, SimulationError> {
81 if self.mid == U256::ZERO || self.q_unit == U256::ZERO || self.c_unit == U256::ZERO {
82 return Err(invalid("curve has no mid price or unit"));
83 }
84 self.kept_pips()?;
85 self.curve(SwapDirection::BaseToQuote)?;
86 self.curve(SwapDirection::QuoteToBase)?;
87 Ok(self)
88 }
89
90 fn curve(&self, direction: SwapDirection) -> Result<Curve, SimulationError> {
92 let (side, asks) = match direction {
93 SwapDirection::BaseToQuote => (&self.bid, false),
94 SwapDirection::QuoteToBase => (&self.ask, true),
95 };
96 Curve::new(side, self.mid, self.q_unit, self.c_unit, asks)
97 }
98
99 fn custody(direction: SwapDirection) -> (usize, usize) {
102 match direction {
103 SwapDirection::BaseToQuote => (0, 1),
104 SwapDirection::QuoteToBase => (1, 0),
105 }
106 }
107
108 fn kept_pips(&self) -> Result<u32, SimulationError> {
113 if self.fee_pips >= FEE_DENOMINATOR {
114 return Err(invalid(format!("fee of {} pips takes the whole output", self.fee_pips)));
115 }
116 Ok(FEE_DENOMINATOR - self.fee_pips)
117 }
118
119 fn after_fee(&self, gross: U256) -> Result<U256, SimulationError> {
121 let kept = self.kept_pips()?;
122 mul_div(gross, U256::from(kept), U256::from(FEE_DENOMINATOR))
123 }
124
125 fn gas(&self, curve: &Curve, direction: SwapDirection, cursor: U256) -> u64 {
127 let below = curve.knots_below(cursor);
128 let bought_through = match direction {
129 SwapDirection::BaseToQuote => 0,
130 SwapDirection::QuoteToBase => below - curve.knots_below(curve.filled),
131 };
132 let transfers = BASE_TRANSFER_GAS
133 .iter()
134 .find(|(base, _, _)| self.base_token.address.as_ref() == base.as_slice())
135 .map_or(0, |(_, selling, buying)| match direction {
136 SwapDirection::BaseToQuote => *selling,
137 SwapDirection::QuoteToBase => *buying,
138 });
139 BASE_SWAP_GAS +
140 transfers +
141 GAS_PER_KNOT_BELOW_CURSOR * below +
142 GAS_PER_KNOT_BOUGHT_THROUGH * bought_through
143 }
144
145 fn sells(&self, direction: SwapDirection) -> bool {
146 let (_, out) = Self::custody(direction);
147 self.kept_pips().is_ok() &&
148 self.available[out] > U256::ZERO &&
149 self.curve(direction)
150 .and_then(|curve| curve.capacity())
151 .is_ok_and(|capacity| capacity > U256::ZERO)
152 }
153}
154
155impl PairState for BaibaiState {
156 fn base_token(&self) -> &Token {
157 &self.base_token
158 }
159
160 fn quote_token(&self) -> &Token {
161 &self.quote_token
162 }
163
164 fn directions(&self) -> Vec<(Bytes, Bytes)> {
165 sim::directions(
166 &self.base_token,
167 &self.quote_token,
168 self.sells(SwapDirection::BaseToQuote),
169 self.sells(SwapDirection::QuoteToBase),
170 )
171 }
172}
173
174#[typetag::serde]
175impl ProtocolSim for BaibaiState {
176 fn fee(&self) -> f64 {
177 f64::from(self.fee_pips) / f64::from(FEE_DENOMINATOR)
178 }
179
180 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
182 let direction = SwapDirection::require(
183 &self.base_token,
184 &self.quote_token,
185 &base.address,
186 "e.address,
187 )?;
188 let (_, out) = Self::custody(direction);
189 if self.available[out] == U256::ZERO {
190 return Err(invalid("no custody to pay out"));
191 }
192 let atomic = self
193 .curve(direction)?
194 .marginal_price()?;
195 let decimals = 10f64.powf(f64::from(base.decimals) - f64::from(quote.decimals));
196 let kept = f64::from(self.kept_pips()?) / f64::from(FEE_DENOMINATOR);
197 Ok(atomic * decimals * kept)
198 }
199
200 fn get_amount_out(
201 &self,
202 amount_in: BigUint,
203 token_in: &Token,
204 token_out: &Token,
205 ) -> Result<GetAmountOutResult, SimulationError> {
206 sim::require_positive_amount(&amount_in)?;
207 let direction = SwapDirection::require(
208 &self.base_token,
209 &self.quote_token,
210 &token_in.address,
211 &token_out.address,
212 )?;
213 let input = biguint_to_uint(&amount_in)?;
214 let curve = self.curve(direction)?;
215 let (gross, cursor) = curve.quote(input)?;
216 let output = self.after_fee(gross)?;
217 if output == U256::ZERO {
218 return Err(invalid("input below the curve's atomic precision"));
219 }
220 let (paid_in, paid_out) = Self::custody(direction);
221 if output > self.available[paid_out] {
222 return Err(invalid(format!(
223 "output {output} exceeds the custodian's available {}",
224 self.available[paid_out]
225 )));
226 }
227 let mut next = self.clone();
228 match direction {
229 SwapDirection::BaseToQuote => next.bid.filled = cursor,
230 SwapDirection::QuoteToBase => next.ask.filled = cursor,
231 }
232 next.available[paid_in] = next.available[paid_in].saturating_add(input);
233 next.available[paid_out] -= output;
234 Ok(GetAmountOutResult::new(
235 u256_to_biguint(output),
236 BigUint::from(self.gas(&curve, direction, cursor)),
237 Box::new(next),
238 ))
239 }
240
241 fn get_limits(
244 &self,
245 sell_token: Bytes,
246 buy_token: Bytes,
247 ) -> Result<(BigUint, BigUint), SimulationError> {
248 let direction =
249 SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
250 let (paid_in, paid_out) = Self::custody(direction);
251 let available = self.available[paid_out];
252 if available == U256::ZERO {
253 return Ok((BigUint::ZERO, BigUint::ZERO));
254 }
255 let curve = self.curve(direction)?;
256 let mut high = curve
257 .capacity()?
258 .min(U256::MAX - self.available[paid_in]);
259 let full_output = self.after_fee(curve.quote(high)?.0)?;
260 if full_output == U256::ZERO {
261 return Ok((BigUint::ZERO, BigUint::ZERO));
262 }
263 if self.after_fee(curve.output_bound(high)?)? <= available {
264 return Ok((u256_to_biguint(high), u256_to_biguint(full_output)));
265 }
266 let mut low = U256::ZERO;
268 while low < high {
269 let mid = low + (high - low).div_ceil(U256::from(2));
270 if self.after_fee(curve.output_bound(mid)?)? <= available {
271 low = mid;
272 } else {
273 high = mid - U256::from(1);
274 }
275 }
276 let output = self.after_fee(curve.quote(low)?.0)?;
277 if output == U256::ZERO {
278 return Ok((BigUint::ZERO, BigUint::ZERO));
279 }
280 Ok((u256_to_biguint(low), u256_to_biguint(output)))
281 }
282
283 fn delta_transition(
284 &mut self,
285 _delta: ProtocolStateDelta,
286 _tokens: &HashMap<Bytes, Token>,
287 _balances: &Balances,
288 ) -> Result<(), TransitionError> {
289 Err(TransitionError::DecodeError(
290 "BaiBai state is read whole every poll and does not take deltas".into(),
291 ))
292 }
293
294 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
295 crate::evm::query_pool_swap::query_pool_swap(self, params)
296 }
297
298 fn clone_box(&self) -> Box<dyn ProtocolSim> {
299 Box::new(self.clone())
300 }
301
302 fn as_any(&self) -> &dyn Any {
303 self
304 }
305
306 fn as_any_mut(&mut self) -> &mut dyn Any {
307 self
308 }
309
310 fn eq(&self, other: &dyn ProtocolSim) -> bool {
311 other.as_any().downcast_ref::<Self>() == Some(self)
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use rstest::rstest;
318
319 use super::*;
320 use crate::{
321 evm::protocol::u256_num::biguint_to_uint,
322 pamm::protocols::baibai::{
323 math::Knot,
324 test_support::{fee_charging_fixture, fixture, fixtures, state, token, weth_state},
325 BASE_DEPLOYMENT,
326 },
327 };
328
329 fn quote() -> Token {
330 token(BASE_DEPLOYMENT.quote)
331 }
332
333 #[test]
338 fn quotes_match_the_entrypoint_wei_for_wei() {
339 let mut priced = 0;
340 for fixture in fixtures() {
341 for pair in &fixture.pairs {
342 let state = state(&fixture, pair);
343 for case in &pair.cases {
344 let (token_in, token_out) = if case.sell_base {
345 (state.base_token.clone(), quote())
346 } else {
347 (quote(), state.base_token.clone())
348 };
349 let amount_in = u256_to_biguint(case.amount_in);
350 match state.get_amount_out(amount_in, &token_in, &token_out) {
351 Ok(result) => {
352 assert_eq!(result.amount, u256_to_biguint(case.amount_out), "{case:?}");
353 priced += 1;
354 }
355 Err(error) => {
356 assert_eq!(case.amount_out, U256::ZERO, "{case:?}: {error}")
357 }
358 }
359 }
360 }
361 }
362 assert_eq!(priced, 116, "the recordings' fillable cases");
363 }
364
365 #[test]
367 fn a_feeless_state_matches_the_curve_book() {
368 for fixture in fixtures() {
369 for pair in &fixture.pairs {
370 let mut state = state(&fixture, pair);
371 state.fee_pips = 0;
372 for case in pair
373 .cases
374 .iter()
375 .filter(|case| case.curve_out != U256::ZERO)
376 {
377 let (token_in, token_out) = if case.sell_base {
378 (state.base_token.clone(), quote())
379 } else {
380 (quote(), state.base_token.clone())
381 };
382 let result = state
383 .get_amount_out(u256_to_biguint(case.amount_in), &token_in, &token_out)
384 .unwrap();
385 assert_eq!(result.amount, u256_to_biguint(case.curve_out), "{case:?}");
386 }
387 }
388 }
389 }
390
391 #[test]
393 fn the_fee_is_in_millionths_of_the_output() {
394 let fixture = fee_charging_fixture();
395
396 assert_eq!(state(&fixture, &fixture.pairs[0]).fee(), 0.00005);
397 }
398
399 #[test]
402 fn the_router_pays_no_fee_since_its_whitelist() {
403 let state = weth_state();
404
405 let result = state
406 .get_amount_out(BigUint::from(10u64).pow(18), &state.base_token.clone(), "e())
407 .unwrap();
408
409 assert_eq!(state.fee(), 0.0);
410 assert_eq!(result.amount, BigUint::from(2_416_825_836u64));
411 }
412
413 #[test]
414 fn a_swap_advances_the_cursor_and_moves_custody() {
415 let state = weth_state();
416 let weth = state.base_token.clone();
417 let amount = BigUint::from(10u64).pow(17);
418
419 let result = state
420 .get_amount_out(amount.clone(), &weth, "e())
421 .unwrap();
422
423 let next = result
424 .new_state
425 .as_any()
426 .downcast_ref::<BaibaiState>()
427 .unwrap();
428 assert_eq!(next.bid.filled, U256::from(10u64).pow(U256::from(17)));
429 assert_eq!(next.ask.filled, state.ask.filled);
430 assert_eq!(
431 u256_to_biguint(next.available[0]),
432 u256_to_biguint(state.available[0]) + amount
433 );
434 assert_eq!(
435 u256_to_biguint(next.available[1]),
436 u256_to_biguint(state.available[1]) - &result.amount
437 );
438 let again = next
440 .get_amount_out(BigUint::from(10u64).pow(17), &weth, "e())
441 .unwrap();
442 assert!(again.amount <= result.amount);
443 }
444
445 #[rstest]
451 #[case::selling_within_the_first_segment(true, 2u64 * 10u64.pow(17), 115_400)]
452 #[case::selling_past_two_knots(true, 2u64 * 10u64.pow(18), 118_500)]
453 #[case::buying_within_the_first_segment(false, 500_000_000, 115_400)]
454 #[case::buying_past_one_knot(false, 1_000_000_000, 118_310)]
455 fn gas_grows_with_the_knots_a_swap_passes(
456 #[case] sell_base: bool,
457 #[case] amount: u64,
458 #[case] expected: u64,
459 ) {
460 let state = weth_state();
461 let (token_in, token_out) = if sell_base {
462 (state.base_token.clone(), quote())
463 } else {
464 (quote(), state.base_token.clone())
465 };
466
467 let gas = state
468 .get_amount_out(BigUint::from(amount), &token_in, &token_out)
469 .unwrap()
470 .gas;
471
472 assert_eq!(gas, BigUint::from(expected));
473 }
474
475 #[rstest]
477 #[case::selling(true, 1_000_000, 115_400 + 17_100)]
478 #[case::buying(false, 500_000_000, 115_400 + 15_400)]
479 fn cbbtc_swaps_add_its_transfer_gas(
480 #[case] sell_base: bool,
481 #[case] amount: u64,
482 #[case] expected: u64,
483 ) {
484 let fixture = fixture();
485 let state = state(&fixture, &fixture.pairs[1]);
486 assert_eq!(state.base_token.symbol, "cbBTC");
487 let (token_in, token_out) = if sell_base {
488 (state.base_token.clone(), quote())
489 } else {
490 (quote(), state.base_token.clone())
491 };
492
493 let gas = state
494 .get_amount_out(BigUint::from(amount), &token_in, &token_out)
495 .unwrap()
496 .gas;
497
498 assert_eq!(gas, BigUint::from(expected));
499 }
500
501 #[test]
504 fn knots_behind_the_cursor_still_cost_gas() {
505 let mut state = weth_state();
506 state.ask.filled = U256::from(5u64) * U256::from(10u64).pow(U256::from(17));
507
508 let gas = state
509 .get_amount_out(BigUint::from(1_000_000u64), "e(), &state.base_token.clone())
510 .unwrap()
511 .gas;
512
513 assert_eq!(gas, BigUint::from(115_400u64 + 1_550));
514 }
515
516 #[test]
519 fn a_bid_past_its_paying_depth_is_refused() {
520 let mut state = weth_state();
521 state.bid.knots = vec![Knot { q: 1_000, extra: 0 }, Knot { q: 2_000, extra: 46_000_000 }];
522 let weth = state.base_token.clone();
523
524 let (max_in, max_out) = state
525 .get_limits(weth.address.clone(), quote().address)
526 .unwrap();
527
528 let at_limit = state
529 .get_amount_out(max_in.clone(), &weth, "e())
530 .unwrap();
531 assert_eq!(at_limit.amount, max_out);
532 let error = state
533 .get_amount_out(max_in + 1u32, &weth, "e())
534 .unwrap_err();
535 assert!(
536 error
537 .to_string()
538 .contains("paying depth"),
539 "{error}"
540 );
541 }
542
543 #[rstest]
546 #[case::the_whole_output(1_000_000)]
547 #[case::more_than_the_output(1_000_001)]
548 fn a_fee_of_the_whole_output_trades_nothing(#[case] fee_pips: u32) {
549 let mut state = weth_state();
550 state.fee_pips = fee_pips;
551 let weth = state.base_token.clone();
552
553 let quoted = state
554 .get_amount_out(BigUint::from(10u64).pow(16), &weth, "e())
555 .unwrap_err();
556 let priced = state
557 .spot_price(&weth, "e())
558 .unwrap_err();
559
560 for error in [quoted, priced] {
561 assert!(
562 error
563 .to_string()
564 .contains("takes the whole output"),
565 "{error}"
566 );
567 }
568 assert!(state.directions().is_empty());
569 assert!(state.validated().is_err());
570 }
571
572 #[test]
573 fn output_beyond_custody_is_refused() {
574 let mut state = weth_state();
575 state.available[1] = U256::from(1_000_000);
576
577 let error = state
578 .get_amount_out(BigUint::from(10u64).pow(17), &state.base_token.clone(), "e())
579 .unwrap_err();
580
581 assert!(error.to_string().contains("available"), "{error}");
582 }
583
584 #[rstest]
585 #[case::zero_amount(0u64, true)]
586 #[case::unrelated_tokens(1_000u64, false)]
587 fn invalid_requests_are_refused(#[case] amount: u64, #[case] own_tokens: bool) {
588 let state = weth_state();
589 let token_in = if own_tokens {
590 state.base_token.clone()
591 } else {
592 token(alloy::primitives::Address::repeat_byte(0x11))
593 };
594
595 let error = state
596 .get_amount_out(BigUint::from(amount), &token_in, "e())
597 .unwrap_err();
598
599 assert!(matches!(error, SimulationError::InvalidInput(..)), "{error}");
600 }
601
602 #[rstest]
604 #[case::sell_base(true)]
605 #[case::buy_base(false)]
606 fn the_limits_are_fillable_and_tight(#[case] sell_base: bool) {
607 let state = weth_state();
608 let (token_in, token_out) = if sell_base {
609 (state.base_token.clone(), quote())
610 } else {
611 (quote(), state.base_token.clone())
612 };
613
614 let (max_in, max_out) = state
615 .get_limits(token_in.address.clone(), token_out.address.clone())
616 .unwrap();
617
618 let at_limit = state
619 .get_amount_out(max_in.clone(), &token_in, &token_out)
620 .unwrap();
621 assert_eq!(at_limit.amount, max_out);
622 assert!(state
623 .get_amount_out(max_in + 1u32, &token_in, &token_out)
624 .is_err());
625 }
626
627 fn bid_paying_depth(state: &BaibaiState) -> U256 {
631 let side = &state.bid;
632 let wad = U256::from(10u64).pow(U256::from(18));
633 let bps = U256::from(10_000u64);
634 let scale = U256::from(u64::try_from(10_000 + i64::from(side.spread_bps)).unwrap());
635 let price = state.mid * scale / bps;
636 let last_q = side
637 .knots
638 .last()
639 .map_or(U256::ZERO, |knot| U256::from(knot.q) * state.q_unit);
640 let depth = last_q * U256::from(side.depth_bps) / bps;
641 let mut reach = side.filled;
642 let (mut prev_q, mut prev_c) = (U256::ZERO, U256::ZERO);
643 for knot in &side.knots {
644 let q = U256::from(knot.q) * state.q_unit;
645 let c = U256::from(knot.extra) * state.c_unit;
646 if q > side.filled && reach < depth {
647 if price * (q - prev_q) <= (c - prev_c) * wad {
648 break;
649 }
650 reach = q.min(depth);
651 }
652 (prev_q, prev_c) = (q, c);
653 }
654 reach.saturating_sub(side.filled)
655 }
656
657 fn assert_tight_limits(
661 state: &BaibaiState,
662 direction: SwapDirection,
663 refusal: &str,
664 flat_allowed: bool,
665 context: &str,
666 ) -> (BigUint, BigUint) {
667 let (token_in, token_out) = match direction {
668 SwapDirection::BaseToQuote => (state.base_token.clone(), quote()),
669 SwapDirection::QuoteToBase => (quote(), state.base_token.clone()),
670 };
671 let (max_in, max_out) = state
672 .get_limits(token_in.address.clone(), token_out.address.clone())
673 .unwrap();
674 if max_in == BigUint::ZERO {
675 return (max_in, max_out);
676 }
677 let at_limit = state
678 .get_amount_out(max_in.clone(), &token_in, &token_out)
679 .unwrap_or_else(|e| panic!("{context}: the limit {max_in} is refused: {e}"));
680 assert_eq!(at_limit.amount, max_out, "{context}");
681 match state.get_amount_out(max_in.clone() + 1u32, &token_in, &token_out) {
682 Err(error) => assert!(error.to_string().contains(refusal), "{context}: {error}"),
683 Ok(past) => assert!(
684 flat_allowed && past.amount == max_out,
685 "{context}: one atom past the limit {max_in} pays {}",
686 past.amount
687 ),
688 }
689 (max_in, max_out)
690 }
691
692 #[rstest]
702 #[case::as_recorded(|_: &mut BaibaiState| {})]
703 #[case::with_a_fee(|s: &mut BaibaiState| s.fee_pips = 1_000)]
704 #[case::with_spreads(|s: &mut BaibaiState| {
705 s.ask.spread_bps = 25;
706 s.bid.spread_bps = -25;
707 })]
708 #[case::at_half_depth(|s: &mut BaibaiState| {
709 s.ask.depth_bps = 5_000;
710 s.bid.depth_bps = 5_000;
711 })]
712 fn the_limits_hold_on_every_recording(#[case] vary: fn(&mut BaibaiState)) {
713 let (mut curve_bound, mut custody_bound) = (0, 0);
714 for fixture in fixtures() {
715 for pair in &fixture.pairs {
716 let mut state = state(&fixture, pair);
717 vary(&mut state);
718 let state = state.validated().unwrap();
719 for (direction, beyond_curve) in [
720 (SwapDirection::BaseToQuote, "beyond the bid's paying depth"),
721 (SwapDirection::QuoteToBase, "beyond ask depth"),
722 ] {
723 let context = format!("{direction:?} at block {}", fixture.block);
724 let (max_in, max_out) =
725 assert_tight_limits(&state, direction, beyond_curve, false, &context);
726 if direction == SwapDirection::BaseToQuote {
727 assert_eq!(
728 biguint_to_uint(&max_in).unwrap(),
729 bid_paying_depth(&state),
730 "{context}"
731 );
732 }
733 if max_out < BigUint::from(2u32) {
734 continue;
735 }
736 curve_bound += 1;
737
738 let mut short = state.clone();
739 let available = biguint_to_uint(&max_out).unwrap() / U256::from(2);
740 short.available[BaibaiState::custody(direction).1] = available;
741 let (short_in, short_out) = assert_tight_limits(
742 &short,
743 direction,
744 "exceeds the custodian's",
745 true,
746 &context,
747 );
748 assert!(short_out <= u256_to_biguint(available), "{context}");
749 assert!(short_in < max_in, "{context}");
750 custody_bound += 1;
751 }
752 }
753 }
754 assert!(curve_bound > 0, "no limit was bound by the curve");
755 assert!(custody_bound > 0, "no limit was bound by custody");
756 }
757
758 #[test]
759 fn an_empty_custody_trades_neither_way() {
760 let mut state = weth_state();
761 state.available = [U256::ZERO, U256::ZERO];
762
763 assert!(state.directions().is_empty());
764 let limits = state
765 .get_limits(state.base_token.address.clone(), quote().address)
766 .unwrap();
767 assert_eq!(limits, (BigUint::ZERO, BigUint::ZERO));
768 assert!(state
769 .spot_price(&state.base_token.clone(), "e())
770 .is_err());
771 }
772
773 #[test]
775 fn spot_prices_bracket_the_mid() {
776 let state = weth_state();
777 let weth = state.base_token.clone();
778 let mid = 2_417.07;
779
780 let bid = state
781 .spot_price(&weth, "e())
782 .unwrap();
783 let ask = 1.0 /
784 state
785 .spot_price("e(), &weth)
786 .unwrap();
787
788 assert!(bid < ask, "bid {bid} ask {ask}");
789 assert!((bid - mid).abs() / mid < 0.01, "bid {bid}");
790 assert!((ask - mid).abs() / mid < 0.01, "ask {ask}");
791 }
792
793 #[rstest]
794 #[case::fee_takes_everything(|s: &mut BaibaiState| s.fee_pips = 1_000_000)]
795 #[case::no_mid(|s: &mut BaibaiState| s.mid = U256::ZERO)]
796 #[case::too_many_knots(|s: &mut BaibaiState| s.ask.knots = (1..=37).map(|i| Knot { q: i, extra: i }).collect())]
797 #[case::falling_cost(|s: &mut BaibaiState| s.bid.knots = vec![Knot { q: 1, extra: 5 }, Knot { q: 2, extra: 4 }])]
798 #[case::repeated_quantity(|s: &mut BaibaiState| s.bid.knots = vec![Knot { q: 1, extra: 0 }, Knot { q: 1, extra: 1 }])]
799 #[case::depth_over_100_percent(|s: &mut BaibaiState| s.ask.depth_bps = 10_001)]
800 #[case::spread_of_minus_100_percent(|s: &mut BaibaiState| s.bid.spread_bps = -10_000)]
801 #[case::spread_below_minus_100_percent(|s: &mut BaibaiState| s.ask.spread_bps = i16::MIN)]
802 fn malformed_states_are_rejected(#[case] corrupt: fn(&mut BaibaiState)) {
803 let mut state = weth_state();
804 corrupt(&mut state);
805
806 assert!(state.validated().is_err());
807 }
808
809 #[test]
810 fn a_state_round_trips_through_serde() {
811 let state: Box<dyn ProtocolSim> = Box::new(weth_state());
812
813 let json = serde_json::to_string(&state).unwrap();
814 let back: Box<dyn ProtocolSim> = serde_json::from_str(&json).unwrap();
815
816 assert!(back.eq(state.as_ref()));
817 }
818}