Skip to main content

tycho_simulation/evm/protocol/curve/adapter/
build.rs

1//! Construct `crate::evm::protocol::curve::math::Pool` from raw on-chain state.
2//!
3//! This module bridges the gap between raw on-chain data (balances, decimals,
4//! storage values) and the typed `Pool` enum that curve-math needs for swap
5//! computation.
6//!
7//! # Usage
8//!
9//! ```rust
10//! use curve_adapter::{CurveVariant, RawPoolState, build_pool};
11//! use alloy_primitives::U256;
12//!
13//! let state = RawPoolState {
14//!     variant: CurveVariant::StableSwapV2,
15//!     balances: vec![
16//!         U256::from(1_000_000_000_000_000_000_000u128),
17//!         U256::from(1_000_000_000_000u128),
18//!     ],
19//!     token_decimals: vec![18, 6],
20//!     amp: U256::from(40_000u64), // A=400 * A_PRECISION=100
21//!     fee: Some(U256::from(4_000_000u64)),
22//!     ..Default::default()
23//! };
24//!
25//! let pool = build_pool(&state).unwrap();
26//! let dy = pool.get_amount_out(0, 1, U256::from(1_000_000_000_000_000_000u128));
27//! ```
28
29use alloy_primitives::U256;
30
31use crate::evm::protocol::curve::{adapter::CurveVariant, math::Pool};
32
33/// Errors from [`build_pool`].
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum BuildError {
36    /// A required field is missing for this variant.
37    MissingField { variant: CurveVariant, field: &'static str },
38    /// The number of balances doesn't match the expected coin count.
39    WrongCoinCount { variant: CurveVariant, expected: usize, actual: usize },
40    /// Token decimals length doesn't match balances length.
41    DecimalsMismatch { balances_len: usize, decimals_len: usize },
42    /// Token decimals exceed the maximum (18 for CryptoSwap, 36 for StableSwap).
43    DecimalsTooLarge { index: usize, decimals: u8, max: u8 },
44    /// Dynamic rates length doesn't match balances length.
45    DynamicRatesMismatch { balances_len: usize, rates_len: usize },
46    /// Price scale has wrong number of elements.
47    PriceScaleWrongLen { expected: usize, actual: usize },
48    /// StableSwapMeta requires `dynamic_rates` with an explicit rate for
49    /// the base pool LP token (last coin). Without it, rates[N-1] defaults
50    /// to `10^(36-decimals)` which is incorrect — it must be
51    /// `base_pool.get_virtual_price()`.
52    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/// Raw on-chain pool state, as collected by a transport (RPC, Substreams, etc.).
89///
90/// The consumer fills in the fields relevant to the pool's [`CurveVariant`],
91/// then calls [`build_pool`] to get a `crate::evm::protocol::curve::math::Pool` ready for swap
92/// computation.
93#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
94pub struct RawPoolState {
95    /// Which Curve variant this pool is.
96    pub variant: CurveVariant,
97
98    /// Admin share of the swap fee, scaled by 1e10. Required for StableSwap execution state.
99    #[serde(default)]
100    pub admin_fee: Option<U256>,
101
102    /// Token balances in native token units (wei). **Updates every block.**
103    ///
104    /// Length determines coin count (2, 3, or 4+).
105    ///
106    /// # Gotchas
107    ///
108    /// **StableSwapNG:** `balances(i)` on-chain returns `balanceOf(pool) - admin_balances[i]`,
109    /// excluding uncollected admin fees. An indexer tracking ERC20 Transfer events sees
110    /// `balanceOf` changes, not `balances()`. The difference is small but causes wei-level
111    /// mismatches. Use the `balances()` getter, not `balanceOf`.
112    ///
113    /// **Rebase tokens (e.g. stETH):** balances change without Transfer events — the token
114    /// rebases in-place. Requires calling `balanceOf(pool)` on the rebase token each block.
115    pub balances: Vec<U256>,
116
117    /// Token decimals for each coin (e.g. `[18, 6]` for ETH/USDC).
118    /// Must have the same length as `balances`.
119    pub token_decimals: Vec<u8>,
120
121    /// Amplification parameter — already interpolated for the target block.
122    /// **Semi-static:** only changes during A ramping (rare admin events, days apart).
123    ///
124    /// This value must match what the on-chain `_A()` internal function returns
125    /// at the target block's timestamp. It includes the variant's precision
126    /// scaling (A_PRECISION=100 for StableSwap V2+, A_MULTIPLIER=10000 for
127    /// CryptoSwap, 1 for V0/V1).
128    ///
129    /// # How to obtain this value
130    ///
131    /// **RPC consumer:**
132    /// Call the pool's `A()` view function at the target block.
133    /// Returns the already-interpolated value in a single RPC call.
134    /// ```text
135    /// let amp = pool_contract.A().block(block_number).call().await?;
136    /// ```
137    /// **Warning:** for all A_PRECISION=100 variants (V2, Meta, NG, ALend),
138    /// `A()` returns `initial_A / A_PRECISION` via integer division, losing
139    /// the remainder:
140    /// ```text
141    /// initial_A = 79258
142    /// A() = 79258 / 100 = 792      (truncated)
143    /// A() * 100 = 79200 ≠ 79258    (lost 58)
144    /// ```
145    /// For exact precision, read `initial_A()` directly when no ramping
146    /// (`initial_A == future_A`), or use [`interpolate_a`] during ramps.
147    ///
148    /// **Substreams / storage-based consumer:**
149    /// Read `initial_A`, `future_A`, `initial_A_time`, `future_A_time` from
150    /// contract storage, then interpolate for the current block's timestamp:
151    /// ```text
152    /// let amp = curve_adapter::interpolate_a(
153    ///     initial_a, future_a,
154    ///     initial_a_time, future_a_time,
155    ///     block_timestamp,
156    /// );
157    /// ```
158    /// For V0/V1 pools that store a single `A` value (no ramping),
159    /// pass that value directly.
160    ///
161    /// **Caution with factory deploy events:** `PlainPoolDeployed` and
162    /// `MetaPoolDeployed` events emit A as the user-provided value (e.g. 400),
163    /// NOT the raw on-chain value (e.g. 40000). Multiply by A_PRECISION
164    /// (100 for V2/NG/Meta/ALend) before passing here.
165    pub amp: U256,
166
167    /// StableSwap fee. **Static** (set at pool creation).
168    /// Required for all StableSwap variants.
169    pub fee: Option<U256>,
170
171    /// CryptoSwap mid fee. **Static.** Required for all CryptoSwap variants.
172    pub mid_fee: Option<U256>,
173
174    /// CryptoSwap out fee. **Static.** Required for all CryptoSwap variants.
175    pub out_fee: Option<U256>,
176
177    /// CryptoSwap fee gamma. **Static.** Required for all CryptoSwap variants.
178    pub fee_gamma: Option<U256>,
179
180    /// Dynamic fee multiplier. **Static.** Required for StableSwapNG and StableSwapALend.
181    pub offpeg_fee_multiplier: Option<U256>,
182
183    /// Price scale(s). **Updates every block.**
184    /// TwoCrypto: 1 element, TriCrypto: 2 elements.
185    /// Required for all CryptoSwap variants.
186    pub price_scale: Option<Vec<U256>>,
187
188    /// Pool invariant D. **Updates every block.** Required for all CryptoSwap variants.
189    pub d: Option<U256>,
190
191    /// Gamma parameter. **Semi-static** (only changes during admin ramp).
192    /// Required for TwoCryptoV1, TwoCryptoNG, TriCryptoV1, TriCryptoNG.
193    /// NOT required for TwoCryptoStable (gamma is ignored).
194    pub gamma: Option<U256>,
195
196    /// Per-token dynamic rates for StableSwap variants. **Depends on token type.**
197    ///
198    /// If `None`, rates are computed from `token_decimals` as `10^(36 - decimals)`.
199    /// This is correct for v6+ crvUSD factory pools (balances variant) which
200    /// use static decimal-based rates and have no `stored_rates()` getter.
201    ///
202    /// If `Some`, must have the same length as `balances`. Each element:
203    /// - `Some(rate)` — use this dynamic rate (oracle, ERC4626, etc.)
204    /// - `None` — compute from decimals as `10^(36 - decimals)`
205    ///
206    /// # When to provide dynamic rates
207    ///
208    /// **StableSwapNG with oracle tokens:** Call `stored_rates()` on the pool
209    /// contract each block. Plain tokens return static rates, but ERC4626/oracle
210    /// tokens return rates that change per-block.
211    ///
212    /// **MetaPools:** `rates[last]` must be `base_pool.get_virtual_price()`.
213    /// To find the base pool address: try `pool.base_pool()` first. MetaPool
214    /// Factory proxy pools lack this getter — use `factory.get_base_pool(pool)`
215    /// instead. Do not assume the base pool is 3pool; BTC meta pools use sBTC.
216    ///
217    /// # Gotchas
218    ///
219    /// **Fee-on-transfer tokens:** actual received amount differs from the
220    /// transfer parameter. Curve pools generally do not support these tokens,
221    /// but if encountered, balances will be incorrect.
222    ///
223    /// **Tokens with 0 decimals:** rate becomes `10^36` — valid but rounding
224    /// impact is outsized. Every wei of such a token is worth `10^36` in
225    /// normalized space.
226    pub dynamic_rates: Option<Vec<Option<U256>>>,
227
228    /// On-chain precisions for CryptoSwap variants. **Immutable.**
229    ///
230    /// If `Some`, used directly instead of computing from `token_decimals`.
231    /// Read from the pool contract's `precisions()` getter.
232    ///
233    /// This is important because some tokens report incorrect `decimals()`
234    /// (e.g. Spectra PT tokens), and the factory computes the correct
235    /// precisions at deployment time.
236    ///
237    /// If `None`, precisions are computed as `10^(18 - decimals)`.
238    pub precisions: Option<Vec<U256>>,
239
240    /// Selects the deployed Vyper flavour for **TwoCryptoV1 only**. **Immutable.**
241    ///
242    /// Legacy 2-coin CryptoSwap V1 pools ship in two flavours whose Newton `get_y` solver differs
243    /// by a single `mul2` integer-division grouping (see
244    /// [`crate::evm::protocol::curve::math::core::twocrypto_v1`]). `Some(true)` selects the ETH
245    /// pool grouping (all factory/proxy and WETH-paired legacy pools); `Some(false)` selects the
246    /// non-ETH legacy direct-deploy grouping.
247    ///
248    /// Required for `TwoCryptoV1` — [`build_pool`] returns [`BuildError::MissingField`] if it is
249    /// `None`. Ignored for every other variant. Obtain it via
250    /// [`detect_eth_variant`](crate::evm::protocol::curve::adapter::detect_eth_variant).
251    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
277/// Interpolate the amplification parameter for a given block timestamp.
278///
279/// This is a 1:1 port of the Vyper `_A()` internal function from Curve
280/// StableSwap and CryptoSwap contracts. The formula is identical across all
281/// Curve variants that support A ramping (V2, Meta, NG, ALend, all CryptoSwap).
282///
283/// V0/V1 pools do not support ramping — they store a single `A` value.
284/// For those, pass `A` directly to [`RawPoolState::amp`] without calling this.
285///
286/// CryptoSwap contracts store `initial_A_gamma` and `future_A_gamma` as packed
287/// values (A and gamma in a single uint256). The caller must unpack the A
288/// component before passing it here.
289///
290/// # Arguments
291///
292/// * `initial_a` — raw start value from storage (includes A_PRECISION/A_MULTIPLIER)
293/// * `future_a` — raw end value from storage (includes A_PRECISION/A_MULTIPLIER)
294/// * `initial_a_time` — ramp start timestamp (seconds)
295/// * `future_a_time` — ramp end timestamp (seconds)
296/// * `block_timestamp` — target block's timestamp (seconds)
297///
298/// # Panics
299///
300/// Panics if `block_timestamp < initial_a_time` (block is before ramp start).
301/// This should never happen with valid on-chain data.
302pub 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    // block_timestamp < initial_a_time should never happen with valid on-chain data.
314    // The Vyper code does not guard against this either (would underflow and revert).
315    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
325/// Compute StableSwap rates from token decimals and optional dynamic rates.
326///
327/// For each token:
328/// - If a dynamic rate is provided, use it directly.
329/// - Otherwise, compute as `10^(36 - decimals)`.
330///
331/// This matches the on-chain `RATE_MULTIPLIER` / `rates` / `PRECISION * RATES`
332/// pattern used across all StableSwap variants.
333fn 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            // Check if there's a dynamic rate for this token
342            if let Some(ref rates) = dynamic_rates {
343                if let Some(Some(rate)) = rates.get(i) {
344                    return *rate;
345                }
346            }
347            // Default: 10^(36 - decimals)
348            U256::from(10u64).pow(U256::from(36 - decimals as u32))
349        })
350        .collect()
351}
352
353/// Compute CryptoSwap precisions from token decimals.
354///
355/// For each token: `10^(18 - decimals)`.
356///
357/// This matches the on-chain `precisions` storage variable in all CryptoSwap
358/// contracts.
359fn 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
366/// Helper to extract a required Option field or return a BuildError.
367macro_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
378/// Construct a `crate::evm::protocol::curve::math::Pool` from raw on-chain state.
379///
380/// This function:
381/// 1. Validates that all required fields are present for the given variant.
382/// 2. Computes rates/precisions from `token_decimals` (with dynamic rate overrides).
383/// 3. Constructs the appropriate `Pool` enum variant.
384///
385/// The returned `Pool` is ready for `get_amount_out()` / `get_amount_in()` calls.
386pub fn build_pool(state: &RawPoolState) -> Result<Pool, BuildError> {
387    // Common validation
388    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    // Validate dynamic_rates length if provided
396    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
420/// Build StableSwapV0, V1, V2, or Meta — all share the same field layout:
421/// `{ balances, rates, amp, fee }`.
422fn 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    // For Meta pools, the last coin is a base pool LP token whose rate must
432    // be the base pool's virtual_price. Validate that the consumer provided it.
433    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    // crvUSD factory pools (v5 and v6) lack offpeg_fee_multiplier.
473    // FEE_DENOMINATOR makes dynamic_fee() return the static fee unchanged.
474    // Consumers reading from substreams or other indexers should pass
475    // offpeg_fee_multiplier: None for these pools — this default handles it.
476    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            // TwoCryptoV1 has two deployed Vyper flavours; the consumer must say which one via
560            // `eth_variant` (typically from `detect_eth_variant`). Other variants ignore it.
561            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        // initial_A == future_A, any timestamp → returns the value
705        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        // timestamp >= future_a_time → returns future_a
713        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        // Ramp from 20000 to 40000 over [1000, 2000]. At t=1500 (midpoint):
726        // 20000 + (40000-20000) * (1500-1000) / (2000-1000) = 20000 + 10000 = 30000
727        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        // Ramp from 40000 to 20000 over [1000, 2000]. At t=1500:
734        // 40000 - (40000-20000) * 500 / 1000 = 40000 - 10000 = 30000
735        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        // Ramp from 10000 to 50000 over [0, 1000]. At t=250:
742        // 10000 + (50000-10000) * 250 / 1000 = 10000 + 10000 = 20000
743        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        // timestamp == initial_a_time → returns initial_a
750        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        // Verify integer division matches Vyper behavior (truncates, not rounds).
757        // Ramp from 10000 to 10003 over [0, 1000]. At t=1:
758        // 10000 + 3 * 1 / 1000 = 10000 + 0 = 10000 (truncated)
759        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), // 1000 DAI
769                U256::from(1_000_000_000u128),                 // 1000 USDC (6 dec)
770                U256::from(1_000_000_000u128),                 // 1000 USDT (6 dec)
771                U256::from(1_000_000_000_000_000_000_000u128), // 1000 sUSD
772            ],
773            token_decimals: vec![18, 6, 6, 18],
774            amp: U256::from(200u64), // A_PRECISION=1
775            fee: Some(U256::from(4_000_000u64)),
776            ..Default::default()
777        };
778
779        let pool = build_pool(&state).unwrap();
780        // Verify it's the right variant by attempting a swap
781        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), // 400 * A_PRECISION(100)
795            fee: Some(U256::from(4_000_000u64)),
796            ..Default::default()
797        };
798
799        let pool = build_pool(&state).unwrap();
800
801        // Check rates are correct: [10^18, 10^30]
802        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); // 1.05 * 10^18
812        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,              // computed from decimals
824                Some(oracle_rate), // oracle rate
825            ]),
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), // 100 * A_PRECISION(100)
847            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        // 18 decimals → 10^(18-18) = 1
857        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); // 1.02
864        let state = RawPoolState {
865            variant: CurveVariant::StableSwapMeta,
866            balances: vec![
867                U256::from(1_000_000_000u128),                 // GUSD (2 dec)
868                U256::from(1_000_000_000_000_000_000_000u128), // 3CRV LP
869            ],
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,                // 10^(36-2) = 10^34
875                Some(virtual_price), // virtual_price from base pool
876            ]),
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), // A=540000 * A_MULTIPLIER
898            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)); // 10^(18-18)
912        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            // gamma intentionally NOT set
928            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        // 6 decimals → 10^(18-6) = 10^12
937        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),               // USDC (6 dec)
946                U256::from(50_000_000u128),                  // WBTC (8 dec)
947                U256::from(500_000_000_000_000_000_000u128), // WETH (18 dec)
948            ],
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), // BTC price
958                U256::from(3_000_000_000_000_000_000_000u128),  // ETH price
959            ]),
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))); // 10^(18-6)
968        assert_eq!(precisions[1], U256::from(10u64).pow(U256::from(10u64))); // 10^(18-8)
969        assert_eq!(precisions[2], U256::from(1u64)); // 10^(18-18)
970        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            // fee intentionally missing
981            ..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], // wrong length
997            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)]), // needs 2, got 1
1045            ..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        // v5+ crvUSD factory pools lack offpeg_fee_multiplier
1058        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            // offpeg_fee_multiplier intentionally missing — defaults to FEE_DENOMINATOR
1065            ..Default::default()
1066        };
1067
1068        let pool = build_pool(&state).expect("should succeed with defaulted offpeg");
1069        // FEE_DENOMINATOR = 10_000_000_000
1070        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        // Real on-chain state for pool 0x1539c2461d7432cc114b0903f1824079BfCA2C92
1076        // (crvUSD/sDAI, v5.0.0 from crvUSD StableSwap Factory, no offpeg_fee_multiplier)
1077        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            // offpeg_fee_multiplier absent (v5+ pool) — defaults to FEE_DENOMINATOR
1091            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        // On-chain get_dy(0, 1, 3219009600398261) = 2720818166217034
1112        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        // Meta pool without dynamic_rates → must fail because rates[1]
1120        // would default to 10^(36-18)=10^18 instead of virtual_price.
1121        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            // dynamic_rates NOT provided → should error
1131            ..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        // dynamic_rates provided but last coin has None (no virtual_price)
1144        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]), // vp not set for last coin
1154            ..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        // 18-decimal token → rate = 10^(36-18) = 10^18
1167        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        // 6-decimal token → rate = 10^(36-6) = 10^30
1174        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        // 8-decimal token → rate = 10^(36-8) = 10^28
1181        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        // 2-decimal token (GUSD) → rate = 10^(36-2) = 10^34
1188        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        // CryptoSwap: precision = 10^(18 - decimals)
1195        let precs = super::compute_crypto_precisions(&[6, 8, 18]);
1196        assert_eq!(precs[0], U256::from(10u64).pow(U256::from(12u64))); // USDC
1197        assert_eq!(precs[1], U256::from(10u64).pow(U256::from(10u64))); // WBTC
1198        assert_eq!(precs[2], U256::from(1u64)); // WETH
1199    }
1200
1201    #[test]
1202    fn precision_mul_matches_fuzz_registry() {
1203        // ALend: precision_mul = 10^(18 - decimals)
1204        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        // Smoke test: every variant can be built with minimal valid state.
1212        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        // V0, V1, V2
1224        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        // Meta (needs virtual_price)
1231        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        // NG
1236        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        // ALend
1241        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        // CryptoSwap common fields
1246        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                // Required for TwoCryptoV1; ignored by every other crypto variant.
1263                eth_variant: Some(true),
1264                ..Default::default()
1265            }
1266        };
1267
1268        // TwoCryptoV1, TwoCryptoNG
1269        for v in [CurveVariant::TwoCryptoV1, CurveVariant::TwoCryptoNG] {
1270            assert!(build_pool(&crypto_base(v, 2)).is_ok(), "failed for {v}");
1271        }
1272
1273        // TwoCryptoStable (no gamma needed)
1274        let mut tcs = crypto_base(CurveVariant::TwoCryptoStable, 2);
1275        tcs.gamma = None;
1276        assert!(build_pool(&tcs).is_ok(), "failed for TwoCryptoStable");
1277
1278        // TriCryptoV1, TriCryptoNG
1279        for v in [CurveVariant::TriCryptoV1, CurveVariant::TriCryptoNG] {
1280            assert!(build_pool(&crypto_base(v, 3)).is_ok(), "failed for {v}");
1281        }
1282    }
1283
1284    //
1285    // These tests use hardcoded state from Ethereum mainnet at block 24722544.
1286    // For each pool variant:
1287    //   1. RawPoolState is populated with real on-chain values
1288    //   2. build_pool() constructs the Pool
1289    //   3. get_amount_out() is compared against on-chain get_dy()
1290    //
1291    // If any test fails, it means build_pool() constructs a Pool that doesn't
1292    // match the on-chain contract's behavior — either rates, amp, or fees are wrong.
1293
1294    fn u(s: &str) -> U256 {
1295        U256::from_str_radix(s, 10).unwrap()
1296    }
1297
1298    #[test]
1299    fn integration_stableswap_v0_susd() {
1300        // sUSD pool: DAI(18)/USDC(6)/USDT(6)/sUSD(18), A=256, A_PRECISION=1
1301        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        // 3pool: DAI(18)/USDC(6)/USDT(6), A=4000, A_PRECISION=1
1324        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        // FRAX/USDC: FRAX(18)/USDC(6), A=1500*100=150000
1346        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        // Aave: aDAI(18)/aUSDC(6)/aUSDT(6), A=2000*100=200000
1364        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        // USDe/DAI NG: USDe(18)/DAI(18), A=400*100=40000
1383        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        // GUSD/3CRV: GUSD(2)/3CRV(18), A=1000*100=100000, virtual_price from 3pool
1406        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,                           // coin 0: 10^(36-2) = 10^34
1414                Some(u("1039823717145796146")), // virtual_price
1415            ]),
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        // CRV/ETH: CRV(18)/WETH(18)
1428        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), // CRV/ETH is WETH-paired → ETH solver
1440            ..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        // crvUSD/FXN: crvUSD(18)/FXN(18)
1452        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        // crvUSD/WETH TwoCryptoStable: crvUSD(18)/WETH(18)
1475        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        // tricrypto2: USDT(6)/WBTC(8)/WETH(18)
1497        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        // tricrypto-ng: USDC(6)/WBTC(8)/WETH(18)
1520        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}