1use std::any::Any;
4
5use alloy::primitives::{Address as AlloyAddress, U256};
6use num_bigint::{BigUint, ToBigUint};
7use serde::{Deserialize, Serialize};
8use tracing::debug;
9use tycho_common::{
10 dto::ProtocolStateDelta,
11 models::token::Token,
12 simulation::{
13 errors::{SimulationError, TransitionError},
14 protocol_sim::{
15 Balances, GetAmountOutResult, PoolSwap, Price, ProtocolSim, QueryPoolSwapParams,
16 SwapConstraint,
17 },
18 },
19 Bytes,
20};
21
22use crate::{
23 evm::{
24 engine_db::{create_engine, SHARED_TYCHO_DB},
25 protocol::{
26 curve::{
27 adapter::{build_pool, CurveVariant},
28 math::Pool,
29 swap_to_price::{exchange, swap_to_price, SwapToPriceError},
30 vm,
31 },
32 u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
33 },
34 },
35 utils::decimals_exponent,
36};
37
38const FEE_DENOMINATOR: f64 = 1e10;
40const STABLESWAP_GAS: u64 = 150_000;
42const CRYPTOSWAP_GAS: u64 = 350_000;
44
45#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
55pub struct CurveState {
56 pool_address: Bytes,
58 tokens: Vec<Bytes>,
60 decimals: Vec<u8>,
62 variant: CurveVariant,
64 pool: Pool,
66 #[serde(default)]
68 admin_fee: Option<U256>,
69}
70
71impl CurveState {
72 pub fn new(
75 pool_address: Bytes,
76 tokens: Vec<Bytes>,
77 decimals: Vec<u8>,
78 variant: CurveVariant,
79 pool: Pool,
80 admin_fee: Option<U256>,
81 ) -> Self {
82 Self { pool_address, tokens, decimals, variant, pool, admin_fee }
83 }
84
85 fn admin_fee(&self) -> Result<U256, SimulationError> {
86 if self.variant == CurveVariant::StableSwapNG {
87 return Ok(U256::from(5_000_000_000u64));
88 }
89 self.admin_fee.ok_or_else(|| {
90 SimulationError::RecoverableError(format!(
91 "Missing Curve admin fee for {}; refresh the pool state",
92 self.pool_address
93 ))
94 })
95 }
96
97 fn coin_index(&self, token: &Bytes) -> Result<usize, SimulationError> {
98 self.tokens
99 .iter()
100 .position(|t| t == token)
101 .ok_or_else(|| {
102 SimulationError::InvalidInput(
103 format!("token {token} is not a coin of curve pool {}", self.pool_address),
104 None,
105 )
106 })
107 }
108
109 fn is_crypto(&self) -> bool {
110 matches!(
111 self.variant,
112 CurveVariant::TwoCryptoV1 |
113 CurveVariant::TwoCryptoNG |
114 CurveVariant::TwoCryptoStable |
115 CurveVariant::TriCryptoV1 |
116 CurveVariant::TriCryptoNG
117 )
118 }
119
120 fn gas_estimate(&self) -> u64 {
121 if self.is_crypto() {
122 CRYPTOSWAP_GAS
123 } else {
124 STABLESWAP_GAS
125 }
126 }
127
128 fn swap_to_target_price(
132 &self,
133 token_in: &Token,
134 token_out: &Token,
135 target: &Price,
136 tolerance: f64,
137 ) -> Result<Option<PoolSwap>, SimulationError> {
138 let i = self.coin_index(&token_in.address)?;
139 let j = self.coin_index(&token_out.address)?;
140 if target.numerator.bits() > 256 || target.denominator.bits() > 256 {
141 return Ok(None);
142 }
143 let target_num = biguint_to_u256(&target.numerator);
144 let target_den = biguint_to_u256(&target.denominator);
145
146 match swap_to_price(
147 &self.pool,
148 i,
149 j,
150 target_num,
151 target_den,
152 tolerance,
153 if self.is_crypto() { U256::ZERO } else { self.admin_fee()? },
154 ) {
155 Ok(dx) => {
156 if dx.is_zero() {
157 let swap = PoolSwap::new(BigUint::ZERO, BigUint::ZERO, self.clone_box(), None);
158 return Ok(Some(swap));
159 }
160 let result = self.get_amount_out(u256_to_biguint(dx), token_in, token_out)?;
161 Ok(Some(PoolSwap::new(u256_to_biguint(dx), result.amount, result.new_state, None)))
162 }
163 Err(SwapToPriceError::TargetAboveSpot) => {
164 let spot = self.spot_price(token_in, token_out)?;
165 let decimal_adjustment =
166 10f64.powi(decimals_exponent(token_in.decimals, token_out.decimals)?);
167 let target =
168 u256_to_f64(target_num)? / u256_to_f64(target_den)? * decimal_adjustment;
169 Err(SimulationError::InvalidInput(
170 format!("Target price {target} is above spot price {spot}"),
171 None,
172 ))
173 }
174 Err(SwapToPriceError::TargetBelowLimit) => Err(SimulationError::InvalidInput(
175 format!(
176 "Target price below reachable limit for curve pool {pool}",
177 pool = self.pool_address
178 ),
179 None,
180 )),
181 Err(err @ SwapToPriceError::InvalidInput(_)) => Err(SimulationError::InvalidInput(
182 format!("{err} for curve pool {pool}", pool = self.pool_address),
183 None,
184 )),
185 Err(SwapToPriceError::UnsupportedVariant) => Ok(None),
186 Err(err @ SwapToPriceError::MathFailed) => {
187 debug!(
188 pool = %self.pool_address,
189 %err,
190 "Curve native swap-to-price failed; using the numerical search"
191 );
192 Ok(None)
193 }
194 }
195 }
196}
197
198#[typetag::serde]
199impl ProtocolSim for CurveState {
200 fn fee(&self) -> f64 {
201 let fee = self.pool.fee().or_else(|| {
202 self.pool
203 .crypto_fees()
204 .map(|(mid, _, _)| mid)
205 });
206 fee.and_then(|f| u256_to_f64(f).ok())
207 .map(|f| f / FEE_DENOMINATOR)
208 .unwrap_or(0.0)
209 }
210
211 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
212 let i = self.coin_index(&base.address)?;
213 let j = self.coin_index("e.address)?;
214 let (numerator, denominator) = self
215 .pool
216 .spot_price(i, j)
217 .ok_or_else(|| {
218 SimulationError::RecoverableError(format!(
219 "curve spot price unavailable for {}",
220 self.pool_address
221 ))
222 })?;
223 let ratio = u256_to_f64(numerator)? / u256_to_f64(denominator)?;
226 let decimal_adjustment = 10f64.powi(decimals_exponent(base.decimals, quote.decimals)?);
227 Ok(ratio * decimal_adjustment)
228 }
229
230 fn get_amount_out(
231 &self,
232 amount_in: BigUint,
233 token_in: &Token,
234 token_out: &Token,
235 ) -> Result<GetAmountOutResult, SimulationError> {
236 let i = self.coin_index(&token_in.address)?;
237 let j = self.coin_index(&token_out.address)?;
238 let dx = biguint_to_u256(&amount_in);
239
240 let mut new_pool = self.pool.clone();
241 let dy = if self.is_crypto() {
242 let dy = self
243 .pool
244 .get_amount_out(i, j, dx)
245 .ok_or_else(|| {
246 SimulationError::RecoverableError(format!(
247 "curve get_amount_out failed for {}",
248 self.pool_address
249 ))
250 })?;
251 let balances = self.pool.balances();
252 new_pool
254 .set_balance(i, balances[i] + dx)
255 .map_err(|e| SimulationError::FatalError(e.to_string()))?;
256 new_pool
257 .set_balance(j, balances[j].saturating_sub(dy))
258 .map_err(|e| SimulationError::FatalError(e.to_string()))?;
259 dy
260 } else {
261 let result = exchange(&self.pool, i, j, dx, self.admin_fee()?).ok_or_else(|| {
262 SimulationError::RecoverableError(format!(
263 "curve exchange accounting failed for {}",
264 self.pool_address
265 ))
266 })?;
267 for (index, balance) in result.balances.into_iter().enumerate() {
268 new_pool
269 .set_balance(index, balance)
270 .map_err(|e| SimulationError::FatalError(e.to_string()))?;
271 }
272 result.amount
273 };
274
275 let new_state = Self { pool: new_pool, ..self.clone() };
276 Ok(GetAmountOutResult::new(
277 u256_to_biguint(dy),
278 self.gas_estimate()
279 .to_biguint()
280 .expect("u64 fits in BigUint"),
281 Box::new(new_state),
282 ))
283 }
284
285 fn get_limits(
286 &self,
287 sell_token: Bytes,
288 buy_token: Bytes,
289 ) -> Result<(BigUint, BigUint), SimulationError> {
290 let i = self.coin_index(&sell_token)?;
291 let j = self.coin_index(&buy_token)?;
292 let (balance_in, balance_out) = {
293 let balances = self.pool.balances();
294 (balances[i], balances[j])
295 };
296 if balance_in.is_zero() || balance_out.is_zero() {
297 return Ok((BigUint::ZERO, BigUint::ZERO));
298 }
299 let max_out_reserve = balance_out.saturating_sub(U256::from(1));
302 let max_out = self
303 .pool
304 .get_amount_out(i, j, balance_in)
305 .ok_or_else(|| {
306 SimulationError::RecoverableError(format!(
307 "curve get_limits: solver failed at max input for {}",
308 self.pool_address
309 ))
310 })?
311 .min(max_out_reserve);
312 Ok((u256_to_biguint(balance_in), u256_to_biguint(max_out)))
313 }
314
315 fn delta_transition(
322 &mut self,
323 delta: ProtocolStateDelta,
324 _tokens: &std::collections::HashMap<Bytes, Token>,
325 _balances: &Balances,
326 ) -> Result<(), TransitionError> {
327 let state = match delta
328 .updated_attributes
329 .get(vm::POOL_STATE_ADJUSTED)
330 {
331 Some(encoded) => {
332 let state = vm::decode_raw_state(encoded)?;
333 if state.variant != self.variant {
334 return Err(SimulationError::FatalError(format!(
335 "Variant mismatch: expected {}, got {}",
336 self.variant, state.variant
337 ))
338 .into())
339 }
340 if state.token_decimals != self.decimals {
341 return Err(SimulationError::FatalError(format!(
342 "Token decimals mismatch: expected {:?}, got {:?}",
343 self.decimals, state.token_decimals
344 ))
345 .into())
346 }
347 state
348 }
349 None => {
350 let engine = create_engine(SHARED_TYCHO_DB.clone(), false)?;
351 let pool_address = AlloyAddress::from_slice(self.pool_address.as_ref());
352 vm::read_raw_pool_state(
353 &engine,
354 &pool_address,
355 self.variant,
356 &self.decimals,
357 &Default::default(),
358 )?
359 }
360 };
361 let pool = build_pool(&state)
362 .map_err(|e| SimulationError::FatalError(format!("curve build_pool failed: {e}")))?;
363 self.pool = pool;
364 self.admin_fee = state.admin_fee;
365 Ok(())
366 }
367
368 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
372 match params.swap_constraint() {
373 SwapConstraint::TradeLimitPrice { .. } => {
374 crate::evm::query_pool_swap::query_pool_swap(self, params)
375 }
376 SwapConstraint::PoolTargetPrice { target, tolerance, .. } => {
377 let native = self.swap_to_target_price(
378 params.token_in(),
379 params.token_out(),
380 target,
381 *tolerance,
382 )?;
383 match native {
384 Some(swap) => Ok(swap),
385 None => crate::evm::query_pool_swap::query_pool_swap(self, params),
386 }
387 }
388 }
389 }
390
391 fn clone_box(&self) -> Box<dyn ProtocolSim> {
392 Box::new(self.clone())
393 }
394
395 fn as_any(&self) -> &dyn Any {
396 self
397 }
398
399 fn as_any_mut(&mut self) -> &mut dyn Any {
400 self
401 }
402
403 fn eq(&self, other: &dyn ProtocolSim) -> bool {
404 other
405 .as_any()
406 .downcast_ref::<Self>()
407 .is_some_and(|other| self == other)
408 }
409}
410
411#[cfg(test)]
412mod tests {
413 use std::{collections::HashMap, str::FromStr};
414
415 use num_traits::ToPrimitive;
416 use rstest::rstest;
417 use tycho_common::{
418 models::Chain,
419 simulation::protocol_sim::{QueryPoolSwapParams, SwapConstraint},
420 };
421
422 use super::*;
423 use crate::evm::{
424 protocol::curve::{adapter::RawPoolState, vm::encode_raw_state},
425 query_pool_swap::test_helpers::{target_price_params, to_price},
426 };
427
428 const VARIANT: CurveVariant = CurveVariant::TriCryptoNG;
429 const DECIMALS: [u8; 3] = [6, 8, 18];
430
431 fn u(s: &str) -> U256 {
432 s.parse().unwrap()
433 }
434
435 fn raw_pool_state(balances: Vec<U256>) -> RawPoolState {
437 RawPoolState {
438 variant: VARIANT,
439 balances,
440 token_decimals: DECIMALS.to_vec(),
441 amp: u("1707629"),
442 mid_fee: Some(u("3000000")),
443 out_fee: Some(u("30000000")),
444 fee_gamma: Some(u("500000000000000")),
445 d: Some(u("7457948167729606869978625")),
446 gamma: Some(u("11809167828997")),
447 price_scale: Some(vec![u("59372627314351316239076"), u("1565715369034455123313")]),
448 ..Default::default()
449 }
450 }
451
452 fn state(balances: Vec<U256>) -> CurveState {
453 let raw_state = raw_pool_state(balances);
454 let pool = build_pool(&raw_state).expect("build");
455 CurveState::new(
456 Bytes::from([7u8; 20]),
457 vec![Bytes::from([1u8; 20]), Bytes::from([2u8; 20]), Bytes::from([3u8; 20])],
458 DECIMALS.to_vec(),
459 VARIANT,
460 pool,
461 Some(U256::ZERO),
462 )
463 }
464
465 fn delta(attributes: HashMap<String, Bytes>) -> ProtocolStateDelta {
466 ProtocolStateDelta { updated_attributes: attributes, ..Default::default() }
467 }
468
469 #[test]
470 fn test_delta_transition_rebuilds_from_attribute() {
471 let confirmed = vec![u("2466241139205"), u("4200057336"), u("1595469030050811720465")];
472 let pending = vec![u("2470000000000"), u("4190000000"), u("1600000000000000000000")];
473 let mut curve = state(confirmed.clone());
474 let attribute = encode_raw_state(&raw_pool_state(pending.clone())).expect("encode");
475
476 curve
477 .delta_transition(
478 delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), attribute)])),
479 &HashMap::new(),
480 &Balances::default(),
481 )
482 .expect("delta transition from attribute failed");
483
484 assert_eq!(
487 curve.pool.balances()[..3],
488 pending[..],
489 "balances must come from the attribute"
490 );
491 assert_ne!(curve.pool.balances()[..3], confirmed[..]);
492 }
493
494 #[test]
495 fn test_delta_transition_errors_on_variant_mismatch() {
496 let mut curve = state(vec![u("1"), u("2"), u("3")]);
497 let mut pending_state = raw_pool_state(curve.pool.balances().to_vec());
498 pending_state.variant = CurveVariant::StableSwapMeta;
499 let encoded = encode_raw_state(&pending_state).expect("encode");
500
501 let result = curve.delta_transition(
502 delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), encoded)])),
503 &HashMap::new(),
504 &Balances::default(),
505 );
506
507 assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
508 }
509
510 #[test]
511 fn test_delta_transition_errors_on_decimals_mismatch() {
512 let mut curve = state(vec![u("1"), u("2"), u("3")]);
513 let mut pending_state = raw_pool_state(curve.pool.balances().to_vec());
514 pending_state.token_decimals = vec![18, 18, 18];
515 let encoded = encode_raw_state(&pending_state).expect("encode");
516
517 let result = curve.delta_transition(
518 delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), encoded)])),
519 &HashMap::new(),
520 &Balances::default(),
521 );
522
523 assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
524 }
525
526 #[test]
527 fn test_delta_transition_rejects_malformed_attribute() {
528 let mut curve = state(vec![u("1"), u("2"), u("3")]);
529
530 let result = curve.delta_transition(
531 delta(HashMap::from([(
532 vm::POOL_STATE_ADJUSTED.to_string(),
533 Bytes::from(b"not json".to_vec()),
534 )])),
535 &HashMap::new(),
536 &Balances::default(),
537 );
538
539 assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
542 }
543
544 const WAD: u128 = 1_000_000_000_000_000_000;
545 const RATE_6_DEC: u128 = 1_000_000_000_000_000_000_000_000_000_000;
546
547 fn token(index: u8, decimals: u32) -> Token {
548 let address =
549 Bytes::from_str(&format!("0x00000000000000000000000000000000000000{index:02x}"))
550 .expect("valid address");
551 Token::new(
552 &address,
553 &format!("T{index}"),
554 decimals,
555 0,
556 &[Some(10_000)],
557 Chain::Ethereum,
558 100,
559 )
560 }
561
562 fn curve_state(pool: Pool, variant: CurveVariant, decimals: Vec<u8>) -> CurveState {
563 let tokens: Vec<Bytes> = (0..decimals.len())
564 .map(|k| token(u8::try_from(k).unwrap(), decimals[k] as u32).address)
565 .collect();
566 CurveState::new(
567 Bytes::from_str("0x00000000000000000000000000000000000000ff").expect("valid address"),
568 tokens,
569 decimals,
570 variant,
571 pool,
572 Some(U256::ZERO),
573 )
574 }
575
576 fn v1_two_coin_state() -> (CurveState, Token, Token) {
577 let pool = Pool::StableSwapV1 {
578 balances: vec![U256::from(50_000_000u128 * WAD), U256::from(48_000_000u128 * WAD)],
579 rates: vec![U256::from(WAD), U256::from(WAD)],
580 amp: U256::from(2000u64),
581 fee: U256::from(1_000_000u64),
582 };
583 (curve_state(pool, CurveVariant::StableSwapV1, vec![18, 18]), token(0, 18), token(1, 18))
584 }
585
586 fn v1_three_coin_mixed_state() -> (CurveState, Token, Token) {
587 let pool = Pool::StableSwapV1 {
589 balances: vec![
590 U256::from(63_975_337_809_806_329_031_583_135u128),
591 U256::from(61_219_263_170_093u128),
592 U256::from(37_832_425_459_809u128),
593 ],
594 rates: vec![U256::from(WAD), U256::from(RATE_6_DEC), U256::from(RATE_6_DEC)],
595 amp: U256::from(4000u64),
596 fee: U256::from(1_500_000u64),
597 };
598 (curve_state(pool, CurveVariant::StableSwapV1, vec![18, 6, 6]), token(0, 18), token(1, 6))
599 }
600
601 fn v1_three_coin_mixed_state_reverse() -> (CurveState, Token, Token) {
602 let (state, token_out, token_in) = v1_three_coin_mixed_state();
603 (state, token_in, token_out)
604 }
605
606 fn ng_dynamic_fee_state() -> (CurveState, Token, Token) {
607 let pool = Pool::StableSwapNG {
608 balances: vec![U256::from(1_500_000u128 * WAD), U256::from(700_000u128 * WAD)],
609 rates: vec![U256::from(WAD), U256::from(WAD)],
610 amp: U256::from(40_000u64),
611 fee: U256::from(4_000_000u64),
612 offpeg_fee_multiplier: U256::from(20_000_000_000u64),
613 };
614 (curve_state(pool, CurveVariant::StableSwapNG, vec![18, 18]), token(0, 18), token(1, 18))
615 }
616
617 fn meta_state() -> (CurveState, Token, Token) {
618 let pool = Pool::StableSwapMeta {
619 balances: vec![U256::from(500_000u128 * WAD), U256::from(480_000u128 * WAD)],
620 rates: vec![U256::from(WAD), U256::from(1_030_000_000_000_000_000u128)],
621 amp: U256::from(50_000u64),
622 fee: U256::from(4_000_000u64),
623 };
624 (curve_state(pool, CurveVariant::StableSwapMeta, vec![18, 18]), token(0, 18), token(1, 18))
625 }
626
627 #[test]
628 fn pending_state_preserves_admin_fee_for_exchange() {
629 let (mut state, token_in, token_out) = v1_two_coin_state();
630 let pool = state.pool.clone();
631 #[expect(clippy::unreachable, reason = "v1_two_coin_state builds a StableSwapV1 pool")]
632 let Pool::StableSwapV1 { balances, rates: _, amp, fee } = pool
633 else {
634 unreachable!()
635 };
636 let raw = RawPoolState {
637 variant: CurveVariant::StableSwapV1,
638 balances,
639 amp,
640 fee: Some(fee),
641 token_decimals: vec![18, 18],
642 admin_fee: Some(U256::from(5_000_000_000u64)),
643 ..Default::default()
644 };
645 state
646 .delta_transition(
647 delta(HashMap::from([(
648 vm::POOL_STATE_ADJUSTED.into(),
649 encode_raw_state(&raw).unwrap(),
650 )])),
651 &HashMap::new(),
652 &Balances::default(),
653 )
654 .unwrap();
655 assert_eq!(state.admin_fee, raw.admin_fee);
656 let mut without_admin = state.clone();
657 without_admin.admin_fee = Some(U256::ZERO);
658 let amount = BigUint::from(WAD);
659 let with_fee = state
660 .get_amount_out(amount.clone(), &token_in, &token_out)
661 .unwrap();
662 let no_fee = without_admin
663 .get_amount_out(amount, &token_in, &token_out)
664 .unwrap();
665 assert_eq!(with_fee.amount, no_fee.amount);
666 let balance = |result: &GetAmountOutResult| {
667 result
668 .new_state
669 .as_any()
670 .downcast_ref::<CurveState>()
671 .unwrap()
672 .pool
673 .balances()[1]
674 };
675 assert!(balance(&with_fee) < balance(&no_fee));
676 }
677
678 fn two_crypto_ng_state() -> (CurveState, Token, Token) {
679 let wad = U256::from(WAD);
680 let pool = Pool::TwoCryptoNG {
681 balances: [U256::from(5000u64) * wad, U256::from(5000u64) * wad],
682 precisions: [U256::from(1u64), U256::from(1u64)],
683 price_scale: wad,
684 d: U256::from(10000u64) * wad,
685 ann: U256::from(540_000u64) * U256::from(10_000u64),
686 gamma: U256::from(11_809_167_828_997u64),
687 mid_fee: U256::from(3_000_000u64),
688 out_fee: U256::from(30_000_000u64),
689 fee_gamma: U256::from(230_000_000_000_000u64),
690 };
691 (curve_state(pool, CurveVariant::TwoCryptoNG, vec![18, 18]), token(0, 18), token(1, 18))
692 }
693
694 const TOLERANCE: f64 = 0.001;
695
696 fn spot_target_params(
699 state: &CurveState,
700 token_in: &Token,
701 token_out: &Token,
702 multiplier: f64,
703 ) -> (QueryPoolSwapParams, f64) {
704 let spot = state
705 .spot_price(token_in, token_out)
706 .expect("spot price");
707 let target_f64 = spot * multiplier;
708 let target = to_price(target_f64, token_in, token_out);
709 (target_price_params(token_in, token_out, target, TOLERANCE), target_f64)
710 }
711
712 #[rstest]
713 #[case::v1_two_coin_shallow(v1_two_coin_state(), 0.9999)]
714 #[case::v1_two_coin_mid(v1_two_coin_state(), 0.999)]
715 #[case::v1_two_coin_deep(v1_two_coin_state(), 0.99)]
716 #[case::v1_mixed_decimals_18_to_6(v1_three_coin_mixed_state(), 0.99)]
717 #[case::v1_mixed_decimals_6_to_18(v1_three_coin_mixed_state_reverse(), 0.99)]
718 #[case::ng_dynamic_fee(ng_dynamic_fee_state(), 0.99)]
719 #[case::ng_dynamic_fee_mid(ng_dynamic_fee_state(), 0.999)]
720 #[case::meta_virtual_price(meta_state(), 0.99)]
721 #[case::meta_virtual_price_mid(meta_state(), 0.999)]
722 fn test_query_pool_swap_native_amounts(
723 #[case] setup: (CurveState, Token, Token),
724 #[case] multiplier: f64,
725 ) {
726 let (state, token_in, token_out) = setup;
727 let (params, target) = spot_target_params(&state, &token_in, &token_out, multiplier);
728
729 let swap = state
730 .query_pool_swap(¶ms)
731 .expect("native query_pool_swap");
732
733 let price = swap
734 .new_state()
735 .spot_price(&token_in, &token_out)
736 .unwrap();
737 assert!(price >= target && price <= target * (1.0 + TOLERANCE));
738 let executed = state
739 .get_amount_out(swap.amount_in().clone(), &token_in, &token_out)
740 .unwrap();
741 assert_eq!(swap.amount_out(), &executed.amount);
742 assert!(ProtocolSim::eq(swap.new_state(), executed.new_state.as_ref()));
743 }
744
745 #[rstest]
748 #[case::v1_two_coin_shallow(v1_two_coin_state(), 0.9999)]
749 #[case::v1_two_coin_mid(v1_two_coin_state(), 0.999)]
750 #[case::v1_two_coin_deep(v1_two_coin_state(), 0.99)]
751 #[case::v1_mixed_decimals_18_to_6(v1_three_coin_mixed_state(), 0.99)]
752 #[case::v1_mixed_decimals_6_to_18(v1_three_coin_mixed_state_reverse(), 0.99)]
753 #[case::ng_dynamic_fee(ng_dynamic_fee_state(), 0.99)]
754 #[case::ng_dynamic_fee_mid(ng_dynamic_fee_state(), 0.999)]
755 #[case::meta_virtual_price(meta_state(), 0.99)]
756 #[case::meta_virtual_price_mid(meta_state(), 0.999)]
757 fn test_query_pool_swap_numerical_comparison(
758 #[case] setup: (CurveState, Token, Token),
759 #[case] multiplier: f64,
760 ) {
761 let (state, token_in, token_out) = setup;
762 let (params, target_f64) = spot_target_params(&state, &token_in, &token_out, multiplier);
763
764 let native = state
765 .query_pool_swap(¶ms)
766 .expect("native query_pool_swap");
767 let numerical = crate::evm::query_pool_swap::query_pool_swap(&state, ¶ms)
768 .expect("numerical query_pool_swap");
769
770 for (label, swap, band) in
771 [("native", &native, TOLERANCE / 2.0), ("numerical", &numerical, 5.0 * TOLERANCE)]
772 {
773 assert!(swap.amount_in() > &BigUint::ZERO, "{label} amount_in should be > 0");
774 let new_spot = swap
775 .new_state()
776 .spot_price(&token_in, &token_out)
777 .expect("post-swap spot");
778 let error = (new_spot - target_f64) / target_f64;
779 assert!(
780 error >= -1e-12,
781 "{label} post-swap spot {new_spot} fell below target {target_f64}"
782 );
783 assert!(
784 error <= band,
785 "{label} post-swap spot {new_spot} outside band of target {target_f64}: {error}"
786 );
787 }
788 }
789
790 #[test]
793 fn test_crypto_variant_delegates_to_numerical() {
794 let (state, token_in, token_out) = two_crypto_ng_state();
795 let (params, _) = spot_target_params(&state, &token_in, &token_out, 0.995);
796
797 let result = state.query_pool_swap(¶ms);
798 let Err(SimulationError::InvalidInput(msg, _)) = result else {
799 panic!("crypto pools must delegate to the numerical search, got {result:?}");
800 };
801 assert!(msg.contains("< limit"), "expected the numerical search's limit error, got: {msg}");
802 }
803
804 #[test]
805 fn test_query_pool_swap_target_wider_than_u256() {
806 let (state, token_in, token_out) = v1_two_coin_state();
807 let (params, target_f64) = spot_target_params(&state, &token_in, &token_out, 0.999);
808 let SwapConstraint::PoolTargetPrice { target, .. } = params.swap_constraint() else {
809 panic!("spot_target_params builds a PoolTargetPrice constraint");
810 };
811 let scale = BigUint::from(1u8) << 256;
812 let wide_target = Price::new(&target.numerator * &scale, &target.denominator * &scale);
813 let params = target_price_params(&token_in, &token_out, wide_target, TOLERANCE);
814
815 let swap = state
816 .query_pool_swap(¶ms)
817 .expect("numerical query_pool_swap");
818
819 assert!(swap.price_points().is_some(), "only the numerical search returns price points");
820 let new_spot = swap
821 .new_state()
822 .spot_price(&token_in, &token_out)
823 .expect("post-swap spot");
824 let error = (new_spot - target_f64) / target_f64;
825 assert!(
826 (-1e-12..=5.0 * TOLERANCE).contains(&error),
827 "post-swap spot {new_spot} missed {target_f64}"
828 );
829 }
830
831 #[test]
832 fn test_trade_limit_price_delegates_to_numerical() {
833 let (state, token_in, token_out) = v1_two_coin_state();
834 let spot = state
835 .spot_price(&token_in, &token_out)
836 .expect("spot price");
837 let limit_f64 = spot * 0.999;
838 let params = QueryPoolSwapParams::new(
839 token_in.clone(),
840 token_out.clone(),
841 SwapConstraint::TradeLimitPrice {
842 limit: to_price(limit_f64, &token_in, &token_out),
843 tolerance: TOLERANCE,
844 min_amount_in: None,
845 max_amount_in: None,
846 },
847 );
848
849 let swap = state
850 .query_pool_swap(¶ms)
851 .expect("trade limit query_pool_swap");
852 assert!(swap.amount_in() > &BigUint::ZERO);
853 assert!(swap.amount_out() > &BigUint::ZERO);
854 let trade_price = swap
855 .amount_out()
856 .to_f64()
857 .expect("failed to convert the output amount to f64") /
858 swap.amount_in()
859 .to_f64()
860 .expect("failed to convert the input amount to f64");
861 assert!(trade_price >= limit_f64, "trade price {trade_price} violates limit {limit_f64}");
862 }
863
864 #[rstest]
865 #[case::above_spot(1.01, "is above spot price")]
866 #[case::below_limit(1e-9, "below reachable limit for curve pool")]
867 fn test_query_pool_swap_unreachable_target(#[case] multiplier: f64, #[case] expected: &str) {
868 let (state, token_in, token_out) = v1_two_coin_state();
869 let (params, _) = spot_target_params(&state, &token_in, &token_out, multiplier);
870
871 let result = state.query_pool_swap(¶ms);
872 let Err(SimulationError::InvalidInput(msg, _)) = result else {
873 panic!("expected InvalidInput, got {result:?}");
874 };
875 assert!(msg.contains(expected), "unexpected message: {msg}");
876 }
877
878 #[test]
879 fn test_query_pool_swap_target_equal_to_spot() {
880 let (state, token_in, token_out) = v1_two_coin_state();
881 let i = state
882 .coin_index(&token_in.address)
883 .expect("token_in index");
884 let j = state
885 .coin_index(&token_out.address)
886 .expect("token_out index");
887 let (num, den) = state
888 .pool
889 .spot_price(i, j)
890 .expect("pool spot price");
891 let target = Price::new(u256_to_biguint(num), u256_to_biguint(den));
892 let params = target_price_params(&token_in, &token_out, target, TOLERANCE);
893
894 let swap = state
895 .query_pool_swap(¶ms)
896 .expect("query_pool_swap at spot");
897 assert_eq!(swap.amount_in(), &BigUint::ZERO);
898 assert_eq!(swap.amount_out(), &BigUint::ZERO);
899 }
900}