1use alloy_primitives::U256;
30
31use crate::evm::protocol::curve::{adapter::CurveVariant, math::Pool};
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum BuildError {
36 MissingField { variant: CurveVariant, field: &'static str },
38 WrongCoinCount { variant: CurveVariant, expected: usize, actual: usize },
40 DecimalsMismatch { balances_len: usize, decimals_len: usize },
42 DecimalsTooLarge { index: usize, decimals: u8, max: u8 },
44 DynamicRatesMismatch { balances_len: usize, rates_len: usize },
46 PriceScaleWrongLen { expected: usize, actual: usize },
48 MetaMissingVirtualPrice,
53}
54
55impl std::fmt::Display for BuildError {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 match self {
58 Self::MissingField { variant, field } => {
59 write!(f, "{variant}: missing required field `{field}`")
60 }
61 Self::WrongCoinCount { variant, expected, actual } => {
62 write!(f, "{variant}: expected {expected} coins, got {actual} balances")
63 }
64 Self::DecimalsMismatch { balances_len, decimals_len } => write!(
65 f,
66 "token_decimals length ({decimals_len}) != balances length ({balances_len})"
67 ),
68 Self::DecimalsTooLarge { index, decimals, max } => {
69 write!(f, "token_decimals[{index}] = {decimals} exceeds maximum {max}")
70 }
71 Self::DynamicRatesMismatch { balances_len, rates_len } => {
72 write!(f, "dynamic_rates length ({rates_len}) != balances length ({balances_len})")
73 }
74 Self::PriceScaleWrongLen { expected, actual } => {
75 write!(f, "price_scale: expected {expected} elements, got {actual}")
76 }
77 Self::MetaMissingVirtualPrice => write!(
78 f,
79 "StableSwapMeta: dynamic_rates must provide an explicit rate for the last coin \
80 (base pool LP token virtual_price). Without it, swap calculations are incorrect."
81 ),
82 }
83 }
84}
85
86impl std::error::Error for BuildError {}
87
88#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
94pub struct RawPoolState {
95 pub variant: CurveVariant,
97
98 #[serde(default)]
100 pub admin_fee: Option<U256>,
101
102 pub balances: Vec<U256>,
116
117 pub token_decimals: Vec<u8>,
120
121 pub amp: U256,
166
167 pub fee: Option<U256>,
170
171 pub mid_fee: Option<U256>,
173
174 pub out_fee: Option<U256>,
176
177 pub fee_gamma: Option<U256>,
179
180 pub offpeg_fee_multiplier: Option<U256>,
182
183 pub price_scale: Option<Vec<U256>>,
187
188 pub d: Option<U256>,
190
191 pub gamma: Option<U256>,
195
196 pub dynamic_rates: Option<Vec<Option<U256>>>,
227
228 pub precisions: Option<Vec<U256>>,
239
240 pub eth_variant: Option<bool>,
252}
253
254impl Default for RawPoolState {
255 fn default() -> Self {
256 Self {
257 variant: CurveVariant::StableSwapV2,
258 balances: Vec::new(),
259 token_decimals: Vec::new(),
260 amp: U256::ZERO,
261 fee: None,
262 admin_fee: None,
263 mid_fee: None,
264 out_fee: None,
265 fee_gamma: None,
266 offpeg_fee_multiplier: None,
267 price_scale: None,
268 d: None,
269 gamma: None,
270 dynamic_rates: None,
271 precisions: None,
272 eth_variant: None,
273 }
274 }
275}
276
277pub fn interpolate_a(
303 initial_a: U256,
304 future_a: U256,
305 initial_a_time: u64,
306 future_a_time: u64,
307 block_timestamp: u64,
308) -> U256 {
309 if block_timestamp >= future_a_time {
310 return future_a;
311 }
312
313 let elapsed = U256::from(block_timestamp - initial_a_time);
316 let duration = U256::from(future_a_time - initial_a_time);
317
318 if future_a > initial_a {
319 initial_a + (future_a - initial_a) * elapsed / duration
320 } else {
321 initial_a - (initial_a - future_a) * elapsed / duration
322 }
323}
324
325fn compute_stableswap_rates(
334 token_decimals: &[u8],
335 dynamic_rates: &Option<Vec<Option<U256>>>,
336) -> Vec<U256> {
337 token_decimals
338 .iter()
339 .enumerate()
340 .map(|(i, &decimals)| {
341 if let Some(ref rates) = dynamic_rates {
343 if let Some(Some(rate)) = rates.get(i) {
344 return *rate;
345 }
346 }
347 U256::from(10u64).pow(U256::from(36 - decimals as u32))
349 })
350 .collect()
351}
352
353fn compute_crypto_precisions(token_decimals: &[u8]) -> Vec<U256> {
360 token_decimals
361 .iter()
362 .map(|&decimals| U256::from(10u64).pow(U256::from(18 - decimals as u32)))
363 .collect()
364}
365
366macro_rules! require {
368 ($state:expr, $field:ident) => {
369 $state
370 .$field
371 .ok_or(BuildError::MissingField {
372 variant: $state.variant,
373 field: stringify!($field),
374 })?
375 };
376}
377
378pub fn build_pool(state: &RawPoolState) -> Result<Pool, BuildError> {
387 if state.balances.len() != state.token_decimals.len() {
389 return Err(BuildError::DecimalsMismatch {
390 balances_len: state.balances.len(),
391 decimals_len: state.token_decimals.len(),
392 });
393 }
394
395 if let Some(ref dr) = state.dynamic_rates {
397 if dr.len() != state.balances.len() {
398 return Err(BuildError::DynamicRatesMismatch {
399 balances_len: state.balances.len(),
400 rates_len: dr.len(),
401 });
402 }
403 }
404
405 match state.variant {
406 CurveVariant::StableSwapV0 |
407 CurveVariant::StableSwapV1 |
408 CurveVariant::StableSwapV2 |
409 CurveVariant::StableSwapSTETH |
410 CurveVariant::StableSwapMeta => build_stableswap_plain(state),
411 CurveVariant::StableSwapNG => build_stableswap_ng(state),
412 CurveVariant::StableSwapALend => build_stableswap_alend(state),
413 CurveVariant::TwoCryptoV1 | CurveVariant::TwoCryptoNG | CurveVariant::TwoCryptoStable => {
414 build_twocrypto(state)
415 }
416 CurveVariant::TriCryptoV1 | CurveVariant::TriCryptoNG => build_tricrypto(state),
417 }
418}
419
420fn build_stableswap_plain(state: &RawPoolState) -> Result<Pool, BuildError> {
423 let fee = require!(state, fee);
424
425 for (i, &d) in state.token_decimals.iter().enumerate() {
426 if d > 36 {
427 return Err(BuildError::DecimalsTooLarge { index: i, decimals: d, max: 36 });
428 }
429 }
430
431 if state.variant == CurveVariant::StableSwapMeta {
434 let n = state.balances.len();
435 let has_vp = state
436 .dynamic_rates
437 .as_ref()
438 .and_then(|dr| dr.get(n - 1))
439 .map(|r| r.is_some())
440 .unwrap_or(false);
441 if !has_vp {
442 return Err(BuildError::MetaMissingVirtualPrice);
443 }
444 }
445
446 let rates = compute_stableswap_rates(&state.token_decimals, &state.dynamic_rates);
447 let balances = state.balances.clone();
448 let amp = state.amp;
449
450 Ok(match state.variant {
451 CurveVariant::StableSwapV0 => Pool::StableSwapV0 { balances, rates, amp, fee },
452 CurveVariant::StableSwapV1 => Pool::StableSwapV1 { balances, rates, amp, fee },
453 CurveVariant::StableSwapV2 => Pool::StableSwapV2 { balances, rates, amp, fee },
454 CurveVariant::StableSwapSTETH => Pool::StableSwapSTETH { balances, rates, amp, fee },
455 CurveVariant::StableSwapMeta => Pool::StableSwapMeta { balances, rates, amp, fee },
456 #[expect(
457 clippy::unreachable,
458 reason = "build_pool dispatches only the plain StableSwap variants here"
459 )]
460 CurveVariant::StableSwapALend |
461 CurveVariant::StableSwapNG |
462 CurveVariant::TwoCryptoV1 |
463 CurveVariant::TwoCryptoNG |
464 CurveVariant::TwoCryptoStable |
465 CurveVariant::TriCryptoV1 |
466 CurveVariant::TriCryptoNG => unreachable!(),
467 })
468}
469
470fn build_stableswap_ng(state: &RawPoolState) -> Result<Pool, BuildError> {
471 let fee = require!(state, fee);
472 let offpeg = state
477 .offpeg_fee_multiplier
478 .unwrap_or_else(|| U256::from(10_000_000_000u64));
479
480 for (i, &d) in state.token_decimals.iter().enumerate() {
481 if d > 36 {
482 return Err(BuildError::DecimalsTooLarge { index: i, decimals: d, max: 36 });
483 }
484 }
485
486 let rates = compute_stableswap_rates(&state.token_decimals, &state.dynamic_rates);
487
488 Ok(Pool::StableSwapNG {
489 balances: state.balances.clone(),
490 rates,
491 amp: state.amp,
492 fee,
493 offpeg_fee_multiplier: offpeg,
494 })
495}
496
497fn build_stableswap_alend(state: &RawPoolState) -> Result<Pool, BuildError> {
498 let fee = require!(state, fee);
499 let offpeg = require!(state, offpeg_fee_multiplier);
500
501 for (i, &d) in state.token_decimals.iter().enumerate() {
502 if d > 18 {
503 return Err(BuildError::DecimalsTooLarge { index: i, decimals: d, max: 18 });
504 }
505 }
506
507 let precision_mul = compute_crypto_precisions(&state.token_decimals);
508
509 Ok(Pool::StableSwapALend {
510 balances: state.balances.clone(),
511 precision_mul,
512 amp: state.amp,
513 fee,
514 offpeg_fee_multiplier: offpeg,
515 })
516}
517
518fn build_twocrypto(state: &RawPoolState) -> Result<Pool, BuildError> {
519 if state.balances.len() != 2 {
520 return Err(BuildError::WrongCoinCount {
521 variant: state.variant,
522 expected: 2,
523 actual: state.balances.len(),
524 });
525 }
526
527 for (i, &d) in state.token_decimals.iter().enumerate() {
528 if d > 18 {
529 return Err(BuildError::DecimalsTooLarge { index: i, decimals: d, max: 18 });
530 }
531 }
532
533 let mid_fee = require!(state, mid_fee);
534 let out_fee = require!(state, out_fee);
535 let fee_gamma = require!(state, fee_gamma);
536 let d = require!(state, d);
537 let ann = state.amp;
538
539 let price_scale_vec = state
540 .price_scale
541 .as_ref()
542 .ok_or(BuildError::MissingField { variant: state.variant, field: "price_scale" })?;
543 if price_scale_vec.len() != 1 {
544 return Err(BuildError::PriceScaleWrongLen { expected: 1, actual: price_scale_vec.len() });
545 }
546 let price_scale = price_scale_vec[0];
547
548 let default_precs = compute_crypto_precisions(&state.token_decimals);
549 let precisions = state
550 .precisions
551 .as_deref()
552 .unwrap_or(&default_precs);
553 let balances: [U256; 2] = [state.balances[0], state.balances[1]];
554 let prec_arr: [U256; 2] = [precisions[0], precisions[1]];
555
556 match state.variant {
557 CurveVariant::TwoCryptoV1 => {
558 let gamma = require!(state, gamma);
559 let eth_variant = require!(state, eth_variant);
562 Ok(Pool::TwoCryptoV1 {
563 balances,
564 precisions: prec_arr,
565 price_scale,
566 d,
567 ann,
568 gamma,
569 mid_fee,
570 out_fee,
571 fee_gamma,
572 eth_variant,
573 })
574 }
575 CurveVariant::TwoCryptoNG => {
576 let gamma = require!(state, gamma);
577 Ok(Pool::TwoCryptoNG {
578 balances,
579 precisions: prec_arr,
580 price_scale,
581 d,
582 ann,
583 gamma,
584 mid_fee,
585 out_fee,
586 fee_gamma,
587 })
588 }
589 CurveVariant::TwoCryptoStable => Ok(Pool::TwoCryptoStable {
590 balances,
591 precisions: prec_arr,
592 price_scale,
593 d,
594 ann,
595 mid_fee,
596 out_fee,
597 fee_gamma,
598 }),
599 #[expect(
600 clippy::unreachable,
601 reason = "build_pool dispatches only the TwoCrypto variants here"
602 )]
603 CurveVariant::StableSwapV0 |
604 CurveVariant::StableSwapV1 |
605 CurveVariant::StableSwapV2 |
606 CurveVariant::StableSwapSTETH |
607 CurveVariant::StableSwapALend |
608 CurveVariant::StableSwapNG |
609 CurveVariant::StableSwapMeta |
610 CurveVariant::TriCryptoV1 |
611 CurveVariant::TriCryptoNG => {
612 unreachable!("build_twocrypto called for non-twocrypto variant")
613 }
614 }
615}
616
617fn build_tricrypto(state: &RawPoolState) -> Result<Pool, BuildError> {
618 if state.balances.len() != 3 {
619 return Err(BuildError::WrongCoinCount {
620 variant: state.variant,
621 expected: 3,
622 actual: state.balances.len(),
623 });
624 }
625
626 for (i, &d) in state.token_decimals.iter().enumerate() {
627 if d > 18 {
628 return Err(BuildError::DecimalsTooLarge { index: i, decimals: d, max: 18 });
629 }
630 }
631
632 let mid_fee = require!(state, mid_fee);
633 let out_fee = require!(state, out_fee);
634 let fee_gamma = require!(state, fee_gamma);
635 let d = require!(state, d);
636 let gamma = require!(state, gamma);
637 let ann = state.amp;
638
639 let price_scale_vec = state
640 .price_scale
641 .as_ref()
642 .ok_or(BuildError::MissingField { variant: state.variant, field: "price_scale" })?;
643 if price_scale_vec.len() != 2 {
644 return Err(BuildError::PriceScaleWrongLen { expected: 2, actual: price_scale_vec.len() });
645 }
646 let price_scale: [U256; 2] = [price_scale_vec[0], price_scale_vec[1]];
647
648 let default_precs = compute_crypto_precisions(&state.token_decimals);
649 let precisions = state
650 .precisions
651 .as_deref()
652 .unwrap_or(&default_precs);
653 let balances: [U256; 3] = [state.balances[0], state.balances[1], state.balances[2]];
654 let prec_arr: [U256; 3] = [precisions[0], precisions[1], precisions[2]];
655
656 match state.variant {
657 CurveVariant::TriCryptoV1 => Ok(Pool::TriCryptoV1 {
658 balances,
659 precisions: prec_arr,
660 price_scale,
661 d,
662 ann,
663 gamma,
664 mid_fee,
665 out_fee,
666 fee_gamma,
667 }),
668 CurveVariant::TriCryptoNG => Ok(Pool::TriCryptoNG {
669 balances,
670 precisions: prec_arr,
671 price_scale,
672 d,
673 ann,
674 gamma,
675 mid_fee,
676 out_fee,
677 fee_gamma,
678 }),
679 #[expect(
680 clippy::unreachable,
681 reason = "build_pool dispatches only the TriCrypto variants here"
682 )]
683 CurveVariant::StableSwapV0 |
684 CurveVariant::StableSwapV1 |
685 CurveVariant::StableSwapV2 |
686 CurveVariant::StableSwapSTETH |
687 CurveVariant::StableSwapALend |
688 CurveVariant::StableSwapNG |
689 CurveVariant::StableSwapMeta |
690 CurveVariant::TwoCryptoV1 |
691 CurveVariant::TwoCryptoNG |
692 CurveVariant::TwoCryptoStable => {
693 unreachable!("build_tricrypto called for non-tricrypto variant")
694 }
695 }
696}
697
698#[cfg(test)]
699mod tests {
700 use super::*;
701
702 #[test]
703 fn interpolate_a_no_ramp() {
704 let a = U256::from(40_000u64);
706 let result = interpolate_a(a, a, 1000, 2000, 1500);
707 assert_eq!(result, a);
708 }
709
710 #[test]
711 fn interpolate_a_ramp_complete() {
712 let result = interpolate_a(U256::from(20_000u64), U256::from(40_000u64), 1000, 2000, 3000);
714 assert_eq!(result, U256::from(40_000u64));
715 }
716
717 #[test]
718 fn interpolate_a_ramp_exactly_at_end() {
719 let result = interpolate_a(U256::from(20_000u64), U256::from(40_000u64), 1000, 2000, 2000);
720 assert_eq!(result, U256::from(40_000u64));
721 }
722
723 #[test]
724 fn interpolate_a_ramp_up_midpoint() {
725 let result = interpolate_a(U256::from(20_000u64), U256::from(40_000u64), 1000, 2000, 1500);
728 assert_eq!(result, U256::from(30_000u64));
729 }
730
731 #[test]
732 fn interpolate_a_ramp_down_midpoint() {
733 let result = interpolate_a(U256::from(40_000u64), U256::from(20_000u64), 1000, 2000, 1500);
736 assert_eq!(result, U256::from(30_000u64));
737 }
738
739 #[test]
740 fn interpolate_a_ramp_up_quarter() {
741 let result = interpolate_a(U256::from(10_000u64), U256::from(50_000u64), 0, 1000, 250);
744 assert_eq!(result, U256::from(20_000u64));
745 }
746
747 #[test]
748 fn interpolate_a_ramp_at_start() {
749 let result = interpolate_a(U256::from(20_000u64), U256::from(40_000u64), 1000, 2000, 1000);
751 assert_eq!(result, U256::from(20_000u64));
752 }
753
754 #[test]
755 fn interpolate_a_integer_division_truncation() {
756 let result = interpolate_a(U256::from(10_000u64), U256::from(10_003u64), 0, 1000, 1);
760 assert_eq!(result, U256::from(10_000u64));
761 }
762
763 #[test]
764 fn build_stableswap_v0_basic() {
765 let state = RawPoolState {
766 variant: CurveVariant::StableSwapV0,
767 balances: vec![
768 U256::from(1_000_000_000_000_000_000_000u128), U256::from(1_000_000_000u128), U256::from(1_000_000_000u128), U256::from(1_000_000_000_000_000_000_000u128), ],
773 token_decimals: vec![18, 6, 6, 18],
774 amp: U256::from(200u64), fee: Some(U256::from(4_000_000u64)),
776 ..Default::default()
777 };
778
779 let pool = build_pool(&state).unwrap();
780 let dy = pool.get_amount_out(0, 1, U256::from(1_000_000_000_000_000_000u128));
782 assert!(dy.is_some());
783 }
784
785 #[test]
786 fn build_stableswap_v2_rates_18_6() {
787 let state = RawPoolState {
788 variant: CurveVariant::StableSwapV2,
789 balances: vec![
790 U256::from(1_000_000_000_000_000_000_000u128),
791 U256::from(1_000_000_000u128),
792 ],
793 token_decimals: vec![18, 6],
794 amp: U256::from(40_000u64), fee: Some(U256::from(4_000_000u64)),
796 ..Default::default()
797 };
798
799 let pool = build_pool(&state).unwrap();
800
801 let Pool::StableSwapV2 { rates, .. } = &pool else {
803 panic!("wrong variant");
804 };
805 assert_eq!(rates[0], U256::from(10u64).pow(U256::from(18u64)));
806 assert_eq!(rates[1], U256::from(10u64).pow(U256::from(30u64)));
807 }
808
809 #[test]
810 fn build_stableswap_ng_with_dynamic_rates() {
811 let oracle_rate = U256::from(1_050_000_000_000_000_000u128); let state = RawPoolState {
813 variant: CurveVariant::StableSwapNG,
814 balances: vec![
815 U256::from(1_000_000_000_000_000_000_000u128),
816 U256::from(1_000_000_000_000_000_000_000u128),
817 ],
818 token_decimals: vec![18, 18],
819 amp: U256::from(150_000u64),
820 fee: Some(U256::from(4_000_000u64)),
821 offpeg_fee_multiplier: Some(U256::from(20_000_000_000u128)),
822 dynamic_rates: Some(vec![
823 None, Some(oracle_rate), ]),
826 ..Default::default()
827 };
828
829 let pool = build_pool(&state).unwrap();
830 let Pool::StableSwapNG { rates, .. } = &pool else {
831 panic!("wrong variant");
832 };
833 assert_eq!(rates[0], U256::from(10u64).pow(U256::from(18u64)));
834 assert_eq!(rates[1], oracle_rate);
835 }
836
837 #[test]
838 fn build_stableswap_alend_precision_mul() {
839 let state = RawPoolState {
840 variant: CurveVariant::StableSwapALend,
841 balances: vec![
842 U256::from(1_000_000_000_000_000_000_000u128),
843 U256::from(1_000_000_000_000_000_000_000u128),
844 ],
845 token_decimals: vec![18, 18],
846 amp: U256::from(10_000u64), fee: Some(U256::from(4_000_000u64)),
848 offpeg_fee_multiplier: Some(U256::from(20_000_000_000u128)),
849 ..Default::default()
850 };
851
852 let pool = build_pool(&state).unwrap();
853 let Pool::StableSwapALend { precision_mul, .. } = &pool else {
854 panic!("wrong variant");
855 };
856 assert_eq!(precision_mul[0], U256::from(1u64));
858 assert_eq!(precision_mul[1], U256::from(1u64));
859 }
860
861 #[test]
862 fn build_stableswap_meta_virtual_price_rate() {
863 let virtual_price = U256::from(1_020_000_000_000_000_000u128); let state = RawPoolState {
865 variant: CurveVariant::StableSwapMeta,
866 balances: vec![
867 U256::from(1_000_000_000u128), U256::from(1_000_000_000_000_000_000_000u128), ],
870 token_decimals: vec![2, 18],
871 amp: U256::from(150_000u64),
872 fee: Some(U256::from(4_000_000u64)),
873 dynamic_rates: Some(vec![
874 None, Some(virtual_price), ]),
877 ..Default::default()
878 };
879
880 let pool = build_pool(&state).unwrap();
881 let Pool::StableSwapMeta { rates, .. } = &pool else {
882 panic!("wrong variant");
883 };
884 assert_eq!(rates[0], U256::from(10u64).pow(U256::from(34u64)));
885 assert_eq!(rates[1], virtual_price);
886 }
887
888 #[test]
889 fn build_twocrypto_ng_basic() {
890 let state = RawPoolState {
891 variant: CurveVariant::TwoCryptoNG,
892 balances: vec![
893 U256::from(1_000_000_000_000_000_000_000u128),
894 U256::from(1_000_000_000_000_000_000_000u128),
895 ],
896 token_decimals: vec![18, 18],
897 amp: U256::from(540_000u64 * 10_000u64), mid_fee: Some(U256::from(3_000_000u64)),
899 out_fee: Some(U256::from(30_000_000u64)),
900 fee_gamma: Some(U256::from(500_000_000_000_000u128)),
901 d: Some(U256::from(2_000_000_000_000_000_000_000u128)),
902 gamma: Some(U256::from(10_000_000_000_000u128)),
903 price_scale: Some(vec![U256::from(1_000_000_000_000_000_000u128)]),
904 ..Default::default()
905 };
906
907 let pool = build_pool(&state).unwrap();
908 let Pool::TwoCryptoNG { precisions, ann, .. } = &pool else {
909 panic!("wrong variant");
910 };
911 assert_eq!(precisions[0], U256::from(1u64)); assert_eq!(precisions[1], U256::from(1u64));
913 assert_eq!(*ann, state.amp);
914 }
915
916 #[test]
917 fn build_twocrypto_stable_no_gamma() {
918 let state = RawPoolState {
919 variant: CurveVariant::TwoCryptoStable,
920 balances: vec![U256::from(1_000_000_000u128), U256::from(1_000_000_000u128)],
921 token_decimals: vec![6, 6],
922 amp: U256::from(540_000u64 * 10_000u64),
923 mid_fee: Some(U256::from(3_000_000u64)),
924 out_fee: Some(U256::from(30_000_000u64)),
925 fee_gamma: Some(U256::from(500_000_000_000_000u128)),
926 d: Some(U256::from(2_000_000_000u128)),
927 price_scale: Some(vec![U256::from(1_000_000_000_000_000_000u128)]),
929 ..Default::default()
930 };
931
932 let pool = build_pool(&state).unwrap();
933 let Pool::TwoCryptoStable { precisions, .. } = &pool else {
934 panic!("wrong variant");
935 };
936 assert_eq!(precisions[0], U256::from(10u64).pow(U256::from(12u64)));
938 }
939
940 #[test]
941 fn build_tricrypto_ng_basic() {
942 let state = RawPoolState {
943 variant: CurveVariant::TriCryptoNG,
944 balances: vec![
945 U256::from(1_000_000_000u128), U256::from(50_000_000u128), U256::from(500_000_000_000_000_000_000u128), ],
949 token_decimals: vec![6, 8, 18],
950 amp: U256::from(1_707_629u64 * 10_000u64),
951 mid_fee: Some(U256::from(3_000_000u64)),
952 out_fee: Some(U256::from(30_000_000u64)),
953 fee_gamma: Some(U256::from(500_000_000_000_000u128)),
954 d: Some(U256::from(3_000_000_000_000_000_000_000u128)),
955 gamma: Some(U256::from(11_809_167_828_997u128)),
956 price_scale: Some(vec![
957 U256::from(60_000_000_000_000_000_000_000u128), U256::from(3_000_000_000_000_000_000_000u128), ]),
960 ..Default::default()
961 };
962
963 let pool = build_pool(&state).unwrap();
964 let Pool::TriCryptoNG { precisions, price_scale, .. } = &pool else {
965 panic!("wrong variant");
966 };
967 assert_eq!(precisions[0], U256::from(10u64).pow(U256::from(12u64))); assert_eq!(precisions[1], U256::from(10u64).pow(U256::from(10u64))); assert_eq!(precisions[2], U256::from(1u64)); assert_eq!(price_scale.len(), 2);
971 }
972
973 #[test]
974 fn build_missing_fee_returns_error() {
975 let state = RawPoolState {
976 variant: CurveVariant::StableSwapV2,
977 balances: vec![U256::from(1u64), U256::from(1u64)],
978 token_decimals: vec![18, 18],
979 amp: U256::from(40_000u64),
980 ..Default::default()
982 };
983
984 let err = match build_pool(&state) {
985 Err(e) => e,
986 Ok(_) => panic!("expected error"),
987 };
988 assert!(matches!(err, BuildError::MissingField { field: "fee", .. }));
989 }
990
991 #[test]
992 fn build_decimals_mismatch_returns_error() {
993 let state = RawPoolState {
994 variant: CurveVariant::StableSwapV2,
995 balances: vec![U256::from(1u64), U256::from(1u64)],
996 token_decimals: vec![18], amp: U256::from(40_000u64),
998 fee: Some(U256::from(4_000_000u64)),
999 ..Default::default()
1000 };
1001
1002 let err = match build_pool(&state) {
1003 Err(e) => e,
1004 Ok(_) => panic!("expected error"),
1005 };
1006 assert!(matches!(err, BuildError::DecimalsMismatch { .. }));
1007 }
1008
1009 #[test]
1010 fn build_twocrypto_wrong_coin_count() {
1011 let state = RawPoolState {
1012 variant: CurveVariant::TwoCryptoNG,
1013 balances: vec![U256::from(1u64), U256::from(1u64), U256::from(1u64)],
1014 token_decimals: vec![18, 18, 18],
1015 amp: U256::from(1u64),
1016 mid_fee: Some(U256::from(1u64)),
1017 out_fee: Some(U256::from(1u64)),
1018 fee_gamma: Some(U256::from(1u64)),
1019 d: Some(U256::from(1u64)),
1020 gamma: Some(U256::from(1u64)),
1021 price_scale: Some(vec![U256::from(1u64)]),
1022 ..Default::default()
1023 };
1024
1025 let err = match build_pool(&state) {
1026 Err(e) => e,
1027 Ok(_) => panic!("expected error"),
1028 };
1029 assert!(matches!(err, BuildError::WrongCoinCount { expected: 2, actual: 3, .. }));
1030 }
1031
1032 #[test]
1033 fn build_tricrypto_wrong_price_scale_len() {
1034 let state = RawPoolState {
1035 variant: CurveVariant::TriCryptoNG,
1036 balances: vec![U256::from(1u64), U256::from(1u64), U256::from(1u64)],
1037 token_decimals: vec![6, 8, 18],
1038 amp: U256::from(1u64),
1039 mid_fee: Some(U256::from(1u64)),
1040 out_fee: Some(U256::from(1u64)),
1041 fee_gamma: Some(U256::from(1u64)),
1042 d: Some(U256::from(1u64)),
1043 gamma: Some(U256::from(1u64)),
1044 price_scale: Some(vec![U256::from(1u64)]), ..Default::default()
1046 };
1047
1048 let err = match build_pool(&state) {
1049 Err(e) => e,
1050 Ok(_) => panic!("expected error"),
1051 };
1052 assert!(matches!(err, BuildError::PriceScaleWrongLen { expected: 2, actual: 1 }));
1053 }
1054
1055 #[test]
1056 fn build_ng_without_offpeg_defaults_to_fee_denominator() {
1057 let state = RawPoolState {
1059 variant: CurveVariant::StableSwapNG,
1060 balances: vec![U256::from(1u64), U256::from(1u64)],
1061 token_decimals: vec![18, 18],
1062 amp: U256::from(40_000u64),
1063 fee: Some(U256::from(4_000_000u64)),
1064 ..Default::default()
1066 };
1067
1068 let pool = build_pool(&state).expect("should succeed with defaulted offpeg");
1069 assert_eq!(pool.offpeg_fee_multiplier(), Some(U256::from(10_000_000_000u64)));
1071 }
1072
1073 #[test]
1074 fn build_ng_crvusd_sdai_matches_on_chain() {
1075 let state = RawPoolState {
1078 variant: CurveVariant::StableSwapNG,
1079 balances: vec![
1080 "3219009600398261994"
1081 .parse::<U256>()
1082 .expect("balance 0"),
1083 "311156701443769568"
1084 .parse::<U256>()
1085 .expect("balance 1"),
1086 ],
1087 token_decimals: vec![18, 18],
1088 amp: U256::from(150_000u64),
1089 fee: Some(U256::from(1_000_000u64)),
1090 dynamic_rates: Some(vec![
1092 Some(
1093 "1000000000000000000"
1094 .parse::<U256>()
1095 .expect("rate 0"),
1096 ),
1097 Some(
1098 "1173627645818786870"
1099 .parse::<U256>()
1100 .expect("rate 1"),
1101 ),
1102 ]),
1103 ..Default::default()
1104 };
1105
1106 let pool = build_pool(&state).expect("should build with defaulted offpeg");
1107 let dy = pool
1108 .get_amount_out(0, 1, U256::from(3_219_009_600_398_261u64))
1109 .expect("swap should succeed");
1110
1111 let expected = U256::from(2_720_818_166_217_034u64);
1113 let diff = if dy > expected { dy - expected } else { expected - dy };
1114 assert!(diff <= U256::from(1u64), "mismatch: got {dy}, expected {expected}, diff {diff}");
1115 }
1116
1117 #[test]
1118 fn build_meta_without_virtual_price_fails() {
1119 let state = RawPoolState {
1122 variant: CurveVariant::StableSwapMeta,
1123 balances: vec![
1124 U256::from(1_000_000_000u128),
1125 U256::from(1_000_000_000_000_000_000_000u128),
1126 ],
1127 token_decimals: vec![2, 18],
1128 amp: U256::from(150_000u64),
1129 fee: Some(U256::from(4_000_000u64)),
1130 ..Default::default()
1132 };
1133
1134 let err = match build_pool(&state) {
1135 Err(e) => e,
1136 Ok(_) => panic!("expected MetaMissingVirtualPrice error"),
1137 };
1138 assert!(matches!(err, BuildError::MetaMissingVirtualPrice));
1139 }
1140
1141 #[test]
1142 fn build_meta_with_partial_dynamic_rates_missing_vp_fails() {
1143 let state = RawPoolState {
1145 variant: CurveVariant::StableSwapMeta,
1146 balances: vec![
1147 U256::from(1_000_000_000u128),
1148 U256::from(1_000_000_000_000_000_000_000u128),
1149 ],
1150 token_decimals: vec![2, 18],
1151 amp: U256::from(150_000u64),
1152 fee: Some(U256::from(4_000_000u64)),
1153 dynamic_rates: Some(vec![None, None]), ..Default::default()
1155 };
1156
1157 let err = match build_pool(&state) {
1158 Err(e) => e,
1159 Ok(_) => panic!("expected MetaMissingVirtualPrice error"),
1160 };
1161 assert!(matches!(err, BuildError::MetaMissingVirtualPrice));
1162 }
1163
1164 #[test]
1165 fn rates_match_fuzz_registry_18_dec() {
1166 let rates = super::compute_stableswap_rates(&[18], &None);
1168 assert_eq!(rates[0], U256::from(10u64).pow(U256::from(18u64)));
1169 }
1170
1171 #[test]
1172 fn rates_match_fuzz_registry_6_dec() {
1173 let rates = super::compute_stableswap_rates(&[6], &None);
1175 assert_eq!(rates[0], U256::from(10u64).pow(U256::from(30u64)));
1176 }
1177
1178 #[test]
1179 fn rates_match_fuzz_registry_8_dec() {
1180 let rates = super::compute_stableswap_rates(&[8], &None);
1182 assert_eq!(rates[0], U256::from(10u64).pow(U256::from(28u64)));
1183 }
1184
1185 #[test]
1186 fn rates_match_fuzz_registry_2_dec() {
1187 let rates = super::compute_stableswap_rates(&[2], &None);
1189 assert_eq!(rates[0], U256::from(10u64).pow(U256::from(34u64)));
1190 }
1191
1192 #[test]
1193 fn precisions_match_fuzz_registry() {
1194 let precs = super::compute_crypto_precisions(&[6, 8, 18]);
1196 assert_eq!(precs[0], U256::from(10u64).pow(U256::from(12u64))); assert_eq!(precs[1], U256::from(10u64).pow(U256::from(10u64))); assert_eq!(precs[2], U256::from(1u64)); }
1200
1201 #[test]
1202 fn precision_mul_matches_fuzz_registry() {
1203 let pm = super::compute_crypto_precisions(&[18, 6]);
1205 assert_eq!(pm[0], U256::from(1u64));
1206 assert_eq!(pm[1], U256::from(10u64).pow(U256::from(12u64)));
1207 }
1208
1209 #[test]
1210 fn build_all_11_variants_succeed() {
1211 let stableswap_base = |variant: CurveVariant| -> RawPoolState {
1213 RawPoolState {
1214 variant,
1215 balances: vec![U256::from(1_000_000_000_000_000_000u128); 2],
1216 token_decimals: vec![18, 18],
1217 amp: U256::from(40_000u64),
1218 fee: Some(U256::from(4_000_000u64)),
1219 ..Default::default()
1220 }
1221 };
1222
1223 for v in
1225 [CurveVariant::StableSwapV0, CurveVariant::StableSwapV1, CurveVariant::StableSwapV2]
1226 {
1227 assert!(build_pool(&stableswap_base(v)).is_ok(), "failed for {v}");
1228 }
1229
1230 let mut meta = stableswap_base(CurveVariant::StableSwapMeta);
1232 meta.dynamic_rates = Some(vec![None, Some(U256::from(10u64).pow(U256::from(18u64)))]);
1233 assert!(build_pool(&meta).is_ok(), "failed for StableSwapMeta");
1234
1235 let mut ng = stableswap_base(CurveVariant::StableSwapNG);
1237 ng.offpeg_fee_multiplier = Some(U256::from(20_000_000_000u128));
1238 assert!(build_pool(&ng).is_ok(), "failed for StableSwapNG");
1239
1240 let mut alend = stableswap_base(CurveVariant::StableSwapALend);
1242 alend.offpeg_fee_multiplier = Some(U256::from(20_000_000_000u128));
1243 assert!(build_pool(&alend).is_ok(), "failed for StableSwapALend");
1244
1245 let crypto_base = |variant: CurveVariant, n: usize| -> RawPoolState {
1247 RawPoolState {
1248 variant,
1249 balances: vec![U256::from(1_000_000_000_000_000_000u128); n],
1250 token_decimals: vec![18; n],
1251 amp: U256::from(540_000u64 * 10_000u64),
1252 mid_fee: Some(U256::from(3_000_000u64)),
1253 out_fee: Some(U256::from(30_000_000u64)),
1254 fee_gamma: Some(U256::from(500_000_000_000_000u128)),
1255 d: Some(U256::from(2_000_000_000_000_000_000_000u128)),
1256 gamma: Some(U256::from(10_000_000_000_000u128)),
1257 price_scale: Some(if n == 2 {
1258 vec![U256::from(10u64).pow(U256::from(18u64))]
1259 } else {
1260 vec![U256::from(10u64).pow(U256::from(18u64)); n - 1]
1261 }),
1262 eth_variant: Some(true),
1264 ..Default::default()
1265 }
1266 };
1267
1268 for v in [CurveVariant::TwoCryptoV1, CurveVariant::TwoCryptoNG] {
1270 assert!(build_pool(&crypto_base(v, 2)).is_ok(), "failed for {v}");
1271 }
1272
1273 let mut tcs = crypto_base(CurveVariant::TwoCryptoStable, 2);
1275 tcs.gamma = None;
1276 assert!(build_pool(&tcs).is_ok(), "failed for TwoCryptoStable");
1277
1278 for v in [CurveVariant::TriCryptoV1, CurveVariant::TriCryptoNG] {
1280 assert!(build_pool(&crypto_base(v, 3)).is_ok(), "failed for {v}");
1281 }
1282 }
1283
1284 fn u(s: &str) -> U256 {
1295 U256::from_str_radix(s, 10).unwrap()
1296 }
1297
1298 #[test]
1299 fn integration_stableswap_v0_susd() {
1300 let state = RawPoolState {
1302 variant: CurveVariant::StableSwapV0,
1303 balances: vec![
1304 u("1919848022082255699479"),
1305 u("1920322445"),
1306 u("1920171938"),
1307 u("21038816168255729764832232005"),
1308 ],
1309 token_decimals: vec![18, 6, 6, 18],
1310 amp: U256::from(256u64),
1311 fee: Some(U256::from(2_000_000u64)),
1312 ..Default::default()
1313 };
1314 let pool = build_pool(&state).unwrap();
1315 let dy = pool
1316 .get_amount_out(0, 1, u("19198480220822556994"))
1317 .unwrap();
1318 assert_eq!(dy, U256::from(19_009_291u64));
1319 }
1320
1321 #[test]
1322 fn integration_stableswap_v1_3pool() {
1323 let state = RawPoolState {
1325 variant: CurveVariant::StableSwapV1,
1326 balances: vec![
1327 u("45102835177280382580138407"),
1328 u("45853975278310"),
1329 u("72989152672276"),
1330 ],
1331 token_decimals: vec![18, 6, 6],
1332 amp: U256::from(4000u64),
1333 fee: Some(U256::from(1_500_000u64)),
1334 ..Default::default()
1335 };
1336 let pool = build_pool(&state).unwrap();
1337 let dy = pool
1338 .get_amount_out(0, 1, u("451028351772803825801384"))
1339 .unwrap();
1340 assert_eq!(dy, u("450961663745"));
1341 }
1342
1343 #[test]
1344 fn integration_stableswap_v2_frax_usdc() {
1345 let state = RawPoolState {
1347 variant: CurveVariant::StableSwapV2,
1348 balances: vec![u("6722234569994793202271485"), u("714493991383")],
1349 token_decimals: vec![18, 6],
1350 amp: U256::from(150_000u64),
1351 fee: Some(U256::from(1_000_000u64)),
1352 ..Default::default()
1353 };
1354 let pool = build_pool(&state).unwrap();
1355 let dy = pool
1356 .get_amount_out(0, 1, u("67222345699947932022714"))
1357 .unwrap();
1358 assert_eq!(dy, u("66561674655"));
1359 }
1360
1361 #[test]
1362 fn integration_stableswap_alend_aave() {
1363 let state = RawPoolState {
1365 variant: CurveVariant::StableSwapALend,
1366 balances: vec![u("968991099162993551077367"), u("1012448901351"), u("414282246850")],
1367 token_decimals: vec![18, 6, 6],
1368 amp: U256::from(200_000u64),
1369 fee: Some(U256::from(4_000_000u64)),
1370 offpeg_fee_multiplier: Some(u("20000000000")),
1371 ..Default::default()
1372 };
1373 let pool = build_pool(&state).unwrap();
1374 let dy = pool
1375 .get_amount_out(0, 1, u("9689910991629935510773"))
1376 .unwrap();
1377 assert_eq!(dy, u("9686201099"));
1378 }
1379
1380 #[test]
1381 fn integration_stableswap_ng_usde_dai() {
1382 let state = RawPoolState {
1384 variant: CurveVariant::StableSwapNG,
1385 balances: vec![u("124403796536542495997070"), u("95031311223261676260348")],
1386 token_decimals: vec![18, 18],
1387 amp: U256::from(40_000u64),
1388 fee: Some(U256::from(4_000_000u64)),
1389 offpeg_fee_multiplier: Some(u("20000000000")),
1390 dynamic_rates: Some(vec![
1391 Some(u("1000000000000000000")),
1392 Some(u("1000000000000000000")),
1393 ]),
1394 ..Default::default()
1395 };
1396 let pool = build_pool(&state).unwrap();
1397 let dy = pool
1398 .get_amount_out(0, 1, u("1244037965365424959970"))
1399 .unwrap();
1400 assert_eq!(dy, u("1242635841481792448583"));
1401 }
1402
1403 #[test]
1404 fn integration_stableswap_meta_gusd_3crv() {
1405 let state = RawPoolState {
1407 variant: CurveVariant::StableSwapMeta,
1408 balances: vec![u("59814423"), u("1210422553896217308280639")],
1409 token_decimals: vec![2, 18],
1410 amp: U256::from(100_000u64),
1411 fee: Some(U256::from(4_000_000u64)),
1412 dynamic_rates: Some(vec![
1413 None, Some(u("1039823717145796146")), ]),
1416 ..Default::default()
1417 };
1418 let pool = build_pool(&state).unwrap();
1419 let dy = pool
1420 .get_amount_out(0, 1, u("598144"))
1421 .unwrap();
1422 assert_eq!(dy, u("5755338887370979902172"));
1423 }
1424
1425 #[test]
1426 fn integration_twocrypto_v1_crv_eth() {
1427 let state = RawPoolState {
1429 variant: CurveVariant::TwoCryptoV1,
1430 balances: vec![u("33389428640766852909"), u("1538654846121127403001612563")],
1431 token_decimals: vec![18, 18],
1432 amp: U256::from(400_000u64),
1433 d: Some(u("3338917956478824050009")),
1434 gamma: Some(u("145000000000000")),
1435 price_scale: Some(vec![u("52805053500476")]),
1436 mid_fee: Some(U256::from(26_000_000u64)),
1437 out_fee: Some(U256::from(45_000_000u64)),
1438 fee_gamma: Some(u("230000000000000")),
1439 eth_variant: Some(true), ..Default::default()
1441 };
1442 let pool = build_pool(&state).unwrap();
1443 let dy = pool
1444 .get_amount_out(0, 1, u("333894286407668529"))
1445 .unwrap();
1446 assert_eq!(dy, u("15024547954512515366680912"));
1447 }
1448
1449 #[test]
1450 fn integration_twocrypto_ng_crvusd_fxn() {
1451 let state = RawPoolState {
1453 variant: CurveVariant::TwoCryptoNG,
1454 balances: vec![u("575304877931995002539"), u("1286854862507061937737")],
1455 token_decimals: vec![18, 18],
1456 amp: U256::from(400_000u64),
1457 d: Some(u("1309807915207365083258")),
1458 gamma: Some(u("145000000000000")),
1459 price_scale: Some(vec![u("578321621819309618")]),
1460 mid_fee: Some(U256::from(26_000_000u64)),
1461 out_fee: Some(U256::from(45_000_000u64)),
1462 fee_gamma: Some(u("230000000000000")),
1463 ..Default::default()
1464 };
1465 let pool = build_pool(&state).unwrap();
1466 let dy = pool
1467 .get_amount_out(0, 1, u("5753048779319950025"))
1468 .unwrap();
1469 assert_eq!(dy, u("12553693226638615366"));
1470 }
1471
1472 #[test]
1473 fn integration_twocrypto_stable_crvusd_weth() {
1474 let state = RawPoolState {
1476 variant: CurveVariant::TwoCryptoStable,
1477 balances: vec![u("17087755783041929282185464"), u("13675635632110845893058")],
1478 token_decimals: vec![18, 18],
1479 amp: U256::from(25_000u64),
1480 d: Some(u("53892663239303863640675237")),
1481 price_scale: Some(vec![u("2783064941591876143844")]),
1482 mid_fee: Some(U256::from(60_000_000u64)),
1483 out_fee: Some(U256::from(220_000_000u64)),
1484 fee_gamma: Some(u("1395000000000000")),
1485 ..Default::default()
1486 };
1487 let pool = build_pool(&state).unwrap();
1488 let dy = pool
1489 .get_amount_out(0, 1, u("170877557830419292821854"))
1490 .unwrap();
1491 assert_eq!(dy, u("77522288630419592645"));
1492 }
1493
1494 #[test]
1495 fn integration_tricrypto_v1_usdt_wbtc_weth() {
1496 let state = RawPoolState {
1498 variant: CurveVariant::TriCryptoV1,
1499 balances: vec![u("3687737692530"), u("5185841754"), u("1696614171366863858308")],
1500 token_decimals: vec![6, 8, 18],
1501 amp: U256::from(1_707_629u64),
1502 d: Some(u("11006845200255249518958282")),
1503 gamma: Some(u("11809167828997")),
1504 price_scale: Some(vec![u("70578404679338064954709"), u("2156666095129214805267")]),
1505 mid_fee: Some(U256::from(3_000_000u64)),
1506 out_fee: Some(U256::from(30_000_000u64)),
1507 fee_gamma: Some(u("500000000000000")),
1508 ..Default::default()
1509 };
1510 let pool = build_pool(&state).unwrap();
1511 let dy = pool
1512 .get_amount_out(0, 1, u("36877376925"))
1513 .unwrap();
1514 assert_eq!(dy, U256::from(51_646_866u64));
1515 }
1516
1517 #[test]
1518 fn integration_tricrypto_ng_usdc_wbtc_weth() {
1519 let state = RawPoolState {
1521 variant: CurveVariant::TriCryptoNG,
1522 balances: vec![u("3323859056394"), u("4735137544"), u("1544027711277257449902")],
1523 token_decimals: vec![6, 8, 18],
1524 amp: U256::from(1_707_629u64),
1525 d: Some(u("10010654847128420517547506")),
1526 gamma: Some(u("11809167828997")),
1527 price_scale: Some(vec![u("70750968814053384159761"), u("2161000205852311064272")]),
1528 mid_fee: Some(U256::from(3_000_000u64)),
1529 out_fee: Some(U256::from(30_000_000u64)),
1530 fee_gamma: Some(u("500000000000000")),
1531 ..Default::default()
1532 };
1533 let pool = build_pool(&state).unwrap();
1534 let dy = pool
1535 .get_amount_out(0, 1, u("33238590563"))
1536 .unwrap();
1537 assert_eq!(dy, U256::from(46_932_317u64));
1538 }
1539}