Skip to main content

tycho_simulation/evm/protocol/curve/
state.rs

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