1use std::any::Any;
4
5use alloy::primitives::{Address as AlloyAddress, U256};
6use num_bigint::{BigUint, ToBigUint};
7use serde::{Deserialize, Serialize};
8use tracing::{debug, info};
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 policy::CurvePolicy,
30 swap_to_price::{exchange, swap_to_price, SwapToPriceError},
31 vm,
32 },
33 u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
34 },
35 },
36 utils::decimals_exponent,
37};
38
39const FEE_DENOMINATOR: f64 = 1e10;
41const STABLESWAP_GAS: u64 = 150_000;
43const CRYPTOSWAP_GAS: u64 = 350_000;
45const SUPPORTED_POLICY_VERSION: u64 = 1;
47const GRANT_GAS: u64 = 176_000;
49
50#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
60pub struct CurveState {
61 pool_address: Bytes,
63 tokens: Vec<Bytes>,
65 decimals: Vec<u8>,
67 variant: CurveVariant,
69 pool: Pool,
71 #[serde(default)]
73 admin_fee: Option<U256>,
74 #[serde(default)]
76 policy: CurvePolicy,
77 #[serde(default)]
79 pricing: Pricing,
80}
81
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
84enum Pricing {
85 #[default]
87 Public,
88 Exclusive,
91}
92
93impl CurveState {
94 pub fn new(
97 pool_address: Bytes,
98 tokens: Vec<Bytes>,
99 decimals: Vec<u8>,
100 variant: CurveVariant,
101 pool: Pool,
102 admin_fee: Option<U256>,
103 ) -> Self {
104 Self {
105 pool_address,
106 tokens,
107 decimals,
108 variant,
109 pool,
110 admin_fee,
111 policy: CurvePolicy::default(),
112 pricing: Pricing::Public,
113 }
114 }
115
116 pub(super) fn with_policy(mut self, policy: CurvePolicy) -> Self {
118 self.policy = policy;
119 self
120 }
121
122 pub fn exclusive_view(&self) -> Option<Self> {
128 if !self.can_grant() {
129 return None;
130 }
131 let mut view = Self { pricing: Pricing::Exclusive, ..self.clone() };
132 self.apply_grant(&mut view.pool)?;
133 Some(view)
134 }
135
136 pub fn is_exclusive_view(&self) -> bool {
138 self.pricing == Pricing::Exclusive && self.can_grant()
139 }
140
141 fn can_grant(&self) -> bool {
143 self.policy.version() == U256::from(SUPPORTED_POLICY_VERSION) &&
144 !self.policy.is_killed() &&
145 !self.policy.min_fee().is_zero()
146 }
147
148 fn apply_grant(&self, pool: &mut Pool) -> Option<()> {
151 if !self.can_grant() {
152 return None;
153 }
154 set_fixed_fee(pool, self.policy.min_fee())
155 }
156
157 fn admin_fee(&self) -> Result<U256, SimulationError> {
158 if self.variant == CurveVariant::StableSwapNG {
159 return Ok(U256::from(5_000_000_000u64));
160 }
161 self.admin_fee.ok_or_else(|| {
162 SimulationError::RecoverableError(format!(
163 "Missing Curve admin fee for {}; refresh the pool state",
164 self.pool_address
165 ))
166 })
167 }
168
169 fn coin_index(&self, token: &Bytes) -> Result<usize, SimulationError> {
170 self.tokens
171 .iter()
172 .position(|t| t == token)
173 .ok_or_else(|| {
174 SimulationError::InvalidInput(
175 format!("token {token} is not a coin of curve pool {}", self.pool_address),
176 None,
177 )
178 })
179 }
180
181 fn is_crypto(&self) -> bool {
182 matches!(
183 self.variant,
184 CurveVariant::TwoCryptoV1 |
185 CurveVariant::TwoCryptoNG |
186 CurveVariant::TwoCryptoStable |
187 CurveVariant::TriCryptoV1 |
188 CurveVariant::TriCryptoNG
189 )
190 }
191
192 fn gas_estimate(&self) -> u64 {
193 let gas = if self.is_crypto() { CRYPTOSWAP_GAS } else { STABLESWAP_GAS };
194 if self.is_exclusive_view() {
195 gas + GRANT_GAS
196 } else {
197 gas
198 }
199 }
200
201 fn swap_to_target_price(
205 &self,
206 token_in: &Token,
207 token_out: &Token,
208 target: &Price,
209 tolerance: f64,
210 ) -> Result<Option<PoolSwap>, SimulationError> {
211 let i = self.coin_index(&token_in.address)?;
212 let j = self.coin_index(&token_out.address)?;
213 if target.numerator.bits() > 256 || target.denominator.bits() > 256 {
214 return Ok(None);
215 }
216 let target_num = biguint_to_u256(&target.numerator);
217 let target_den = biguint_to_u256(&target.denominator);
218
219 match swap_to_price(
220 &self.pool,
221 i,
222 j,
223 target_num,
224 target_den,
225 tolerance,
226 if self.is_crypto() { U256::ZERO } else { self.admin_fee()? },
227 ) {
228 Ok(dx) => {
229 if dx.is_zero() {
230 let swap = PoolSwap::new(BigUint::ZERO, BigUint::ZERO, self.clone_box(), None);
231 return Ok(Some(swap));
232 }
233 let result = self.get_amount_out(u256_to_biguint(dx), token_in, token_out)?;
234 Ok(Some(PoolSwap::new(u256_to_biguint(dx), result.amount, result.new_state, None)))
235 }
236 Err(SwapToPriceError::TargetAboveSpot) => {
237 let spot = self.spot_price(token_in, token_out)?;
238 let decimal_adjustment =
239 10f64.powi(decimals_exponent(token_in.decimals, token_out.decimals)?);
240 let target =
241 u256_to_f64(target_num)? / u256_to_f64(target_den)? * decimal_adjustment;
242 Err(SimulationError::InvalidInput(
243 format!("Target price {target} is above spot price {spot}"),
244 None,
245 ))
246 }
247 Err(SwapToPriceError::TargetBelowLimit) => Err(SimulationError::InvalidInput(
248 format!(
249 "Target price below reachable limit for curve pool {pool}",
250 pool = self.pool_address
251 ),
252 None,
253 )),
254 Err(err @ SwapToPriceError::InvalidInput(_)) => Err(SimulationError::InvalidInput(
255 format!("{err} for curve pool {pool}", pool = self.pool_address),
256 None,
257 )),
258 Err(SwapToPriceError::UnsupportedVariant) => Ok(None),
259 Err(err @ SwapToPriceError::MathFailed) => {
260 debug!(
261 pool = %self.pool_address,
262 %err,
263 "Curve native swap-to-price failed; using the numerical search"
264 );
265 Ok(None)
266 }
267 }
268 }
269}
270
271fn set_fixed_fee(pool: &mut Pool, fee: U256) -> Option<()> {
274 match pool {
275 Pool::TwoCryptoV1 { mid_fee, out_fee, .. } |
276 Pool::TwoCryptoNG { mid_fee, out_fee, .. } |
277 Pool::TwoCryptoStable { mid_fee, out_fee, .. } |
278 Pool::TriCryptoV1 { mid_fee, out_fee, .. } |
279 Pool::TriCryptoNG { mid_fee, out_fee, .. } => {
280 *mid_fee = fee;
281 *out_fee = fee;
282 Some(())
283 }
284 Pool::StableSwapV0 { .. } |
285 Pool::StableSwapV1 { .. } |
286 Pool::StableSwapV2 { .. } |
287 Pool::StableSwapSTETH { .. } |
288 Pool::StableSwapALend { .. } |
289 Pool::StableSwapNG { .. } |
290 Pool::StableSwapMeta { .. } => None,
291 }
292}
293
294#[typetag::serde]
295impl ProtocolSim for CurveState {
296 fn fee(&self) -> f64 {
297 let fee = self.pool.fee().or_else(|| {
298 self.pool
299 .crypto_fees()
300 .map(|(mid, _, _)| mid)
301 });
302 fee.and_then(|f| u256_to_f64(f).ok())
303 .map(|f| f / FEE_DENOMINATOR)
304 .unwrap_or(0.0)
305 }
306
307 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
308 let i = self.coin_index(&base.address)?;
309 let j = self.coin_index("e.address)?;
310 let (numerator, denominator) = self
311 .pool
312 .spot_price(i, j)
313 .ok_or_else(|| {
314 SimulationError::RecoverableError(format!(
315 "curve spot price unavailable for {}",
316 self.pool_address
317 ))
318 })?;
319 let ratio = u256_to_f64(numerator)? / u256_to_f64(denominator)?;
322 let decimal_adjustment = 10f64.powi(decimals_exponent(base.decimals, quote.decimals)?);
323 Ok(ratio * decimal_adjustment)
324 }
325
326 fn get_amount_out(
327 &self,
328 amount_in: BigUint,
329 token_in: &Token,
330 token_out: &Token,
331 ) -> Result<GetAmountOutResult, SimulationError> {
332 let i = self.coin_index(&token_in.address)?;
333 let j = self.coin_index(&token_out.address)?;
334 let dx = biguint_to_u256(&amount_in);
335
336 let mut new_pool = self.pool.clone();
337 let dy = if self.is_crypto() {
338 let dy = self
339 .pool
340 .get_amount_out(i, j, dx)
341 .ok_or_else(|| {
342 SimulationError::RecoverableError(format!(
343 "curve get_amount_out failed for {}",
344 self.pool_address
345 ))
346 })?;
347 let balances = self.pool.balances();
348 new_pool
350 .set_balance(i, balances[i] + dx)
351 .map_err(|e| SimulationError::FatalError(e.to_string()))?;
352 new_pool
353 .set_balance(j, balances[j].saturating_sub(dy))
354 .map_err(|e| SimulationError::FatalError(e.to_string()))?;
355 dy
356 } else {
357 let result = exchange(&self.pool, i, j, dx, self.admin_fee()?).ok_or_else(|| {
358 SimulationError::RecoverableError(format!(
359 "curve exchange accounting failed for {}",
360 self.pool_address
361 ))
362 })?;
363 for (index, balance) in result.balances.into_iter().enumerate() {
364 new_pool
365 .set_balance(index, balance)
366 .map_err(|e| SimulationError::FatalError(e.to_string()))?;
367 }
368 result.amount
369 };
370
371 let new_state = Self { pool: new_pool, ..self.clone() };
372 Ok(GetAmountOutResult::new(
373 u256_to_biguint(dy),
374 self.gas_estimate()
375 .to_biguint()
376 .expect("u64 fits in BigUint"),
377 Box::new(new_state),
378 ))
379 }
380
381 fn get_limits(
382 &self,
383 sell_token: Bytes,
384 buy_token: Bytes,
385 ) -> Result<(BigUint, BigUint), SimulationError> {
386 let i = self.coin_index(&sell_token)?;
387 let j = self.coin_index(&buy_token)?;
388 let (balance_in, balance_out) = {
389 let balances = self.pool.balances();
390 (balances[i], balances[j])
391 };
392 if balance_in.is_zero() || balance_out.is_zero() {
393 return Ok((BigUint::ZERO, BigUint::ZERO));
394 }
395 let max_out_reserve = balance_out.saturating_sub(U256::from(1));
398 let max_out = self
399 .pool
400 .get_amount_out(i, j, balance_in)
401 .ok_or_else(|| {
402 SimulationError::RecoverableError(format!(
403 "curve get_limits: solver failed at max input for {}",
404 self.pool_address
405 ))
406 })?
407 .min(max_out_reserve);
408 Ok((u256_to_biguint(balance_in), u256_to_biguint(max_out)))
409 }
410
411 fn delta_transition(
418 &mut self,
419 delta: ProtocolStateDelta,
420 _tokens: &std::collections::HashMap<Bytes, Token>,
421 _balances: &Balances,
422 ) -> Result<(), TransitionError> {
423 let mut policy = self.policy.clone();
424 for (name, value) in &delta.updated_attributes {
425 policy
426 .update(name, value)
427 .map_err(|error| TransitionError::DecodeError(error.to_string()))?;
428 }
429 for name in &delta.deleted_attributes {
430 policy.delete(name);
431 }
432 let state = match delta
433 .updated_attributes
434 .get(vm::POOL_STATE_ADJUSTED)
435 {
436 Some(encoded) => {
437 let state = vm::decode_raw_state(encoded)?;
438 if state.variant != self.variant {
439 return Err(SimulationError::FatalError(format!(
440 "Variant mismatch: expected {}, got {}",
441 self.variant, state.variant
442 ))
443 .into())
444 }
445 if state.token_decimals != self.decimals {
446 return Err(SimulationError::FatalError(format!(
447 "Token decimals mismatch: expected {:?}, got {:?}",
448 self.decimals, state.token_decimals
449 ))
450 .into())
451 }
452 state
453 }
454 None => {
455 let engine = create_engine(SHARED_TYCHO_DB.clone(), false)?;
456 let pool_address = AlloyAddress::from_slice(self.pool_address.as_ref());
457 vm::read_raw_pool_state(
458 &engine,
459 &pool_address,
460 self.variant,
461 &self.decimals,
462 &Default::default(),
463 )?
464 }
465 };
466 let mut pool = build_pool(&state)
467 .map_err(|e| SimulationError::FatalError(format!("curve build_pool failed: {e}")))?;
468 let was_granted = self.is_exclusive_view();
469 self.policy = policy;
470 if self.pricing == Pricing::Exclusive {
471 let is_granted = self.apply_grant(&mut pool).is_some();
472 if is_granted != was_granted {
473 info!(
474 pool = %self.pool_address,
475 is_granted,
476 "curve exclusive view changes between grant and public pricing"
477 );
478 }
479 }
480 self.pool = pool;
481 self.admin_fee = state.admin_fee;
482 Ok(())
483 }
484
485 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
489 match params.swap_constraint() {
490 SwapConstraint::TradeLimitPrice { .. } => {
491 crate::evm::query_pool_swap::query_pool_swap(self, params)
492 }
493 SwapConstraint::PoolTargetPrice { target, tolerance, .. } => {
494 let native = self.swap_to_target_price(
495 params.token_in(),
496 params.token_out(),
497 target,
498 *tolerance,
499 )?;
500 match native {
501 Some(swap) => Ok(swap),
502 None => crate::evm::query_pool_swap::query_pool_swap(self, params),
503 }
504 }
505 }
506 }
507
508 fn clone_box(&self) -> Box<dyn ProtocolSim> {
509 Box::new(self.clone())
510 }
511
512 fn as_any(&self) -> &dyn Any {
513 self
514 }
515
516 fn as_any_mut(&mut self) -> &mut dyn Any {
517 self
518 }
519
520 fn eq(&self, other: &dyn ProtocolSim) -> bool {
521 other
522 .as_any()
523 .downcast_ref::<Self>()
524 .is_some_and(|other| self == other)
525 }
526}
527
528#[cfg(test)]
529mod tests {
530 use std::{collections::HashMap, str::FromStr};
531
532 use num_traits::ToPrimitive;
533 use rstest::rstest;
534 use tycho_common::{
535 models::Chain,
536 simulation::protocol_sim::{QueryPoolSwapParams, SwapConstraint},
537 };
538
539 use super::*;
540 use crate::evm::{
541 protocol::curve::{
542 adapter::RawPoolState,
543 policy::{
544 POLICY_ATTRIBUTE, POLICY_KILLED_ATTRIBUTE, POLICY_MIN_FEE_ATTRIBUTE,
545 POLICY_VERSION_ATTRIBUTE,
546 },
547 vm::encode_raw_state,
548 },
549 query_pool_swap::test_helpers::{target_price_params, to_price},
550 };
551
552 const VARIANT: CurveVariant = CurveVariant::TriCryptoNG;
553 const DECIMALS: [u8; 3] = [6, 8, 18];
554
555 fn u(s: &str) -> U256 {
556 s.parse().unwrap()
557 }
558
559 fn raw_pool_state(balances: Vec<U256>) -> RawPoolState {
561 RawPoolState {
562 variant: VARIANT,
563 balances,
564 token_decimals: DECIMALS.to_vec(),
565 amp: u("1707629"),
566 mid_fee: Some(u("3000000")),
567 out_fee: Some(u("30000000")),
568 fee_gamma: Some(u("500000000000000")),
569 d: Some(u("7457948167729606869978625")),
570 gamma: Some(u("11809167828997")),
571 price_scale: Some(vec![u("59372627314351316239076"), u("1565715369034455123313")]),
572 ..Default::default()
573 }
574 }
575
576 fn state(balances: Vec<U256>) -> CurveState {
577 let raw_state = raw_pool_state(balances);
578 let pool = build_pool(&raw_state).expect("build");
579 CurveState::new(
580 Bytes::from([7u8; 20]),
581 vec![Bytes::from([1u8; 20]), Bytes::from([2u8; 20]), Bytes::from([3u8; 20])],
582 DECIMALS.to_vec(),
583 VARIANT,
584 pool,
585 Some(U256::ZERO),
586 )
587 }
588
589 fn delta(attributes: HashMap<String, Bytes>) -> ProtocolStateDelta {
590 ProtocolStateDelta { updated_attributes: attributes, ..Default::default() }
591 }
592
593 #[test]
594 fn test_delta_transition_rebuilds_from_attribute() {
595 let confirmed = vec![u("2466241139205"), u("4200057336"), u("1595469030050811720465")];
596 let pending = vec![u("2470000000000"), u("4190000000"), u("1600000000000000000000")];
597 let mut curve = state(confirmed.clone());
598 let attribute = encode_raw_state(&raw_pool_state(pending.clone())).expect("encode");
599
600 curve
601 .delta_transition(
602 delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), attribute)])),
603 &HashMap::new(),
604 &Balances::default(),
605 )
606 .expect("delta transition from attribute failed");
607
608 assert_eq!(
611 curve.pool.balances()[..3],
612 pending[..],
613 "balances must come from the attribute"
614 );
615 assert_ne!(curve.pool.balances()[..3], confirmed[..]);
616 }
617
618 #[test]
619 fn test_delta_transition_errors_on_variant_mismatch() {
620 let mut curve = state(vec![u("1"), u("2"), u("3")]);
621 let mut pending_state = raw_pool_state(curve.pool.balances().to_vec());
622 pending_state.variant = CurveVariant::StableSwapMeta;
623 let encoded = encode_raw_state(&pending_state).expect("encode");
624
625 let result = curve.delta_transition(
626 delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), encoded)])),
627 &HashMap::new(),
628 &Balances::default(),
629 );
630
631 assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
632 }
633
634 #[test]
635 fn test_delta_transition_errors_on_decimals_mismatch() {
636 let mut curve = state(vec![u("1"), u("2"), u("3")]);
637 let mut pending_state = raw_pool_state(curve.pool.balances().to_vec());
638 pending_state.token_decimals = vec![18, 18, 18];
639 let encoded = encode_raw_state(&pending_state).expect("encode");
640
641 let result = curve.delta_transition(
642 delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), encoded)])),
643 &HashMap::new(),
644 &Balances::default(),
645 );
646
647 assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
648 }
649
650 #[test]
651 fn test_delta_transition_rejects_malformed_attribute() {
652 let mut curve = state(vec![u("1"), u("2"), u("3")]);
653
654 let result = curve.delta_transition(
655 delta(HashMap::from([(
656 vm::POOL_STATE_ADJUSTED.to_string(),
657 Bytes::from(b"not json".to_vec()),
658 )])),
659 &HashMap::new(),
660 &Balances::default(),
661 );
662
663 assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
666 }
667
668 fn policy(entries: &[(&str, Vec<u8>)]) -> CurvePolicy {
669 let attributes = entries
670 .iter()
671 .map(|(name, value)| (name.to_string(), Bytes::from(value.clone())))
672 .collect();
673 CurvePolicy::from_attributes(&attributes).expect("decode policy")
674 }
675
676 #[rstest]
677 #[case::set(Some(vec![7; 20]), false, Some(vec![7; 20]))]
678 #[case::cleared(Some(vec![0; 20]), false, None)]
679 #[case::deleted(None, true, None)]
680 #[case::absent(None, false, Some(vec![9; 20]))]
681 fn test_delta_transition_policy_attribute(
682 #[case] updated: Option<Vec<u8>>,
683 #[case] deleted: bool,
684 #[case] expected: Option<Vec<u8>>,
685 ) {
686 let balances = vec![u("1"), u("2"), u("3")];
687 let mut curve = state(balances.clone()).with_policy(policy(&[
688 (POLICY_ATTRIBUTE, vec![9; 20]),
689 (POLICY_MIN_FEE_ATTRIBUTE, vec![5]),
690 ]));
691 let mut attributes = HashMap::from([(
692 vm::POOL_STATE_ADJUSTED.to_string(),
693 encode_raw_state(&raw_pool_state(balances)).expect("encode"),
694 )]);
695 if let Some(value) = updated {
696 attributes.insert(POLICY_ATTRIBUTE.to_string(), Bytes::from(value));
697 }
698 let mut delta = delta(attributes);
699 if deleted {
700 delta
701 .deleted_attributes
702 .insert(POLICY_ATTRIBUTE.to_string());
703 }
704
705 curve
706 .delta_transition(delta, &HashMap::new(), &Balances::default())
707 .expect("delta transition failed");
708
709 let mut expected_entries = vec![(POLICY_MIN_FEE_ATTRIBUTE, vec![5])];
710 if let Some(address) = expected {
711 expected_entries.push((POLICY_ATTRIBUTE, address));
712 }
713 assert_eq!(curve.policy, policy(&expected_entries));
714 }
715
716 const WAD: u128 = 1_000_000_000_000_000_000;
717 const RATE_6_DEC: u128 = 1_000_000_000_000_000_000_000_000_000_000;
718
719 fn token(index: u8, decimals: u32) -> Token {
720 let address =
721 Bytes::from_str(&format!("0x00000000000000000000000000000000000000{index:02x}"))
722 .expect("valid address");
723 Token::new(
724 &address,
725 &format!("T{index}"),
726 decimals,
727 0,
728 &[Some(10_000)],
729 Chain::Ethereum,
730 100,
731 )
732 }
733
734 fn curve_state(pool: Pool, variant: CurveVariant, decimals: Vec<u8>) -> CurveState {
735 let tokens: Vec<Bytes> = (0..decimals.len())
736 .map(|k| token(u8::try_from(k).unwrap(), decimals[k] as u32).address)
737 .collect();
738 CurveState::new(
739 Bytes::from_str("0x00000000000000000000000000000000000000ff").expect("valid address"),
740 tokens,
741 decimals,
742 variant,
743 pool,
744 Some(U256::ZERO),
745 )
746 }
747
748 fn v1_two_coin_state() -> (CurveState, Token, Token) {
749 let pool = Pool::StableSwapV1 {
750 balances: vec![U256::from(50_000_000u128 * WAD), U256::from(48_000_000u128 * WAD)],
751 rates: vec![U256::from(WAD), U256::from(WAD)],
752 amp: U256::from(2000u64),
753 fee: U256::from(1_000_000u64),
754 };
755 (curve_state(pool, CurveVariant::StableSwapV1, vec![18, 18]), token(0, 18), token(1, 18))
756 }
757
758 fn v1_three_coin_mixed_state() -> (CurveState, Token, Token) {
759 let pool = Pool::StableSwapV1 {
761 balances: vec![
762 U256::from(63_975_337_809_806_329_031_583_135u128),
763 U256::from(61_219_263_170_093u128),
764 U256::from(37_832_425_459_809u128),
765 ],
766 rates: vec![U256::from(WAD), U256::from(RATE_6_DEC), U256::from(RATE_6_DEC)],
767 amp: U256::from(4000u64),
768 fee: U256::from(1_500_000u64),
769 };
770 (curve_state(pool, CurveVariant::StableSwapV1, vec![18, 6, 6]), token(0, 18), token(1, 6))
771 }
772
773 fn v1_three_coin_mixed_state_reverse() -> (CurveState, Token, Token) {
774 let (state, token_out, token_in) = v1_three_coin_mixed_state();
775 (state, token_in, token_out)
776 }
777
778 fn ng_dynamic_fee_state() -> (CurveState, Token, Token) {
779 let pool = Pool::StableSwapNG {
780 balances: vec![U256::from(1_500_000u128 * WAD), U256::from(700_000u128 * WAD)],
781 rates: vec![U256::from(WAD), U256::from(WAD)],
782 amp: U256::from(40_000u64),
783 fee: U256::from(4_000_000u64),
784 offpeg_fee_multiplier: U256::from(20_000_000_000u64),
785 };
786 (curve_state(pool, CurveVariant::StableSwapNG, vec![18, 18]), token(0, 18), token(1, 18))
787 }
788
789 fn meta_state() -> (CurveState, Token, Token) {
790 let pool = Pool::StableSwapMeta {
791 balances: vec![U256::from(500_000u128 * WAD), U256::from(480_000u128 * WAD)],
792 rates: vec![U256::from(WAD), U256::from(1_030_000_000_000_000_000u128)],
793 amp: U256::from(50_000u64),
794 fee: U256::from(4_000_000u64),
795 };
796 (curve_state(pool, CurveVariant::StableSwapMeta, vec![18, 18]), token(0, 18), token(1, 18))
797 }
798
799 #[test]
800 fn pending_state_preserves_admin_fee_for_exchange() {
801 let (mut state, token_in, token_out) = v1_two_coin_state();
802 let pool = state.pool.clone();
803 #[expect(clippy::unreachable, reason = "v1_two_coin_state builds a StableSwapV1 pool")]
804 let Pool::StableSwapV1 { balances, rates: _, amp, fee } = pool
805 else {
806 unreachable!()
807 };
808 let raw = RawPoolState {
809 variant: CurveVariant::StableSwapV1,
810 balances,
811 amp,
812 fee: Some(fee),
813 token_decimals: vec![18, 18],
814 admin_fee: Some(U256::from(5_000_000_000u64)),
815 ..Default::default()
816 };
817 state
818 .delta_transition(
819 delta(HashMap::from([(
820 vm::POOL_STATE_ADJUSTED.into(),
821 encode_raw_state(&raw).unwrap(),
822 )])),
823 &HashMap::new(),
824 &Balances::default(),
825 )
826 .unwrap();
827 assert_eq!(state.admin_fee, raw.admin_fee);
828 let mut without_admin = state.clone();
829 without_admin.admin_fee = Some(U256::ZERO);
830 let amount = BigUint::from(WAD);
831 let with_fee = state
832 .get_amount_out(amount.clone(), &token_in, &token_out)
833 .unwrap();
834 let no_fee = without_admin
835 .get_amount_out(amount, &token_in, &token_out)
836 .unwrap();
837 assert_eq!(with_fee.amount, no_fee.amount);
838 let balance = |result: &GetAmountOutResult| {
839 result
840 .new_state
841 .as_any()
842 .downcast_ref::<CurveState>()
843 .unwrap()
844 .pool
845 .balances()[1]
846 };
847 assert!(balance(&with_fee) < balance(&no_fee));
848 }
849
850 fn granted_policy(min_fee: u64) -> CurvePolicy {
851 policy(&[
852 (POLICY_VERSION_ATTRIBUTE, vec![1]),
853 (POLICY_MIN_FEE_ATTRIBUTE, min_fee.to_be_bytes().to_vec()),
854 ])
855 }
856
857 #[test]
858 fn test_exclusive_view_min_fee() {
859 let (state, token_in, token_out) = two_crypto_ng_state();
860 let amount_out = |state: &CurveState| {
861 state
862 .get_amount_out(BigUint::from(10u64).pow(18), &token_in, &token_out)
863 .expect("amount out")
864 };
865 let exclusive = |min_fee: u64| {
866 state
867 .clone()
868 .with_policy(granted_policy(min_fee))
869 .exclusive_view()
870 .expect("exclusive view")
871 };
872 let lowest = amount_out(&exclusive(100_000));
873 let one_percent = amount_out(&exclusive(100_000_000));
874
875 assert!(lowest.amount > amount_out(&state).amount);
876 let scaled_one_percent = &one_percent.amount * 99_999u64;
878 let scaled_lowest = &lowest.amount * 99_000u64;
879 let difference = if scaled_one_percent > scaled_lowest {
880 scaled_one_percent - scaled_lowest
881 } else {
882 scaled_lowest - scaled_one_percent
883 };
884 assert!(difference <= BigUint::from(200_000u64), "difference {difference}");
885 assert_eq!(one_percent.gas, BigUint::from(CRYPTOSWAP_GAS + GRANT_GAS));
886 }
887
888 #[rstest]
889 #[case::no_policy(vec![0], vec![0], 100_000)]
890 #[case::unknown_version(vec![2], vec![0], 100_000)]
891 #[case::killed(vec![1], vec![1], 100_000)]
892 #[case::zero_min_fee(vec![1], vec![0], 0)]
893 fn test_exclusive_view_without_grants(
894 #[case] version: Vec<u8>,
895 #[case] killed: Vec<u8>,
896 #[case] min_fee: u64,
897 ) {
898 let (state, _, _) = two_crypto_ng_state();
899 let state = state.with_policy(policy(&[
900 (POLICY_VERSION_ATTRIBUTE, version),
901 (POLICY_KILLED_ATTRIBUTE, killed),
902 (POLICY_MIN_FEE_ATTRIBUTE, min_fee.to_be_bytes().to_vec()),
903 ]));
904
905 assert!(state.exclusive_view().is_none());
906 }
907
908 #[test]
909 fn test_exclusive_view_stableswap_pool() {
910 let (state, _, _) = v1_two_coin_state();
911
912 assert!(state
913 .with_policy(granted_policy(100_000))
914 .exclusive_view()
915 .is_none());
916 }
917
918 fn exclusive_view_after_delta(name: &str, value: Vec<u8>) -> CurveState {
920 let balances = vec![u("2466241139205"), u("4200057336"), u("1595469030050811720465")];
921 let mut view = state(balances.clone())
922 .with_policy(granted_policy(100_000))
923 .exclusive_view()
924 .expect("exclusive view");
925 let attributes = HashMap::from([
926 (
927 vm::POOL_STATE_ADJUSTED.to_string(),
928 encode_raw_state(&raw_pool_state(balances)).expect("encode"),
929 ),
930 (name.to_string(), Bytes::from(value)),
931 ]);
932 view.delta_transition(delta(attributes), &HashMap::new(), &Balances::default())
933 .expect("delta transition failed");
934 view
935 }
936
937 #[test]
938 fn test_exclusive_view_delta_transition_min_fee() {
939 let view = exclusive_view_after_delta(
940 POLICY_MIN_FEE_ATTRIBUTE,
941 100_000_000u64.to_be_bytes().to_vec(),
942 );
943
944 assert!(view.is_exclusive_view());
945 assert_eq!(view.fee(), 0.01);
946 }
947
948 #[test]
949 fn test_exclusive_view_delta_transition_killed() {
950 let view = exclusive_view_after_delta(POLICY_KILLED_ATTRIBUTE, vec![1]);
951
952 assert!(!view.is_exclusive_view());
953 assert_eq!(view.fee(), 0.0003);
954 }
955
956 #[test]
957 fn test_exclusive_view_delta_transition_revived() {
958 let mut view = exclusive_view_after_delta(POLICY_KILLED_ATTRIBUTE, vec![1]);
959 let balances = vec![u("2466241139205"), u("4200057336"), u("1595469030050811720465")];
960 let attributes = HashMap::from([
961 (
962 vm::POOL_STATE_ADJUSTED.to_string(),
963 encode_raw_state(&raw_pool_state(balances)).expect("encode"),
964 ),
965 (POLICY_KILLED_ATTRIBUTE.to_string(), Bytes::from(vec![0])),
966 ]);
967
968 view.delta_transition(delta(attributes), &HashMap::new(), &Balances::default())
969 .expect("delta transition failed");
970
971 assert!(view.is_exclusive_view());
972 assert_eq!(view.fee(), 0.00001);
973 }
974
975 #[test]
976 fn test_delta_transition_malformed_policy_attribute() {
977 let balances = vec![u("1"), u("2"), u("3")];
978 let before = policy(&[(POLICY_ATTRIBUTE, vec![9; 20])]);
979 let mut curve = state(balances.clone()).with_policy(before.clone());
980 let attributes = HashMap::from([
981 (
982 vm::POOL_STATE_ADJUSTED.to_string(),
983 encode_raw_state(&raw_pool_state(balances)).expect("encode"),
984 ),
985 (POLICY_ATTRIBUTE.to_string(), Bytes::from(vec![7; 19])),
986 ]);
987
988 let result =
989 curve.delta_transition(delta(attributes), &HashMap::new(), &Balances::default());
990
991 assert!(matches!(result, Err(TransitionError::DecodeError(_))), "got {result:?}");
992 assert_eq!(curve.policy, before);
993 }
994
995 fn two_crypto_ng_state() -> (CurveState, Token, Token) {
996 let wad = U256::from(WAD);
997 let pool = Pool::TwoCryptoNG {
998 balances: [U256::from(5000u64) * wad, U256::from(5000u64) * wad],
999 precisions: [U256::from(1u64), U256::from(1u64)],
1000 price_scale: wad,
1001 d: U256::from(10000u64) * wad,
1002 ann: U256::from(540_000u64) * U256::from(10_000u64),
1003 gamma: U256::from(11_809_167_828_997u64),
1004 mid_fee: U256::from(3_000_000u64),
1005 out_fee: U256::from(30_000_000u64),
1006 fee_gamma: U256::from(230_000_000_000_000u64),
1007 };
1008 (curve_state(pool, CurveVariant::TwoCryptoNG, vec![18, 18]), token(0, 18), token(1, 18))
1009 }
1010
1011 const TOLERANCE: f64 = 0.001;
1012
1013 fn spot_target_params(
1016 state: &CurveState,
1017 token_in: &Token,
1018 token_out: &Token,
1019 multiplier: f64,
1020 ) -> (QueryPoolSwapParams, f64) {
1021 let spot = state
1022 .spot_price(token_in, token_out)
1023 .expect("spot price");
1024 let target_f64 = spot * multiplier;
1025 let target = to_price(target_f64, token_in, token_out);
1026 (target_price_params(token_in, token_out, target, TOLERANCE), target_f64)
1027 }
1028
1029 #[rstest]
1030 #[case::v1_two_coin_shallow(v1_two_coin_state(), 0.9999)]
1031 #[case::v1_two_coin_mid(v1_two_coin_state(), 0.999)]
1032 #[case::v1_two_coin_deep(v1_two_coin_state(), 0.99)]
1033 #[case::v1_mixed_decimals_18_to_6(v1_three_coin_mixed_state(), 0.99)]
1034 #[case::v1_mixed_decimals_6_to_18(v1_three_coin_mixed_state_reverse(), 0.99)]
1035 #[case::ng_dynamic_fee(ng_dynamic_fee_state(), 0.99)]
1036 #[case::ng_dynamic_fee_mid(ng_dynamic_fee_state(), 0.999)]
1037 #[case::meta_virtual_price(meta_state(), 0.99)]
1038 #[case::meta_virtual_price_mid(meta_state(), 0.999)]
1039 fn test_query_pool_swap_native_amounts(
1040 #[case] setup: (CurveState, Token, Token),
1041 #[case] multiplier: f64,
1042 ) {
1043 let (state, token_in, token_out) = setup;
1044 let (params, target) = spot_target_params(&state, &token_in, &token_out, multiplier);
1045
1046 let swap = state
1047 .query_pool_swap(¶ms)
1048 .expect("native query_pool_swap");
1049
1050 let price = swap
1051 .new_state()
1052 .spot_price(&token_in, &token_out)
1053 .unwrap();
1054 assert!(price >= target && price <= target * (1.0 + TOLERANCE));
1055 let executed = state
1056 .get_amount_out(swap.amount_in().clone(), &token_in, &token_out)
1057 .unwrap();
1058 assert_eq!(swap.amount_out(), &executed.amount);
1059 assert!(ProtocolSim::eq(swap.new_state(), executed.new_state.as_ref()));
1060 }
1061
1062 #[rstest]
1065 #[case::v1_two_coin_shallow(v1_two_coin_state(), 0.9999)]
1066 #[case::v1_two_coin_mid(v1_two_coin_state(), 0.999)]
1067 #[case::v1_two_coin_deep(v1_two_coin_state(), 0.99)]
1068 #[case::v1_mixed_decimals_18_to_6(v1_three_coin_mixed_state(), 0.99)]
1069 #[case::v1_mixed_decimals_6_to_18(v1_three_coin_mixed_state_reverse(), 0.99)]
1070 #[case::ng_dynamic_fee(ng_dynamic_fee_state(), 0.99)]
1071 #[case::ng_dynamic_fee_mid(ng_dynamic_fee_state(), 0.999)]
1072 #[case::meta_virtual_price(meta_state(), 0.99)]
1073 #[case::meta_virtual_price_mid(meta_state(), 0.999)]
1074 fn test_query_pool_swap_numerical_comparison(
1075 #[case] setup: (CurveState, Token, Token),
1076 #[case] multiplier: f64,
1077 ) {
1078 let (state, token_in, token_out) = setup;
1079 let (params, target_f64) = spot_target_params(&state, &token_in, &token_out, multiplier);
1080
1081 let native = state
1082 .query_pool_swap(¶ms)
1083 .expect("native query_pool_swap");
1084 let numerical = crate::evm::query_pool_swap::query_pool_swap(&state, ¶ms)
1085 .expect("numerical query_pool_swap");
1086
1087 for (label, swap, band) in
1088 [("native", &native, TOLERANCE / 2.0), ("numerical", &numerical, 5.0 * TOLERANCE)]
1089 {
1090 assert!(swap.amount_in() > &BigUint::ZERO, "{label} amount_in should be > 0");
1091 let new_spot = swap
1092 .new_state()
1093 .spot_price(&token_in, &token_out)
1094 .expect("post-swap spot");
1095 let error = (new_spot - target_f64) / target_f64;
1096 assert!(
1097 error >= -1e-12,
1098 "{label} post-swap spot {new_spot} fell below target {target_f64}"
1099 );
1100 assert!(
1101 error <= band,
1102 "{label} post-swap spot {new_spot} outside band of target {target_f64}: {error}"
1103 );
1104 }
1105 }
1106
1107 #[test]
1110 fn test_crypto_variant_delegates_to_numerical() {
1111 let (state, token_in, token_out) = two_crypto_ng_state();
1112 let (params, _) = spot_target_params(&state, &token_in, &token_out, 0.995);
1113
1114 let result = state.query_pool_swap(¶ms);
1115 let Err(SimulationError::InvalidInput(msg, _)) = result else {
1116 panic!("crypto pools must delegate to the numerical search, got {result:?}");
1117 };
1118 assert!(msg.contains("< limit"), "expected the numerical search's limit error, got: {msg}");
1119 }
1120
1121 #[test]
1122 fn test_query_pool_swap_target_wider_than_u256() {
1123 let (state, token_in, token_out) = v1_two_coin_state();
1124 let (params, target_f64) = spot_target_params(&state, &token_in, &token_out, 0.999);
1125 let SwapConstraint::PoolTargetPrice { target, .. } = params.swap_constraint() else {
1126 panic!("spot_target_params builds a PoolTargetPrice constraint");
1127 };
1128 let scale = BigUint::from(1u8) << 256;
1129 let wide_target = Price::new(&target.numerator * &scale, &target.denominator * &scale);
1130 let params = target_price_params(&token_in, &token_out, wide_target, TOLERANCE);
1131
1132 let swap = state
1133 .query_pool_swap(¶ms)
1134 .expect("numerical query_pool_swap");
1135
1136 assert!(swap.price_points().is_some(), "only the numerical search returns price points");
1137 let new_spot = swap
1138 .new_state()
1139 .spot_price(&token_in, &token_out)
1140 .expect("post-swap spot");
1141 let error = (new_spot - target_f64) / target_f64;
1142 assert!(
1143 (-1e-12..=5.0 * TOLERANCE).contains(&error),
1144 "post-swap spot {new_spot} missed {target_f64}"
1145 );
1146 }
1147
1148 #[test]
1149 fn test_trade_limit_price_delegates_to_numerical() {
1150 let (state, token_in, token_out) = v1_two_coin_state();
1151 let spot = state
1152 .spot_price(&token_in, &token_out)
1153 .expect("spot price");
1154 let limit_f64 = spot * 0.999;
1155 let params = QueryPoolSwapParams::new(
1156 token_in.clone(),
1157 token_out.clone(),
1158 SwapConstraint::TradeLimitPrice {
1159 limit: to_price(limit_f64, &token_in, &token_out),
1160 tolerance: TOLERANCE,
1161 min_amount_in: None,
1162 max_amount_in: None,
1163 },
1164 );
1165
1166 let swap = state
1167 .query_pool_swap(¶ms)
1168 .expect("trade limit query_pool_swap");
1169 assert!(swap.amount_in() > &BigUint::ZERO);
1170 assert!(swap.amount_out() > &BigUint::ZERO);
1171 let trade_price = swap
1172 .amount_out()
1173 .to_f64()
1174 .expect("failed to convert the output amount to f64") /
1175 swap.amount_in()
1176 .to_f64()
1177 .expect("failed to convert the input amount to f64");
1178 assert!(trade_price >= limit_f64, "trade price {trade_price} violates limit {limit_f64}");
1179 }
1180
1181 #[rstest]
1182 #[case::above_spot(1.01, "is above spot price")]
1183 #[case::below_limit(1e-9, "below reachable limit for curve pool")]
1184 fn test_query_pool_swap_unreachable_target(#[case] multiplier: f64, #[case] expected: &str) {
1185 let (state, token_in, token_out) = v1_two_coin_state();
1186 let (params, _) = spot_target_params(&state, &token_in, &token_out, multiplier);
1187
1188 let result = state.query_pool_swap(¶ms);
1189 let Err(SimulationError::InvalidInput(msg, _)) = result else {
1190 panic!("expected InvalidInput, got {result:?}");
1191 };
1192 assert!(msg.contains(expected), "unexpected message: {msg}");
1193 }
1194
1195 #[test]
1196 fn test_query_pool_swap_target_equal_to_spot() {
1197 let (state, token_in, token_out) = v1_two_coin_state();
1198 let i = state
1199 .coin_index(&token_in.address)
1200 .expect("token_in index");
1201 let j = state
1202 .coin_index(&token_out.address)
1203 .expect("token_out index");
1204 let (num, den) = state
1205 .pool
1206 .spot_price(i, j)
1207 .expect("pool spot price");
1208 let target = Price::new(u256_to_biguint(num), u256_to_biguint(den));
1209 let params = target_price_params(&token_in, &token_out, target, TOLERANCE);
1210
1211 let swap = state
1212 .query_pool_swap(¶ms)
1213 .expect("query_pool_swap at spot");
1214 assert_eq!(swap.amount_in(), &BigUint::ZERO);
1215 assert_eq!(swap.amount_out(), &BigUint::ZERO);
1216 }
1217}