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