Skip to main content

tycho_simulation/evm/protocol/cowamm/
state.rs

1use std::{any::Any, collections::HashMap, fmt::Debug};
2
3use alloy::primitives::U256;
4use num_bigint::{BigUint, ToBigUint};
5use serde::{Deserialize, Serialize};
6use tycho_common::{
7    dto::ProtocolStateDelta,
8    models::token::Token,
9    simulation::{
10        errors::{SimulationError, TransitionError},
11        protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
12    },
13    Bytes,
14};
15
16use crate::evm::protocol::{
17    cowamm::{
18        bmath::*,
19        constants::{BONE, MAX_IN_RATIO},
20        error::CowAMMError,
21    },
22    safe_math::{safe_add_u256, safe_div_u256, safe_mul_u256, safe_sub_u256},
23    u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
24};
25
26const COWAMM_FEE: f64 = 0.0; // 0% fee
27
28// Token 3 tuple: (address, liquidity, weight)
29type TokenInfo = (Bytes, U256, U256);
30
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32pub struct CowAMMState {
33    /// The Pool Address
34    pub address: Bytes,
35    /// Token A information: (address, liquidity, weight)
36    pub token_a: TokenInfo,
37    /// Token B information: (address, liquidity, weight)
38    pub token_b: TokenInfo,
39    /// The Swap Fee on the Pool
40    pub fee: u64,
41    ///The lp token of the pool
42    pub lp_token: Bytes,
43    /// The Supply of the lp token
44    pub lp_token_supply: U256,
45}
46
47impl CowAMMState {
48    /// Creates a new `CowAMMState` instance.
49    ///
50    /// # Arguments
51    /// - `token_a`: The address of the first token in the pair.
52    /// - `token_b`: The address of the second token in the pair.
53    /// - `liquidity_a`: Liquidity of the first token in the pair.
54    /// - `liquidity_b`: Liquidity of the second token in the pair.
55    /// - `lp_token`: The pool address (usually the LP token address).
56    /// - `lp_token_supply`: The supply of the lp_token in the pool
57    /// - `weight_a`: The denormalized weight of `token_a`.
58    /// - `weight_b`: The denormalized weight of `token_b`.
59    /// - `fee`: The swap fee for the pool.
60    ///
61    /// # Returns
62    /// A new `CowAMMState` with token states initialized.
63    #[expect(
64        clippy::too_many_arguments,
65        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
66    )]
67    pub fn new(
68        address: Bytes,
69        token_a_addr: Bytes,
70        token_b_addr: Bytes,
71        liquidity_a: U256,
72        liquidity_b: U256,
73        lp_token: Bytes,
74        lp_token_supply: U256,
75        weight_a: U256,
76        weight_b: U256,
77        fee: u64,
78    ) -> Self {
79        Self {
80            address,
81            token_a: (token_a_addr, liquidity_a, weight_a),
82            token_b: (token_b_addr, liquidity_b, weight_b),
83            lp_token,
84            lp_token_supply,
85            fee,
86        }
87    }
88    /// Helper methods
89    fn token_a_addr(&self) -> &Bytes {
90        &self.token_a.0
91    }
92
93    fn liquidity_a(&self) -> U256 {
94        self.token_a.1
95    }
96
97    fn liquidity_b(&self) -> U256 {
98        self.token_b.1
99    }
100
101    fn weight_a(&self) -> U256 {
102        self.token_a.2
103    }
104
105    fn weight_b(&self) -> U256 {
106        self.token_b.2
107    }
108
109    /// Calculates the proportion of tokens a user receives when exiting the pool by burning LP
110    /// tokens,
111    ///
112    ///
113    /// Solidity reference:
114    /// https://github.com/balancer/balancer-v2-monorepo/blob/master/pkg/core/contracts/pools/weighted/WeightedMath.sol#L299
115    ///
116    /// Formula:
117    /// amountOut\[i\] = balances\[i\] * (lpTokenAmountIn / totalLpToken)
118    ///
119    /// # Arguments
120    /// * `pool` - Reference to the pool containing balances and LP supply
121    /// * `lp_token_in` - Amount of LP tokens to burn
122    ///
123    /// # Returns
124    /// Tuple of `(amountOut_tokenA, amountOut_tokenB)`
125    pub fn calc_tokens_out_given_exact_lp_token_in(
126        &self,
127        lp_token_in: U256,
128    ) -> Result<(U256, U256), SimulationError> {
129        // Collect balances
130        let liquidity_a = self.liquidity_a();
131        let liquidity_b = self.liquidity_b();
132
133        let balances = [liquidity_a, liquidity_b];
134
135        let total_lp_token = self.lp_token_supply;
136
137        // lpTokenRatio = lp_token_in / total_lp_token
138        let lp_token_ratio = bdiv(lp_token_in, total_lp_token).map_err(|err| {
139            SimulationError::FatalError(format!("Error in calculating LP token ratio {err:?}"))
140        })?;
141
142        // amountsOut[i] = balances[i] * lp_token_ratio
143        let mut amounts_out = Vec::with_capacity(balances.len());
144
145        for balance in balances.iter() {
146            let amount = bmul(*balance, lp_token_ratio).map_err(|err| {
147                SimulationError::FatalError(format!("Error in calculating amount out {err:?}"))
148            })?;
149            amounts_out.push(amount);
150        }
151        Ok((amounts_out[0], amounts_out[1]))
152    }
153
154    //https://github.com/balancer/cow-amm/blob/main/src/contracts/BPool.sol#L174
155    /// joinPool
156    #[expect(
157        clippy::unused_self,
158        reason = "public API; changing the signature is a breaking change"
159    )]
160    pub fn join_pool(
161        &self,
162        new_state: &mut CowAMMState,
163        pool_amount_out: U256,
164        max_amounts_in: &[U256],
165    ) -> Result<(), CowAMMError> {
166        let pool_total = new_state.lp_token_supply;
167        let ratio = bdiv(pool_amount_out, pool_total)?;
168
169        if ratio.is_zero() {
170            return Err(CowAMMError::InvalidPoolRatio);
171        }
172
173        let balances = vec![new_state.liquidity_a(), new_state.liquidity_b()];
174
175        for (i, bal) in balances.into_iter().enumerate() {
176            let token_amount_in = bmul(ratio, bal)?;
177            if token_amount_in.is_zero() {
178                return Err(CowAMMError::InvalidTokenAmountIn);
179            }
180            if token_amount_in > max_amounts_in[i] {
181                return Err(CowAMMError::TokenAmountInAboveMax);
182            }
183
184            // equivalent to _pullUnderlying
185            if i == 0 {
186                new_state.token_a.1 = badd(new_state.token_a.1, token_amount_in)?;
187            } else {
188                new_state.token_b.1 = badd(new_state.token_b.1, token_amount_in)?;
189            }
190        }
191
192        // mint LP shares
193        new_state.lp_token_supply = badd(new_state.lp_token_supply, pool_amount_out)?;
194        Ok(())
195    }
196
197    /// exitPool
198    pub fn exit_pool(
199        &self,
200        new_state: &mut CowAMMState,
201        pool_amount_in: U256,
202        min_amounts_out: &[U256],
203        exit_fee: U256,
204    ) -> Result<(), CowAMMError> {
205        let pool_total = self.lp_token_supply;
206
207        // calculate fee
208        let fee = bmul(pool_amount_in, exit_fee)?;
209
210        let pai_after_fee = bsub(pool_amount_in, fee)?;
211        let ratio = bdiv(pai_after_fee, pool_total)?;
212
213        if ratio.is_zero() {
214            return Err(CowAMMError::InvalidPoolRatio);
215        }
216
217        // burn LP shares
218        new_state.lp_token_supply = bsub(self.lp_token_supply, pai_after_fee)?;
219
220        let balances = vec![self.liquidity_a(), self.liquidity_b()];
221        for (i, bal) in balances.into_iter().enumerate() {
222            let token_amount_out = bmul(ratio, bal)?;
223
224            if token_amount_out.is_zero() {
225                return Err(CowAMMError::InvalidTokenAmountOut);
226            }
227
228            if token_amount_out < min_amounts_out[i] {
229                return Err(CowAMMError::TokenAmountOutBelowMinAmountOut);
230            }
231
232            // Update new_state balances
233            if i == 0 {
234                new_state.token_a.1 = bsub(self.token_a.1, token_amount_out)?;
235            } else {
236                new_state.token_b.1 = bsub(self.token_b.1, token_amount_out)?;
237            }
238        }
239
240        Ok(())
241    }
242
243    /// Calculates swap limits for operations involving LP tokens.
244    ///
245    /// # Parameters
246    /// - `is_lp_buy`:
247    ///   - `false` → **LP → Token** (redeeming LP tokens)
248    ///   - `true`  → **Token → LP** (minting or acquiring LP tokens)
249    /// - `sell_token`: Token being provided by the user
250    /// - `buy_token`: Token being received by the user
251    ///
252    /// # Returns
253    /// - When `is_lp_buy == false` (**LP → Token**):
254    ///   - `(max_lp_in, max_token_out)`
255    ///     - `max_lp_in`: Maximum LP tokens that can be redeemed without exceeding swap limits
256    ///     - `max_token_out`: Maximum amount of the underlying token that can be received
257    ///
258    /// - When `is_lp_buy == true` (**Token → LP**):
259    ///   - `(max_token_in, max_lp_out)`
260    ///     - `max_token_in`: Maximum amount of the underlying token that can be provided
261    ///     - `max_lp_out`: Maximum LP tokens that can be minted or received
262    fn get_lp_swap_limits(
263        &self,
264        is_lp_buy: bool,
265        sell_token: &Bytes,
266        buy_token: &Bytes,
267    ) -> Result<(BigUint, BigUint), SimulationError> {
268        // LP swaps are modeled as: swap part of the input to the other leg, then join/exit.
269        // Limits cap the intermediate swap via MAX_IN_RATIO; dust is allowed.
270        if is_lp_buy {
271            // Buy LP: swap part of the sell token into the other leg, then join.
272            let is_token_a_in = *sell_token == *self.token_a_addr();
273
274            let (bal_in, weight_in, bal_out, weight_out) = if is_token_a_in {
275                (self.liquidity_a(), self.weight_a(), self.liquidity_b(), self.weight_b())
276            } else {
277                (self.liquidity_b(), self.weight_b(), self.liquidity_a(), self.weight_a())
278            };
279
280            // Cap total input by MAX_IN_RATIO of the input token balance.
281            let max_token_in = bmul(bal_in, MAX_IN_RATIO)
282                .map_err(|err| SimulationError::FatalError(format!("max_in error: {err:?}")))?;
283
284            if max_token_in.is_zero() || bal_in.is_zero() || bal_out.is_zero() {
285                return Ok((BigUint::ZERO, BigUint::ZERO));
286            }
287
288            // Find a split (x to swap, max_token_in - x to keep) that matches pool proportions.
289            let mut lo = U256::ZERO;
290            let mut hi = max_token_in;
291            let mut best_x = U256::ZERO;
292            for _ in 0..128 {
293                let x = safe_div_u256(safe_add_u256(lo, hi)?, U256::from(2u8))?;
294                let out = calculate_out_given_in(
295                    bal_in,
296                    weight_in,
297                    bal_out,
298                    weight_out,
299                    x,
300                    U256::from(self.fee),
301                )
302                .map_err(|e| SimulationError::FatalError(format!("amount_out error: {e:?}")))?;
303
304                let in_remaining = safe_sub_u256(max_token_in, x)?;
305                let bal_in_after = safe_add_u256(bal_in, x)?;
306                let bal_out_after = safe_sub_u256(bal_out, out)?;
307
308                // Target: in_remaining / bal_in_after == out / bal_out_after
309                let left = safe_mul_u256(in_remaining, bal_out_after)?;
310                let right = safe_mul_u256(out, bal_in_after)?;
311
312                if left > right {
313                    lo = safe_add_u256(x, U256::from(1u8))?;
314                } else {
315                    best_x = x;
316                    if x.is_zero() {
317                        break;
318                    }
319                    hi = safe_sub_u256(x, U256::from(1u8))?;
320                }
321            }
322
323            let x = best_x;
324            let out = calculate_out_given_in(
325                bal_in,
326                weight_in,
327                bal_out,
328                weight_out,
329                x,
330                U256::from(self.fee),
331            )
332            .map_err(|e| SimulationError::FatalError(format!("amount_out error: {e:?}")))?;
333
334            let in_remaining = safe_sub_u256(max_token_in, x)?;
335            let bal_in_after = safe_add_u256(bal_in, x)?;
336            let bal_out_after = safe_sub_u256(bal_out, out)?;
337
338            // LP minting is limited by the smaller proportional contribution.
339            let pool_total = self.lp_token_supply;
340            let lp_from_in = safe_div_u256(safe_mul_u256(in_remaining, pool_total)?, bal_in_after)?;
341            let lp_from_out = safe_div_u256(safe_mul_u256(out, pool_total)?, bal_out_after)?;
342            let max_lp_out = if lp_from_in < lp_from_out { lp_from_in } else { lp_from_out };
343
344            Ok((u256_to_biguint(max_token_in), u256_to_biguint(max_lp_out)))
345        } else {
346            // Sell LP: exit to both tokens, then swap the unwanted leg into the desired token.
347            let is_token_a_out = *buy_token == *self.token_a_addr();
348
349            let (unwanted_liquidity, unwanted_weight, wanted_liquidity, wanted_weight) =
350                if is_token_a_out {
351                    // Want token_a; swap token_b into token_a after exit.
352                    (self.liquidity_b(), self.weight_b(), self.liquidity_a(), self.weight_a())
353                } else {
354                    // Want token_b; swap token_a into token_b after exit.
355                    (self.liquidity_a(), self.weight_a(), self.liquidity_b(), self.weight_b())
356                };
357
358            if unwanted_liquidity.is_zero() {
359                return Ok((BigUint::ZERO, BigUint::ZERO));
360            }
361
362            // Cap the exit ratio so the unwanted leg can be fully swapped under MAX_IN_RATIO.
363            let max_intermediate_swap_in = bmul(unwanted_liquidity, MAX_IN_RATIO)
364                .map_err(|err| SimulationError::FatalError(format!("max_in error: {err:?}")))?;
365
366            let ratio = bdiv(max_intermediate_swap_in, unwanted_liquidity)
367                .map_err(|err| SimulationError::FatalError(format!("ratio error: {err:?}")))?;
368
369            // LP in upper bound implied by the ratio cap.
370            let max_lp_in = bmul(self.lp_token_supply, ratio)
371                .map_err(|err| SimulationError::FatalError(format!("max_lp_in error: {err:?}")))?;
372
373            // Wanted token from the exit leg at the capped ratio.
374            let exit_wanted = bmul(wanted_liquidity, ratio).map_err(|err| {
375                SimulationError::FatalError(format!("exit_wanted error: {err:?}"))
376            })?;
377
378            // Wanted token from swapping the unwanted leg at MAX_IN_RATIO.
379            let swap_out = calculate_out_given_in(
380                unwanted_liquidity,
381                unwanted_weight,
382                wanted_liquidity,
383                wanted_weight,
384                max_intermediate_swap_in,
385                U256::from(self.fee),
386            )
387            .map_err(|err| SimulationError::FatalError(format!("amount_out error: {err:?}")))?;
388
389            // Total upper bound: wanted from exit + wanted from swap.
390            let max_token_out = safe_add_u256(exit_wanted, swap_out)?;
391
392            Ok((u256_to_biguint(max_lp_in), u256_to_biguint(max_token_out)))
393        }
394    }
395}
396
397#[typetag::serde]
398impl ProtocolSim for CowAMMState {
399    fn fee(&self) -> f64 {
400        COWAMM_FEE
401    }
402    /// Calculates a f64 representation of base token price in the AMM.
403    /// ********************************************************************************************
404    /// ** calcSpotPrice
405    /// // sP = spotPrice
406    /// // bI = tokenBalanceIn                ( bI / wI )         1
407    /// // bO = tokenBalanceOut         sP =  -----------  *  ----------
408    /// // wI = tokenWeightIn                 ( bO / wO )     ( 1 - sF )
409    /// // wO = tokenWeightOut
410    /// // sF = swapFee
411    /// // *************************************************************************************
412    /// *********/
413    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
414        let (bal_in, weight_in) = if base.address == *self.token_a_addr() {
415            (self.liquidity_a(), self.weight_a())
416        } else if base.address == self.token_b.0 {
417            (self.liquidity_b(), self.weight_b())
418        } else {
419            return Err(SimulationError::FatalError(
420                "spot_price base token not in pool".to_string(),
421            ));
422        };
423
424        let (bal_out, weight_out) = if quote.address == *self.token_a_addr() {
425            (self.liquidity_a(), self.weight_a())
426        } else if quote.address == self.token_b.0 {
427            (self.liquidity_b(), self.weight_b())
428        } else {
429            return Err(SimulationError::FatalError(
430                "spot_price quote token not in pool".to_string(),
431            ));
432        };
433
434        let numer = bdiv(bal_in, weight_in).map_err(|err| {
435            SimulationError::FatalError(format!(
436                "Error in numerator bdiv(balance_base / weight_base): {err:?}"
437            ))
438        })?;
439        let denom = bdiv(bal_out, weight_out).map_err(|err| {
440            SimulationError::FatalError(format!(
441                "Error in denominator bdiv(balance_quote / weight_quote): {err:?}"
442            ))
443        })?;
444
445        let ratio = bmul(
446            bdiv(numer, denom).map_err(|err| {
447                SimulationError::FatalError(format!("Error in (numer / denom): {err:?}"))
448            })?,
449            BONE,
450        )
451        .map_err(|err| {
452            SimulationError::FatalError(format!("Error in bmul(ratio * scale): {err:?}"))
453        })?;
454
455        u256_to_f64(ratio)
456    }
457
458    fn get_amount_out(
459        &self,
460        amount_in: BigUint,
461        token_in: &Token,
462        token_out: &Token,
463    ) -> Result<GetAmountOutResult, SimulationError> {
464        let amount_in = biguint_to_u256(&amount_in);
465        if amount_in.is_zero() {
466            return Err(SimulationError::InvalidInput("Amount in cannot be zero".to_string(), None));
467        }
468
469        let is_lp_in = token_in.address == self.address;
470        let is_lp_out = token_out.address == self.address;
471
472        if is_lp_in && is_lp_out {
473            return Err(SimulationError::InvalidInput(
474                "Cannot swap LP token for LP token".into(),
475                None,
476            ));
477        }
478
479        let mut new_state = self.clone();
480
481        // ============================
482        // EXIT POOL (LP → TOKEN) //
483        // ============================
484        if is_lp_in && !is_lp_out {
485            let (proportional_token_amount_a, proportional_token_amount_b) = self
486                .calc_tokens_out_given_exact_lp_token_in(amount_in)
487                .map_err(|e| {
488                    SimulationError::FatalError(format!(
489                        "failed to calculate token proportions out error: {e:?}"
490                    ))
491                })?;
492            self.exit_pool(
493                &mut new_state,
494                amount_in,
495                &[proportional_token_amount_a, proportional_token_amount_b],
496                U256::from(self.fee),
497            )
498            .map_err(|err| SimulationError::FatalError(format!("exit_pool error: {err:?}")))?;
499
500            let (amount_to_swap, is_token_a_swap_in) = if token_out.address == *self.token_a_addr()
501            {
502                (proportional_token_amount_b, false)
503            } else {
504                (proportional_token_amount_a, true)
505            };
506
507            let amount_out = if is_token_a_swap_in {
508                calculate_out_given_in(
509                    new_state.liquidity_a(),
510                    new_state.weight_a(),
511                    new_state.liquidity_b(),
512                    new_state.weight_b(),
513                    amount_to_swap,
514                    U256::from(self.fee),
515                )
516            } else {
517                calculate_out_given_in(
518                    new_state.liquidity_b(),
519                    new_state.weight_b(),
520                    new_state.liquidity_a(),
521                    new_state.weight_a(),
522                    amount_to_swap,
523                    U256::from(self.fee),
524                )
525            }
526            .map_err(|e| SimulationError::FatalError(format!("amount_out error: {e:?}")))?;
527
528            if is_token_a_swap_in {
529                new_state.token_a.1 = safe_sub_u256(new_state.liquidity_a(), amount_to_swap)?;
530                new_state.token_b.1 = safe_add_u256(new_state.liquidity_b(), amount_out)?;
531            } else {
532                new_state.token_b.1 = safe_sub_u256(new_state.liquidity_b(), amount_to_swap)?;
533                new_state.token_a.1 = safe_add_u256(new_state.liquidity_a(), amount_out)?;
534            }
535
536            let total_trade_amount = if is_token_a_swap_in {
537                safe_add_u256(amount_out, proportional_token_amount_b)?
538            } else {
539                safe_add_u256(amount_out, proportional_token_amount_a)?
540            };
541
542            return Ok(GetAmountOutResult {
543                amount: u256_to_biguint(total_trade_amount),
544                gas: 194_140u64.to_biguint().unwrap(),
545                new_state: Box::new(new_state),
546            });
547        }
548
549        // ============================
550        // JOIN POOL (TOKEN → LP)
551        // ============================
552        if is_lp_out && !is_lp_in {
553            // This is the TOKEN -> LP flow: we will split the input token into
554            // (1) a swap leg to balance pool proportions and (2) a join leg to mint LP.
555            let fee = U256::from(self.fee);
556            let (bal_in, weight_in, bal_out, weight_out, is_token_a_in) =
557                if token_in.address == *new_state.token_a_addr() {
558                    (
559                        new_state.liquidity_a(),
560                        new_state.weight_a(),
561                        new_state.liquidity_b(),
562                        new_state.weight_b(),
563                        true,
564                    )
565                } else {
566                    (
567                        new_state.liquidity_b(),
568                        new_state.weight_b(),
569                        new_state.liquidity_a(),
570                        new_state.weight_a(),
571                        false,
572                    )
573                };
574
575            // Binary search the swap amount (x) that makes the post-swap ratio
576            // match the join ratio, minimizing dust on the join leg.
577            let mut lo = U256::ZERO;
578            let mut hi = amount_in;
579            let mut best_x = U256::ZERO;
580            for _ in 0..128 {
581                // Midpoint in integer space (floor division).
582                let x = safe_div_u256(safe_add_u256(lo, hi)?, U256::from(2u8))?;
583                let out = calculate_out_given_in(bal_in, weight_in, bal_out, weight_out, x, fee)
584                    .map_err(|e| SimulationError::FatalError(format!("amount_out error: {e:?}")))?;
585
586                // Split: x is swapped, the remainder joins as the original token.
587                let in_remaining = safe_sub_u256(amount_in, x)?;
588                let bal_in_after = safe_add_u256(bal_in, x)?;
589                let bal_out_after = safe_sub_u256(bal_out, out)?;
590
591                // Compare cross-products to decide which side of the ratio we are on.
592                let left = safe_mul_u256(in_remaining, bal_out_after)?;
593                let right = safe_mul_u256(out, bal_in_after)?;
594
595                if left > right {
596                    // Too much remaining input relative to swap output: increase swap amount.
597                    lo = safe_add_u256(x, U256::from(1u8))?;
598                } else {
599                    // Swap is large enough; record candidate and try smaller to reduce dust.
600                    best_x = x;
601                    if x.is_zero() {
602                        break;
603                    }
604                    hi = safe_sub_u256(x, U256::from(1u8))?;
605                }
606            }
607
608            // Final swap leg using the best candidate x.
609            let x = best_x;
610            let out = calculate_out_given_in(bal_in, weight_in, bal_out, weight_out, x, fee)
611                .map_err(|e| SimulationError::FatalError(format!("amount_out error: {e:?}")))?;
612
613            // Post-swap balances that will be used for the join leg.
614            let in_remaining = safe_sub_u256(amount_in, x)?;
615            let bal_in_after = safe_add_u256(bal_in, x)?;
616            let bal_out_after = safe_sub_u256(bal_out, out)?;
617
618            if bal_in_after.is_zero() || bal_out_after.is_zero() {
619                return Err(SimulationError::FatalError(
620                    "join_pool balance is zero after swap".to_string(),
621                ));
622            }
623
624            // Compute the LP shares implied by each side, then take the minimum
625            // to avoid over-minting relative to either asset.
626            let pool_total = new_state.lp_token_supply;
627            let lp_from_in = safe_div_u256(safe_mul_u256(in_remaining, pool_total)?, bal_in_after)?;
628            let lp_from_out = safe_div_u256(safe_mul_u256(out, pool_total)?, bal_out_after)?;
629            let mut lp_out = if lp_from_in < lp_from_out { lp_from_in } else { lp_from_out };
630
631            if lp_out.is_zero() {
632                return Err(SimulationError::FatalError(
633                    "join_pool produces zero lp_out".to_string(),
634                ));
635            }
636            // Update the local state with the post-swap balances before joining.
637            if is_token_a_in {
638                new_state.token_a.1 = bal_in_after;
639                new_state.token_b.1 = bal_out_after;
640            } else {
641                new_state.token_b.1 = bal_in_after;
642                new_state.token_a.1 = bal_out_after;
643            }
644
645            // These are the maximum amounts we are allowed to contribute to the join.
646            let (max_a, max_b) =
647                if is_token_a_in { (in_remaining, out) } else { (out, in_remaining) };
648
649            // join_pool uses BONE-based rounding (bdiv/bmul), which can require slightly
650            // more input than the floor-based amounts above. Reduce lp_out until the
651            // implied required amounts fit within max_a/max_b.
652            loop {
653                let ratio = bdiv(lp_out, pool_total).map_err(|err| {
654                    SimulationError::FatalError(format!("join_pool ratio error: {err:?}"))
655                })?;
656                let required_a = bmul(ratio, new_state.liquidity_a()).map_err(|err| {
657                    SimulationError::FatalError(format!("join_pool amount_a error: {err:?}"))
658                })?;
659                let required_b = bmul(ratio, new_state.liquidity_b()).map_err(|err| {
660                    SimulationError::FatalError(format!("join_pool amount_b error: {err:?}"))
661                })?;
662
663                if required_a <= max_a && required_b <= max_b {
664                    break;
665                }
666                if lp_out.is_zero() {
667                    return Err(SimulationError::FatalError(
668                        "join_pool lp_out underflow while applying rounding tolerance".to_string(),
669                    ));
670                }
671                lp_out = safe_sub_u256(lp_out, U256::from(1u8))?;
672            }
673
674            // Perform the join with the adjusted lp_out so the pool accepts the inputs.
675            self.join_pool(&mut new_state, lp_out, &[max_a, max_b])
676                .map_err(|err| SimulationError::FatalError(format!("join_pool error: {err:?}")))?;
677
678            return Ok(GetAmountOutResult {
679                amount: u256_to_biguint(lp_out),
680                gas: 120_000u64.to_biguint().unwrap(),
681                new_state: Box::new(new_state),
682            });
683        }
684
685        // ============================
686        // NORMAL SWAP
687        // ============================
688        let is_token_a_in = token_in.address == *self.token_a_addr();
689        let (bal_in, weight_in, bal_out, weight_out) = if is_token_a_in {
690            (self.liquidity_a(), self.weight_a(), self.liquidity_b(), self.weight_b())
691        } else {
692            (self.liquidity_b(), self.weight_b(), self.liquidity_a(), self.weight_a())
693        };
694
695        let amount_out = calculate_out_given_in(
696            bal_in,
697            weight_in,
698            bal_out,
699            weight_out,
700            amount_in,
701            U256::from(self.fee),
702        )
703        .map_err(|e| SimulationError::FatalError(format!("amount_out error: {e:?}")))?;
704
705        if is_token_a_in {
706            new_state.token_a.1 = safe_sub_u256(new_state.liquidity_a(), amount_in)?;
707            new_state.token_b.1 = safe_add_u256(new_state.liquidity_b(), amount_out)?;
708        } else {
709            new_state.token_b.1 = safe_sub_u256(new_state.liquidity_b(), amount_in)?;
710            new_state.token_a.1 = safe_add_u256(new_state.liquidity_a(), amount_out)?;
711        }
712
713        Ok(GetAmountOutResult {
714            amount: u256_to_biguint(amount_out),
715            gas: 120_000u64.to_biguint().unwrap(),
716            new_state: Box::new(new_state),
717        })
718    }
719
720    fn get_limits(
721        &self,
722        sell_token: Bytes,
723        buy_token: Bytes,
724    ) -> Result<(BigUint, BigUint), SimulationError> {
725        if self.liquidity_a().is_zero() || self.liquidity_b().is_zero() {
726            return Ok((BigUint::ZERO, BigUint::ZERO));
727        }
728
729        // Check if this is an LP token swap
730        let is_lp_sell = sell_token == self.address;
731        let is_lp_buy = buy_token == self.address;
732
733        // Use special LP swap limits that account for intermediate swaps
734        if is_lp_sell || is_lp_buy {
735            return self.get_lp_swap_limits(is_lp_buy, &sell_token, &buy_token);
736        }
737
738        if sell_token == *self.token_a_addr() {
739            // Sell token A for token B
740            let max_in = bmul(self.liquidity_a(), MAX_IN_RATIO)
741                .map_err(|err| SimulationError::FatalError(format!("max_in error: {err:?}")))?;
742
743            let max_out = calculate_out_given_in(
744                self.liquidity_a(),
745                self.weight_a(),
746                self.liquidity_b(),
747                self.weight_b(),
748                max_in,
749                U256::from(self.fee),
750            )
751            .map_err(|err| SimulationError::FatalError(format!("max_out error: {err:?}")))?;
752
753            Ok((u256_to_biguint(max_in), u256_to_biguint(max_out)))
754        } else {
755            // Sell token B for token A
756            let max_in = bmul(self.liquidity_b(), MAX_IN_RATIO)
757                .map_err(|err| SimulationError::FatalError(format!("max_in error: {err:?}")))?;
758
759            let max_out = calculate_out_given_in(
760                self.liquidity_b(),
761                self.weight_b(),
762                self.liquidity_a(),
763                self.weight_a(),
764                max_in,
765                U256::from(self.fee),
766            )
767            .map_err(|err| SimulationError::FatalError(format!("max_out error: {err:?}")))?;
768
769            Ok((u256_to_biguint(max_in), u256_to_biguint(max_out)))
770        }
771    }
772
773    fn delta_transition(
774        &mut self,
775        delta: ProtocolStateDelta,
776        _tokens: &HashMap<Bytes, Token>,
777        _balances: &Balances,
778    ) -> Result<(), TransitionError> {
779        // liquidity_a, liquidity_b and lp_token_supply are considered required attributes and are
780        // expected in every delta we process
781        let liquidity_a = U256::from_be_slice(
782            delta
783                .updated_attributes
784                .get("liquidity_a")
785                .ok_or(TransitionError::MissingAttribute("liquidity_a".to_string()))?,
786        );
787
788        let liquidity_b = U256::from_be_slice(
789            delta
790                .updated_attributes
791                .get("liquidity_b")
792                .ok_or(TransitionError::MissingAttribute("liquidity_b".to_string()))?,
793        );
794
795        let lp_token_supply = U256::from_be_slice(
796            delta
797                .updated_attributes
798                .get("lp_token_supply")
799                .ok_or(TransitionError::MissingAttribute("lp_token_supply".to_string()))?,
800        );
801
802        self.token_a.1 = liquidity_a;
803        self.token_b.1 = liquidity_b;
804        self.lp_token_supply = lp_token_supply;
805
806        Ok(())
807    }
808
809    fn query_pool_swap(
810        &self,
811        params: &tycho_common::simulation::protocol_sim::QueryPoolSwapParams,
812    ) -> Result<tycho_common::simulation::protocol_sim::PoolSwap, SimulationError> {
813        crate::evm::query_pool_swap::query_pool_swap(self, params)
814    }
815
816    fn clone_box(&self) -> Box<dyn ProtocolSim> {
817        Box::new(self.clone())
818    }
819
820    fn as_any(&self) -> &dyn Any {
821        self
822    }
823
824    fn as_any_mut(&mut self) -> &mut dyn Any {
825        self
826    }
827
828    fn eq(&self, other: &dyn ProtocolSim) -> bool {
829        other
830            .as_any()
831            .downcast_ref::<CowAMMState>()
832            .is_some_and(|other_state| self == other_state)
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use std::{
839        collections::{HashMap, HashSet},
840        str::FromStr,
841    };
842
843    use alloy::primitives::U256;
844    use approx::assert_ulps_eq;
845    use num_bigint::BigUint;
846    use num_traits::{One, ToPrimitive, Zero};
847    use rstest::rstest;
848    use tycho_common::{
849        dto::ProtocolStateDelta,
850        models::{token::Token, Chain},
851        simulation::errors::{SimulationError, TransitionError},
852        Bytes,
853    };
854
855    use super::*;
856    use crate::evm::protocol::{
857        cowamm::state::{CowAMMState, ProtocolSim},
858        u256_num::biguint_to_u256,
859    };
860    /// Converts a `BigUint` amount in wei to f64 ETH/WETH
861    pub fn wei_to_eth(amount: &BigUint) -> f64 {
862        // 1 ETH = 10^18 wei
863        let divisor = 1e18_f64;
864        amount.to_f64().unwrap_or(0.0) / divisor
865    }
866
867    fn create_test_tokens() -> (Token, Token, Token, Token, Token, Token, Token) {
868        let t0 = Token::new(
869            &Bytes::from_str("0xDEf1CA1fb7FBcDC777520aa7f396b4E015F497aB").unwrap(),
870            "COW",
871            18,
872            0,
873            &[Some(10_000)],
874            Chain::Ethereum,
875            100,
876        );
877
878        let t1 = Token::new(
879            &Bytes::from_str("0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0").unwrap(),
880            "wstETH",
881            18,
882            0,
883            &[Some(10_000)],
884            Chain::Ethereum,
885            100,
886        );
887
888        let t2 = Token::new(
889            &Bytes::from_str("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1").unwrap(),
890            "BCoW-50CoW-50wstETH",
891            18,
892            0,
893            &[Some(199_999_999_999_999_990)],
894            Chain::Ethereum,
895            100,
896        );
897        let t3 = Token::new(
898            &Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
899            "WETH",
900            18,
901            0,
902            &[Some(1_000_000)],
903            Chain::Ethereum,
904            100,
905        );
906        let t4 = Token::new(
907            &Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(),
908            "USDC",
909            6,
910            0,
911            &[Some(10_000_000)],
912            Chain::Ethereum,
913            100,
914        );
915        let t5 = Token::new(
916            &Bytes::from_str("0xBAac2B4491727D78D2b78815144570b9f2Fe8899").unwrap(),
917            "DOG",
918            18,
919            0,
920            &[Some(10_000_000)],
921            Chain::Ethereum,
922            100,
923        );
924        let t6 = Token::new(
925            &Bytes::from_str("0x9d0e8cdf137976e03ef92ede4c30648d05e25285").unwrap(),
926            "wstETH-DOG-LP-Token",
927            18,
928            0,
929            &[Some(10_000_000)],
930            Chain::Ethereum,
931            100,
932        );
933        (t0, t1, t2, t3, t4, t5, t6)
934    }
935
936    #[rstest]
937    #[case::same_dec(
938        U256::from_str("1547000000000000000000").unwrap(), //COW balance
939        U256::from_str("100000000000000000").unwrap(), //wstETH balance
940        0, 1, // token indices: t0 -> t1
941        BigUint::from_str("5205849666").unwrap(),  //COW in
942        BigUint::from_str("336513").unwrap(), //wstETH out
943    )]
944    #[case::test_dec(
945        U256::from_str("81297577909021519893").unwrap(), //wstETH balance
946        U256::from_str("332162411254631243300976822").unwrap(), //DOG balance
947        1, 5, // token indices: t1 -> t5
948        BigUint::from_str("1000000000000000000").unwrap(),  //wstETH in
949        BigUint::from_str("4036114059417772362872299").unwrap(), //DOG out
950    )]
951    #[case::diff_dec(
952        U256::from_str("170286779513658066185").unwrap(), //WETH balance
953        U256::from_str("413545982676").unwrap(), //USDC balance
954        3, 4, // token indices: t3 -> t4
955        BigUint::from_str("217679081735374278").unwrap(), //WETH in
956        BigUint::from_str("527964550").unwrap(), // USDC out (≈ 0.2177 WETH) for 527964550 USDC (≈ 527.96 USDC)
957    )]
958    fn test_get_amount_out(
959        #[case] liq_a: U256,
960        #[case] liq_b: U256,
961        #[case] token_in_idx: usize,
962        #[case] token_out_idx: usize,
963        #[case] amount_in: BigUint,
964        #[case] expected_out: BigUint,
965    ) {
966        let (t0, t1, t2, t3, t4, t5, t6) = create_test_tokens();
967        let tokens = [&t0, &t1, &t2, &t3, &t4, &t5, &t6];
968        let token_in = tokens[token_in_idx];
969        let token_out = tokens[token_out_idx];
970
971        let state = CowAMMState::new(
972            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
973            token_in.address.clone(),
974            token_out.address.clone(),
975            liq_a, //wstETH
976            liq_b, //DOG
977            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
978            U256::from_str("128375712183366405029").unwrap(),
979            U256::from_str("1000000000000000000").unwrap(),
980            U256::from_str("1000000000000000000").unwrap(),
981            0,
982        );
983
984        let res = state
985            .get_amount_out(amount_in.clone(), token_in, token_out)
986            .unwrap();
987
988        assert_eq!(res.amount, expected_out);
989
990        let new_state = res
991            .new_state
992            .as_any()
993            .downcast_ref::<CowAMMState>()
994            .unwrap();
995
996        assert_eq!(
997            new_state.liquidity_a(),
998            safe_sub_u256(liq_a, biguint_to_u256(&amount_in)).unwrap()
999        );
1000        assert_eq!(
1001            new_state.liquidity_b(),
1002            safe_add_u256(liq_b, biguint_to_u256(&expected_out)).unwrap()
1003        );
1004
1005        // Original state unchanged
1006        assert_eq!(state.liquidity_a(), liq_a);
1007        assert_eq!(state.liquidity_b(), liq_b);
1008    }
1009
1010    #[rstest]
1011    #[case::buy_lp_token( //buying lp token with COW == buying amounts of wstETH needed to join pool with COW, then joining pool with both tokens
1012        U256::from_str("81297577909021519893").unwrap(),      // wstETH balance
1013        U256::from_str("332162411254631243300976822").unwrap(), //DOG balance
1014        1, 6, // token indices: wstETH -> wstETH-DOG-LP-Token
1015        BigUint::from_str("1000000000000000000").unwrap(), // wstETH in
1016        BigUint::from_str("787128927353433245").unwrap(), // Amount of wstETH-DOG-LP-Token we buy from join the pool
1017    )]
1018    fn test_get_amount_out_buy_lp_token(
1019        #[case] liq_a: U256,
1020        #[case] liq_b: U256,
1021        #[case] token_in_idx: usize,
1022        #[case] token_out_idx: usize,
1023        #[case] amount_in: BigUint,
1024        #[case] expected_out: BigUint,
1025    ) {
1026        let (t0, t1, t2, t3, t4, t5, t6) = create_test_tokens();
1027        let tokens = [&t0, &t1, &t2, &t3, &t4, &t5, &t6];
1028
1029        let token_a = tokens[token_in_idx];
1030        let token_b = tokens[token_out_idx];
1031
1032        let state = CowAMMState::new(
1033            Bytes::from("0x9d0e8cdf137976e03ef92ede4c30648d05e25285"),
1034            t1.address.clone(), //wstETH
1035            t5.address.clone(), //DOG
1036            liq_a,              //wstETH Liquidity
1037            liq_b,              //DOG Liquidity
1038            Bytes::from("0x9d0e8cdf137976e03ef92ede4c30648d05e25285"),
1039            U256::from_str("128375712183366405029").unwrap(),
1040            U256::from_str("1000000000000000000").unwrap(),
1041            U256::from_str("1000000000000000000").unwrap(),
1042            0,
1043        );
1044
1045        let res = state
1046            .get_amount_out(amount_in, token_a, token_b)
1047            .unwrap();
1048
1049        assert_eq!(res.amount, expected_out);
1050        //lp token supply reduced
1051        let new_state = res
1052            .new_state
1053            .as_any()
1054            .downcast_ref::<CowAMMState>()
1055            .unwrap();
1056
1057        assert!(
1058            new_state.lp_token_supply > state.lp_token_supply,
1059            "LP token supply did not increase"
1060        );
1061
1062        // Original state unchanged
1063        assert_eq!(state.liquidity_a(), liq_a);
1064        assert_eq!(state.liquidity_b(), liq_b);
1065    }
1066
1067    #[rstest]
1068    #[case::sell_lp_token( //selling (redeeming) lp_token for COW == exiting pool and converting excess COW to wstETH
1069        U256::from_str("1547000000000000000000").unwrap(),
1070        U256::from_str("100000000000000000").unwrap(),
1071        2, 0, // token indices: t2 -> t0
1072        BigUint::from_str("1000000000000000000").unwrap(), //Amount of lp_token being sold (redeeemd)
1073        BigUint::from_str("15431325000000000000").unwrap(), //COW as output, verify that we sent this amount to the pool in total
1074    )]
1075    fn test_get_amount_out_sell_lp_token(
1076        #[case] liq_a: U256,
1077        #[case] liq_b: U256,
1078        #[case] token_in_idx: usize,
1079        #[case] token_out_idx: usize,
1080        #[case] amount_in: BigUint,
1081        #[case] expected_out: BigUint,
1082    ) {
1083        let (t0, t1, t2, t3, t4, t5, t6) = create_test_tokens();
1084        let tokens = [&t0, &t1, &t2, &t3, &t4, &t5, &t6];
1085
1086        let token_a = tokens[token_in_idx];
1087        let token_b = tokens[token_out_idx];
1088
1089        let state = CowAMMState::new(
1090            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1091            t0.address.clone(), //COW
1092            t1.address.clone(), //wstETH
1093            liq_a,              //COW
1094            liq_b,              //wstETH
1095            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1096            U256::from_str("199999999999999999990").unwrap(),
1097            U256::from_str("1000000000000000000").unwrap(),
1098            U256::from_str("1000000000000000000").unwrap(),
1099            0,
1100        );
1101
1102        let res = state
1103            .get_amount_out(amount_in, token_a, token_b)
1104            .unwrap();
1105
1106        assert_eq!(res.amount, expected_out);
1107        //lp token supply reduced
1108        let new_state = res
1109            .new_state
1110            .as_any()
1111            .downcast_ref::<CowAMMState>()
1112            .unwrap();
1113
1114        if token_a.address == t2.address {
1115            assert!(
1116                new_state.lp_token_supply < state.lp_token_supply,
1117                "LP token supply did not reduce"
1118            );
1119        } else {
1120            assert!(
1121                new_state.lp_token_supply > state.lp_token_supply,
1122                "LP token supply did not reduce"
1123            );
1124        }
1125
1126        // Original state unchanged
1127        assert_eq!(state.liquidity_a(), liq_a);
1128        assert_eq!(state.liquidity_b(), liq_b);
1129    }
1130
1131    #[test]
1132    fn test_get_amount_out_overflow() {
1133        let max = (BigUint::one() << 256) - BigUint::one();
1134
1135        let (t0, t1, _, _, _, _, _) = create_test_tokens();
1136
1137        let state = CowAMMState::new(
1138            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1139            t0.address.clone(),
1140            t1.address.clone(),
1141            U256::from_str("886800000000000000").unwrap(),
1142            U256::from_str("50000000000000000").unwrap(),
1143            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1144            U256::from_str("100000000000000000000").unwrap(),
1145            U256::from_str("1000000000000000000").unwrap(),
1146            U256::from_str("1000000000000000000").unwrap(),
1147            0,
1148        );
1149
1150        let res = state.get_amount_out(max, &t0, &t1);
1151        assert!(res.is_err());
1152        let err = res.err().unwrap();
1153        assert!(matches!(err, SimulationError::FatalError(_)));
1154    }
1155
1156    #[rstest]
1157    #[case(244752492017f64)]
1158    fn test_spot_price(#[case] expected: f64) {
1159        let (t0, _, _, _, _, t5, _) = create_test_tokens();
1160        let state = CowAMMState::new(
1161            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1162            t0.address.clone(),
1163            t5.address.clone(),
1164            U256::from_str("81297577909021519893").unwrap(),
1165            U256::from_str("332162411254631243300976822").unwrap(),
1166            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1167            U256::from_str("128375712183366405029").unwrap(),
1168            U256::from_str("1000000000000000000").unwrap(),
1169            U256::from_str("1000000000000000000").unwrap(),
1170            0,
1171        );
1172
1173        let price = state.spot_price(&t0, &t5).unwrap();
1174        assert_ulps_eq!(price, expected);
1175    }
1176
1177    #[test]
1178    fn test_fee() {
1179        let (t0, t1, _, _, _, _, _) = create_test_tokens();
1180
1181        let state = CowAMMState::new(
1182            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1183            t0.address,
1184            t1.address,
1185            U256::from_str("36925554990922").unwrap(),
1186            U256::from_str("30314846538607556521556").unwrap(),
1187            Bytes::from("0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0"),
1188            U256::from_str("36925554990922").unwrap(),
1189            U256::from_str("30314846538607556521556").unwrap(),
1190            U256::from_str("30314846538607556521556").unwrap(),
1191            0,
1192        );
1193
1194        let res = state.fee();
1195
1196        assert_ulps_eq!(res, 0.0);
1197    }
1198    #[test]
1199    fn test_delta_transition() {
1200        let (t0, t1, _, _, _, _, _) = create_test_tokens();
1201
1202        let mut state = CowAMMState::new(
1203            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1204            t0.address,
1205            t1.address,
1206            U256::from_str("36925554990922").unwrap(),
1207            U256::from_str("30314846538607556521556").unwrap(),
1208            Bytes::from("0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0"),
1209            U256::from_str("36925554990922").unwrap(),
1210            U256::from_str("30314846538607556521556").unwrap(),
1211            U256::from_str("30314846538607556521556").unwrap(),
1212            0,
1213        );
1214        let attributes: HashMap<String, Bytes> = vec![
1215            ("liquidity_a".to_string(), Bytes::from(15000_u64.to_be_bytes().to_vec())),
1216            ("liquidity_b".to_string(), Bytes::from(20000_u64.to_be_bytes().to_vec())),
1217            ("lp_token_supply".to_string(), Bytes::from(250000_u64.to_be_bytes().to_vec())),
1218        ]
1219        .into_iter()
1220        .collect();
1221        let delta = ProtocolStateDelta {
1222            component_id: "State1".to_owned(),
1223            updated_attributes: attributes,
1224            deleted_attributes: HashSet::new(),
1225        };
1226
1227        let res = state.delta_transition(delta, &HashMap::new(), &Balances::default());
1228
1229        assert!(res.is_ok());
1230        assert_eq!(state.liquidity_a(), U256::from_str("15000").unwrap());
1231        assert_eq!(state.liquidity_b(), U256::from_str("20000").unwrap());
1232        assert_eq!(state.lp_token_supply, U256::from_str("250000").unwrap());
1233    }
1234
1235    #[test]
1236    fn test_delta_transition_missing_attribute() {
1237        let mut state = CowAMMState::new(
1238            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1239            Bytes::from("0xDEf1CA1fb7FBcDC777520aa7f396b4E015F497aB"),
1240            Bytes::from("0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0"),
1241            U256::from_str("36925554990922").unwrap(),
1242            U256::from_str("30314846538607556521556").unwrap(),
1243            Bytes::from("0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0"),
1244            U256::from_str("36928554990972").unwrap(),
1245            U256::from_str("30314846538607556521556").unwrap(),
1246            U256::from_str("30314846538607556521556").unwrap(),
1247            0,
1248        );
1249        let attributes: HashMap<String, Bytes> = vec![(
1250            "liquidity_a".to_string(),
1251            Bytes::from(
1252                1500000000000000_u64
1253                    .to_be_bytes()
1254                    .to_vec(),
1255            ),
1256        )]
1257        .into_iter()
1258        .collect();
1259
1260        let delta = ProtocolStateDelta {
1261            component_id: "State1".to_owned(),
1262            updated_attributes: attributes,
1263            deleted_attributes: HashSet::new(),
1264        };
1265
1266        let res = state.delta_transition(delta, &HashMap::new(), &Balances::default());
1267
1268        assert!(res.is_err());
1269        match res {
1270            Err(e) => {
1271                assert!(matches!(e, TransitionError::MissingAttribute(ref x) if x== "liquidity_b"))
1272            }
1273            _ => panic!("Test failed: was expecting an Err value"),
1274        };
1275    }
1276
1277    #[test]
1278    fn test_get_limits_price_impact() {
1279        let (t0, t1, _, _, _, _, _) = create_test_tokens();
1280
1281        let state = CowAMMState::new(
1282            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1283            t0.address,
1284            t1.address,
1285            U256::from_str("886800000000000000").unwrap(),
1286            U256::from_str("50000000000000000").unwrap(),
1287            Bytes::from("0x9bd702E05B9c97E4A4a3E47Df1e0fe7A0C26d2F1"),
1288            U256::from_str("100000000000000000000").unwrap(),
1289            U256::from_str("1000000000000000000").unwrap(),
1290            U256::from_str("1000000000000000000").unwrap(),
1291            0,
1292        );
1293
1294        let (amount_in, _) = state
1295            .get_limits(
1296                Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
1297                Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
1298            )
1299            .unwrap();
1300
1301        let t0 = Token::new(
1302            &Bytes::from_str("0xDEf1CA1fb7FBcDC777520aa7f396b4E015F497aB").unwrap(),
1303            "COW",
1304            18,
1305            0,
1306            &[Some(10_000)],
1307            Chain::Ethereum,
1308            100,
1309        );
1310
1311        let t1 = Token::new(
1312            &Bytes::from_str("0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0").unwrap(),
1313            "wstETH",
1314            18,
1315            0,
1316            &[Some(10_000)],
1317            Chain::Ethereum,
1318            100,
1319        );
1320
1321        let result = state
1322            .get_amount_out(amount_in, &t0, &t1)
1323            .unwrap();
1324        let new_state = result
1325            .new_state
1326            .as_any()
1327            .downcast_ref::<CowAMMState>()
1328            .unwrap();
1329
1330        let initial_price = state.spot_price(&t0, &t1).unwrap();
1331        println!("Initial spot price (t0 -> t1): {}", initial_price);
1332
1333        let new_price = new_state.spot_price(&t0, &t1).unwrap();
1334
1335        println!("New spot price (t0 -> t1), floored: {}", new_price);
1336
1337        assert!(new_price < initial_price);
1338    }
1339    #[test]
1340    fn test_arb_weth_lp_limits_calculation() {
1341        let arb = Token::new(
1342            &Bytes::from_str("0xb50721bcf8d664c30412cfbc6cf7a15145234ad1").unwrap(),
1343            "ARB",
1344            18,
1345            0,
1346            &[Some(10_000)],
1347            Chain::Ethereum,
1348            100,
1349        );
1350        let weth = Token::new(
1351            &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
1352            "WETH",
1353            18,
1354            0,
1355            &[Some(10_000)],
1356            Chain::Ethereum,
1357            100,
1358        );
1359        let lp_token = Token::new(
1360            &Bytes::from_str("0x4359a8ea4c353d93245c0b6b8608a28bb48a05e2").unwrap(),
1361            "BCoW-50ARB-50WETH",
1362            18,
1363            0,
1364            &[Some(60_502_268_657_704_388)],
1365            Chain::Ethereum,
1366            100,
1367        );
1368
1369        let state = CowAMMState::new(
1370            Bytes::from_str("0x4359a8ea4c353d93245c0b6b8608a28bb48a05e2").unwrap(),
1371            arb.address,
1372            weth.address.clone(),
1373            U256::from_str("286275852074040134274570").unwrap(), //ARB
1374            U256::from_str("61694306956323018369").unwrap(),     //WETH
1375            Bytes::from_str("0x4359a8ea4c353d93245c0b6b8608a28bb48a05e2").unwrap(),
1376            U256::from_str("60502268657704388057834").unwrap(),
1377            U256::from_str("1000000000000000000").unwrap(),
1378            U256::from_str("1000000000000000000").unwrap(),
1379            0,
1380        );
1381
1382        //Get limits for LP → WETH
1383        //uses lp_limits
1384        let (max_lp_in, max_weth_out) = state
1385            .get_limits(lp_token.address.clone(), weth.address.clone())
1386            .unwrap();
1387
1388        println!("LP → WETH limits:");
1389        println!("  Max LP in: {}", max_lp_in);
1390        println!("  Max WETH out: {:.6} WETH", wei_to_eth(&max_weth_out));
1391
1392        // Test with 10% of the SAFE max
1393        let amount_in = max_lp_in / BigUint::from(10u64);
1394        println!("\nTesting with 10% of safe max: {}", amount_in);
1395
1396        let res = state
1397            .get_amount_out(amount_in, &lp_token, &weth)
1398            .expect("Should succeed with safe limit");
1399        // Basic sanity assertions
1400        assert!(!res.amount.is_zero(), "Amount out should be non-zero for a valid LP redemption");
1401    }
1402}