Skip to main content

tycho_simulation/evm/protocol/balancer_v3/
state.rs

1//! [`BalancerV3State`] — a hybrid Balancer V3 pool: pure-Rust quote maths
2//! (`balancer_maths_rust`) over state read from the locally indexed VM storage.
3use std::any::Any;
4
5use alloy::primitives::{Address as AlloyAddress, U256};
6use balancer_maths_rust::{
7    common::{
8        maths::{div_up_fixed, mul_down_fixed, mul_up_fixed, pow_up_fixed},
9        pool_base::PoolBase,
10        types::{PoolState, SwapInput, SwapKind, SwapParams},
11        utils::{
12            compute_and_charge_aggregate_swap_fees_raw, to_raw_undo_rate_round_down,
13            to_scaled_18_apply_rate_round_down,
14        },
15        WAD as ONE_WAD_SCALED_18,
16    },
17    pools::{
18        quantamm::QuantAmmPool,
19        reclammv2::{compute_current_virtual_balances, compute_in_given_out, ReClammV2Pool},
20        stable::{self, StablePool},
21        weighted::{WeightedPool, MAX_IN_RATIO},
22    },
23    vault::swap::{swap as vault_swap, MINIMUM_TRADE_AMOUNT},
24    DefaultHook, PoolError,
25};
26use num_bigint::{BigUint, ToBigUint};
27use serde::{Deserialize, Serialize};
28use tycho_common::{
29    dto::ProtocolStateDelta,
30    models::token::Token,
31    simulation::{
32        errors::{SimulationError, TransitionError},
33        protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
34    },
35    Bytes,
36};
37
38use crate::evm::{
39    engine_db::{create_engine, SHARED_TYCHO_DB},
40    protocol::{
41        balancer_v3::vm,
42        u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
43        utils::add_fee_markup,
44    },
45};
46
47/// Fee and rate denominator used throughout Balancer V3 (`1e18`).
48const WAD: f64 = 1e18;
49/// Representative gas for a single-hop Balancer V3 swap. Executions observed in the
50/// `vm:balancer_v3` integration test spent 206k–242k gas including the router and executor.
51const SWAP_GAS: u64 = 210_000;
52/// Fraction of the input balance probed to approximate the marginal price (`1e-6`).
53const SPOT_PRICE_PROBE_DIVISOR: u64 = 1_000_000;
54/// Attribute the stream decoder attaches to every delta, carrying the block's timestamp.
55const BLOCK_TIMESTAMP_ATTRIBUTE: &str = "block_timestamp";
56/// Hard cap the Vault stores any balance under (`2^128 - 1`), which is what bounds a stable
57/// pool's input: `StableMath` itself has no input limit.
58const MAX_VAULT_BALANCE: U256 = U256::from_limbs([u64::MAX, u64::MAX, 0, 0]);
59/// Largest share of the output reserve a reCLAMM swap may buy (`0.99e18`), matching
60/// `_MAX_TOKEN_OUT_RATIO` in the reference implementation.
61const MAX_TOKEN_OUT_RATIO: U256 = U256::from_limbs([990_000_000_000_000_000, 0, 0, 0]);
62/// Largest ratio between any two live balances a stable-pool swap may leave behind, matching
63/// `StableMath.MAX_IMBALANCE_RATIO` (`10_000`). Added to the v3 factory generation's
64/// `StablePool.onSwap`; `balancer_maths_rust` still only models the December 2024 genesis
65/// contracts and has no such check.
66const STABLE_MAX_IMBALANCE_RATIO: U256 = U256::from_limbs([10_000, 0, 0, 0]);
67
68/// A single Balancer V3 pool quoted through `balancer_maths_rust`.
69///
70/// The storage-derived parts of the state are re-read from the VM on every
71/// [`ProtocolSim::delta_transition`] rather than patched from the delta: the values the maths
72/// needs (live balances, token rates, amplification) are derived from storage that other
73/// contracts — rate providers above all — own. What registration fixed forever (tokens, scaling
74/// factors, weights, the hook check) is kept from decode time.
75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76pub struct BalancerV3State {
77    /// Pool contract address (the Tycho component id).
78    pool_address: Bytes,
79    /// Token addresses in pool registration order, which the maths library indexes balances, rates
80    /// and weights by.
81    tokens: Vec<Bytes>,
82    /// Per-token minimum live balance (scaled 18, registration order) a weighted pool's own
83    /// `MinTokenBalanceLib` check enforces. Empty when no such floor applies: non-weighted pools,
84    /// and weighted generations predating the check (`getMinTokenBalances` reverts on them).
85    min_token_balances: Vec<U256>,
86    /// Timestamp of the block this state was read at. reCLAMM quotes depend on it, so it is
87    /// refreshed on every update; the other families ignore it.
88    block_timestamp: u64,
89    /// Pool state in the form the maths library consumes.
90    state: PoolState,
91}
92
93impl BalancerV3State {
94    pub(super) fn new(
95        pool_address: Bytes,
96        tokens: Vec<Bytes>,
97        min_token_balances: Vec<U256>,
98        block_timestamp: u64,
99        state: PoolState,
100    ) -> Self {
101        Self { pool_address, tokens, min_token_balances, block_timestamp, state }
102    }
103
104    /// Token addresses in pool registration order.
105    #[cfg(test)]
106    pub(super) fn token_addresses(&self) -> &[Bytes] {
107        &self.tokens
108    }
109
110    /// Reserves in each token's own units, in pool registration order.
111    #[cfg(test)]
112    pub(super) fn raw_balances(&self) -> Vec<U256> {
113        let base = self.state.base();
114        (0..base.balances_live_scaled_18.len())
115            .map(|index| raw_balance(base, index).expect("a live balance must rescale to raw"))
116            .collect()
117    }
118
119    /// Live scaled-18 balances in pool registration order.
120    #[cfg(test)]
121    pub(super) fn state_balances(&self) -> &[U256] {
122        &self
123            .state
124            .base()
125            .balances_live_scaled_18
126    }
127
128    pub(super) fn token_index(&self, token: &Bytes) -> Result<usize, SimulationError> {
129        self.tokens
130            .iter()
131            .position(|candidate| candidate == token)
132            .ok_or_else(|| {
133                SimulationError::InvalidInput(
134                    format!(
135                        "token {token} is not registered in balancer_v3 pool {}",
136                        self.pool_address
137                    ),
138                    None,
139                )
140            })
141    }
142
143    /// Builds the pool implementation the maths dispatches a swap to, which `Vault::swap` would
144    /// otherwise build itself. [`Self::spot_price`] needs it for a second reason: only `on_swap`
145    /// reports an amount before the swap fee is taken.
146    fn pool_impl(&self) -> Result<Box<dyn PoolBase>, PoolError> {
147        match &self.state {
148            PoolState::Weighted(state) => Ok(Box::new(WeightedPool::from(state.clone()))),
149            PoolState::Stable(state) => Ok(Box::new(StablePool::new(state.mutable.clone()))),
150            PoolState::ReClammV2(state) => Ok(Box::new(ReClammV2Pool::new(state.clone()))),
151            // Unlike the other families, building this resolves the pool's time-interpolated
152            // weights, which fails if the packed weight arrays are shorter than the token list.
153            PoolState::QuantAmm(state) => {
154                QuantAmmPool::new(state.clone()).map(|pool| Box::new(pool) as Box<dyn PoolBase>)
155            }
156            other @ (PoolState::Base(_) |
157            PoolState::GyroECLP(_) |
158            PoolState::ReClamm(_) |
159            PoolState::LiquidityBootstrapping(_) |
160            PoolState::FixedPriceLBP(_)) => {
161                Err(PoolError::UnsupportedPoolType(other.pool_type().to_string()))
162            }
163        }
164    }
165
166    /// Swaps `amount_in` of `token_in` for `token_out`, returning the Vault's own [`PoolError`] on
167    /// failure so callers that care about a specific failure mode (see
168    /// [`ProtocolSim::get_limits`]) do not have to parse it back out of a formatted message.
169    fn vault_swap_exact_in(
170        &self,
171        amount_in: U256,
172        token_in: &Bytes,
173        token_out: &Bytes,
174    ) -> Result<U256, PoolError> {
175        let input = SwapInput {
176            amount_raw: amount_in,
177            swap_kind: SwapKind::GivenIn,
178            token_in: format!("0x{}", hex::encode(token_in)),
179            token_out: format!("0x{}", hex::encode(token_out)),
180        };
181        // `Vault::swap` takes the state by `Box<PoolState>`, cloning it on every call — which the
182        // limit searches make hundreds of. Supplying the pool implementation and hook directly is
183        // all its body does before delegating here, and lets the state be borrowed. The no-op hook
184        // is faithful because the decoder rejects pools carrying a swap hook.
185        vault_swap(&input, &self.state, self.pool_impl()?.as_ref(), &DefaultHook::new(), None)
186    }
187
188    /// Largest input the Vault accepts for a swap from `index_in` to `index_out`, in the input
189    /// token's raw units.
190    ///
191    /// Mirrors the reference implementation's `getMaxSwapAmount` for exact-in swaps. Each family
192    /// bounds it differently — see the per-family functions below; reCLAMM is bounded on the
193    /// output side, by the input that buys [`MAX_TOKEN_OUT_RATIO`] of the output reserve at the
194    /// current virtual balances.
195    fn max_swap_amount_in(
196        &self,
197        index_in: usize,
198        index_out: usize,
199    ) -> Result<U256, SimulationError> {
200        let base = self.state.base();
201        let balances = &base.balances_live_scaled_18;
202        let maths_error = |e: PoolError| {
203            SimulationError::FatalError(format!(
204                "balancer_v3 swap limit failed for pool {}: {e:?}",
205                self.pool_address
206            ))
207        };
208
209        let max_in_scaled_18 = match &self.state {
210            PoolState::Weighted(state) => {
211                self.weighted_max_swap_amount_in(index_in, index_out, state.weights())?
212            }
213            PoolState::Stable(_) => self.stable_max_swap_amount_in(index_in, index_out)?,
214            // QuantAMM is bounded in raw units rather than scaled-18 ones, so it returns straight
215            // away instead of falling through to the conversion below.
216            PoolState::QuantAmm(state) => {
217                return self.quantamm_max_swap_amount_in(
218                    index_in,
219                    index_out,
220                    &state.immutable.max_trade_size_ratio,
221                )
222            }
223            PoolState::ReClammV2(state) => {
224                let max_out_scaled_18 = mul_down_fixed(&MAX_TOKEN_OUT_RATIO, &balances[index_out])
225                    .map_err(maths_error)?;
226                let mutable = &state.mutable;
227                // A pool whose reserves and virtual balances are small enough for its invariant to
228                // round to zero has no price range to speak of, and reports as much rather than
229                // dividing by it. Recoverable: a re-seeded pool quotes again.
230                let (virtual_balance_a, virtual_balance_b, _) = compute_current_virtual_balances(
231                    &mutable.current_timestamp,
232                    balances,
233                    &mutable.last_virtual_balances[0],
234                    &mutable.last_virtual_balances[1],
235                    &mutable.daily_price_shift_base,
236                    &mutable.last_timestamp,
237                    &mutable.centeredness_margin,
238                    &mutable.start_fourth_root_price_ratio,
239                    &mutable.end_fourth_root_price_ratio,
240                    &mutable.price_ratio_update_start_time,
241                    &mutable.price_ratio_update_end_time,
242                )
243                .map_err(|e| {
244                    SimulationError::RecoverableError(format!(
245                        "balancer_v3 reCLAMM pool {} has no usable price range: {e:?}",
246                        self.pool_address
247                    ))
248                })?;
249                compute_in_given_out(
250                    balances,
251                    &virtual_balance_a,
252                    &virtual_balance_b,
253                    index_in,
254                    index_out,
255                    &max_out_scaled_18,
256                )
257                .map_err(|e| {
258                    SimulationError::FatalError(format!(
259                        "balancer_v3 swap limit failed for pool {}: {e}",
260                        self.pool_address
261                    ))
262                })?
263            }
264            other @ (PoolState::Base(_) |
265            PoolState::GyroECLP(_) |
266            PoolState::ReClamm(_) |
267            PoolState::LiquidityBootstrapping(_) |
268            PoolState::FixedPriceLBP(_)) => {
269                return Err(SimulationError::FatalError(format!(
270                    "balancer_v3 pool {} holds unsupported state `{}`",
271                    self.pool_address,
272                    other.pool_type()
273                )))
274            }
275        };
276
277        to_raw_undo_rate_round_down(
278            &max_in_scaled_18,
279            &base.scaling_factors[index_in],
280            &base.token_rates[index_in],
281        )
282        .map_err(maths_error)
283    }
284
285    /// Largest raw input a QuantAMM pool accepts, found by binary search over the Vault path.
286    ///
287    /// `onSwap` applies `maxTradeSizeRatio` to *both* sides, so the input reserve's share of it is
288    /// only an upper bound — on a pool whose weights are far apart, a permitted input can still
289    /// buy more of the output reserve than the same ratio allows. Inverting the output bound in
290    /// closed form would mean recomputing the pool's time-interpolated weights here, which would
291    /// drift from the quotes `balancer_maths_rust` produces; probing the real swap keeps the limit
292    /// consistent with [`Self::get_amount_out`] by construction. The predicate is monotonic in the
293    /// input, so the search converges on the largest accepted amount, or zero if there is none.
294    fn quantamm_max_swap_amount_in(
295        &self,
296        index_in: usize,
297        index_out: usize,
298        max_trade_size_ratio: &U256,
299    ) -> Result<U256, SimulationError> {
300        let base = self.state.base();
301        let maths_error = |e: PoolError| {
302            SimulationError::FatalError(format!(
303                "balancer_v3 swap limit failed for pool {}: {e:?}",
304                self.pool_address
305            ))
306        };
307
308        let input_cap_scaled_18 =
309            mul_down_fixed(&base.balances_live_scaled_18[index_in], max_trade_size_ratio)
310                .map_err(maths_error)?;
311        let mut high = to_raw_undo_rate_round_down(
312            &input_cap_scaled_18,
313            &base.scaling_factors[index_in],
314            &base.token_rates[index_in],
315        )
316        .map_err(maths_error)?;
317
318        let (token_in, token_out) = (&self.tokens[index_in], &self.tokens[index_out]);
319        let accepted = |amount: &U256| {
320            self.vault_swap_exact_in(*amount, token_in, token_out)
321                .is_ok()
322        };
323        if accepted(&high) {
324            return Ok(high);
325        }
326
327        let mut low = U256::ZERO;
328        while high - low > U256::from(1) {
329            let mid = low + ((high - low) >> 1);
330            if accepted(&mid) {
331                low = mid;
332            } else {
333                high = mid;
334            }
335        }
336        Ok(low)
337    }
338
339    /// Caps a weighted-pool exact-in swap in scaled-18 terms, the way the Vault would reject it
340    /// on-chain.
341    ///
342    /// Every generation enforces [`MAX_IN_RATIO`] inside `WeightedMath.computeOutGivenExactIn`.
343    /// Pools registering a per-token minimum balance (`MinTokenBalanceLib`, added to the v2
344    /// generation and not modelled by `balancer_maths_rust`) also require that neither balance
345    /// fall below its minimum after the swap, inverted here through
346    /// [`weighted_in_given_exact_out_unguarded`]. The tighter of the two wins.
347    fn weighted_max_swap_amount_in(
348        &self,
349        index_in: usize,
350        index_out: usize,
351        weights: &[U256],
352    ) -> Result<U256, SimulationError> {
353        let base = self.state.base();
354        let balances = &base.balances_live_scaled_18;
355        let maths_error = |e: PoolError| {
356            SimulationError::FatalError(format!(
357                "balancer_v3 swap limit failed for pool {}: {e:?}",
358                self.pool_address
359            ))
360        };
361
362        let ratio_cap = mul_down_fixed(&balances[index_in], &MAX_IN_RATIO).map_err(maths_error)?;
363        let (Some(&min_in), Some(&min_out)) =
364            (self.min_token_balances.get(index_in), self.min_token_balances.get(index_out))
365        else {
366            // No factory-registered minimum for this pool: nothing beyond MAX_IN_RATIO applies.
367            return Ok(ratio_cap);
368        };
369
370        // Mirrors `onSwap`'s check on the input side: it reads the current balance (offset by the
371        // Vault's rounding buffer of 1), not a post-swap one, so no amount can make this pass.
372        if balances[index_in] + U256::from(1) < min_in {
373            return Ok(U256::ZERO);
374        }
375        // A zero minimum registers no real floor for this token: skip the inversion below rather
376        // than feed it a target of the full balance, which is a singular point on the curve
377        // (`weighted_in_given_exact_out_unguarded` divides by `balance_out - target_out`).
378        if min_out.is_zero() {
379            return Ok(ratio_cap);
380        }
381        let Some(target_out) = balances[index_out].checked_sub(min_out) else {
382            return Ok(U256::ZERO);
383        };
384        if target_out.is_zero() {
385            return Ok(U256::ZERO);
386        }
387
388        let min_balance_cap = match weighted_in_given_exact_out_unguarded(
389            &balances[index_in],
390            &weights[index_in],
391            &balances[index_out],
392            &weights[index_out],
393            &target_out,
394        ) {
395            Ok(cap) => cap,
396            // The inversion raises the output reserve's depletion ratio to `weight_out /
397            // weight_in`, which is 99 on a 99/1 pool. Overflowing it means buying the output side
398            // down to its floor would take more input than a `U256` holds, so the minimum sits
399            // far beyond `MAX_IN_RATIO` and cannot be what binds.
400            Err(PoolError::MathOverflow) => return Ok(ratio_cap),
401            Err(e) => return Err(maths_error(e)),
402        };
403        Ok(ratio_cap.min(min_balance_cap))
404    }
405
406    /// Largest exact-in input a stable-pool swap can take without the live balances drifting past
407    /// [`STABLE_MAX_IMBALANCE_RATIO`]. That check has no closed-form inverse over the stable
408    /// invariant, but [`Self::stable_swap_keeps_balance_valid`] is monotonic in the input, so the
409    /// binary search converges to within a wei.
410    pub(super) fn stable_max_swap_amount_in(
411        &self,
412        index_in: usize,
413        index_out: usize,
414    ) -> Result<U256, SimulationError> {
415        let balances = &self
416            .state
417            .base()
418            .balances_live_scaled_18;
419        let mut low = U256::ZERO;
420        let mut high = MAX_VAULT_BALANCE.saturating_sub(balances[index_in]);
421        if self.stable_swap_keeps_balance_valid(index_in, index_out, &high)? {
422            return Ok(high);
423        }
424        while high - low > U256::from(1) {
425            let mid = low + ((high - low) >> 1);
426            if self.stable_swap_keeps_balance_valid(index_in, index_out, &mid)? {
427                low = mid;
428            } else {
429                high = mid;
430            }
431        }
432        Ok(low)
433    }
434
435    /// Whether an exact-in swap of `amount_in_scaled_18` (pre-fee, matching the Vault's
436    /// `amountGivenScaled18` before the swap-fee deduction) leaves every live balance inside the
437    /// pool's maximum imbalance ratio. Mirrors the v3-generation `StablePool.onSwap`, which
438    /// `balancer_maths_rust` — modelling only the December 2024 genesis contracts — does not
439    /// check.
440    pub(super) fn stable_swap_keeps_balance_valid(
441        &self,
442        index_in: usize,
443        index_out: usize,
444        amount_in_scaled_18: &U256,
445    ) -> Result<bool, SimulationError> {
446        let base = self.state.base();
447        let PoolState::Stable(state) = &self.state else {
448            return Err(SimulationError::FatalError(format!(
449                "balancer_v3 pool {} is not a stable pool",
450                self.pool_address
451            )));
452        };
453        let balances = &base.balances_live_scaled_18;
454        let maths_error = |e: PoolError| {
455            SimulationError::FatalError(format!(
456                "balancer_v3 stable limit probe failed for pool {}: {e:?}",
457                self.pool_address
458            ))
459        };
460
461        // `stable_math::compute_invariant` divides by each balance unchecked, so a zero balance on
462        // an untouched token would panic rather than error — reachable in a pool with more than
463        // two tokens, since `get_limits` only screens `index_in` and `index_out`.
464        if balances.iter().any(U256::is_zero) {
465            return Ok(false);
466        }
467
468        let fee_scaled = mul_up_fixed(amount_in_scaled_18, &base.swap_fee).map_err(maths_error)?;
469        let Some(amount_in_after_fee) = amount_in_scaled_18.checked_sub(fee_scaled) else {
470            return Ok(false);
471        };
472        if amount_in_after_fee < MINIMUM_TRADE_AMOUNT {
473            return Ok(false);
474        }
475
476        let amp = &state.mutable.amp;
477        let invariant = stable::compute_invariant(amp, balances).map_err(maths_error)?;
478        let Ok(amount_out_scaled) = stable::compute_out_given_exact_in(
479            amp,
480            balances,
481            index_in,
482            index_out,
483            &amount_in_after_fee,
484            &invariant,
485        ) else {
486            return Ok(false);
487        };
488        let Some(new_balance_out) = balances[index_out].checked_sub(amount_out_scaled) else {
489            return Ok(false);
490        };
491        let new_balance_in = balances[index_in] + amount_in_after_fee;
492
493        let min_balance = balances
494            .iter()
495            .copied()
496            .min()
497            .unwrap_or_default()
498            .min(new_balance_out);
499        let max_balance = balances
500            .iter()
501            .copied()
502            .max()
503            .unwrap_or_default()
504            .max(new_balance_in);
505        if min_balance.is_zero() {
506            return Ok(false);
507        }
508        Ok(max_balance < STABLE_MAX_IMBALANCE_RATIO * min_balance)
509    }
510
511    /// Applies a completed swap to the live balances, mirroring what the Vault does on-chain.
512    ///
513    /// The protocol's share of the swap fee leaves the pool, so it is deducted from the input
514    /// increment. Re-scaling `amount_out` from the raw amount can land one unit below the value
515    /// the Vault used, which only matters for a route crossing the same pool twice.
516    fn with_swap_applied(
517        &self,
518        amount_in: U256,
519        amount_out: U256,
520        index_in: usize,
521        index_out: usize,
522    ) -> Result<Self, SimulationError> {
523        let base = self.state.base();
524        let maths_error = |e: balancer_maths_rust::PoolError| {
525            SimulationError::FatalError(format!("balancer_v3 balance update failed: {e:?}"))
526        };
527
528        let amount_in_scaled = to_scaled_18_apply_rate_round_down(
529            &amount_in,
530            &base.scaling_factors[index_in],
531            &base.token_rates[index_in],
532        )
533        .map_err(maths_error)?;
534        let amount_out_scaled = to_scaled_18_apply_rate_round_down(
535            &amount_out,
536            &base.scaling_factors[index_out],
537            &base.token_rates[index_out],
538        )
539        .map_err(maths_error)?;
540        let total_fee_scaled =
541            mul_up_fixed(&amount_in_scaled, &base.swap_fee).map_err(maths_error)?;
542        // This returns the fee in the input token's raw units, truncated to whole ones, so it has
543        // to be scaled back up before meeting balances held at 18 decimals. Skipping that leaves
544        // the deduction short by the token's scaling factor — 10^12 for something like USDC.
545        let protocol_fee_raw = compute_and_charge_aggregate_swap_fees_raw(
546            &total_fee_scaled,
547            &base.aggregate_swap_fee,
548            &base.scaling_factors,
549            &base.token_rates,
550            index_in,
551        )
552        .map_err(maths_error)?;
553        let protocol_fee_scaled = to_scaled_18_apply_rate_round_down(
554            &protocol_fee_raw,
555            &base.scaling_factors[index_in],
556            &base.token_rates[index_in],
557        )
558        .map_err(maths_error)?;
559
560        let mut balances = base.balances_live_scaled_18.clone();
561        balances[index_in] += amount_in_scaled - protocol_fee_scaled;
562        balances[index_out] = balances[index_out].saturating_sub(amount_out_scaled);
563
564        let mut updated = self.clone();
565        updated.set_balances(balances);
566        Ok(updated)
567    }
568
569    fn set_balances(&mut self, balances: Vec<U256>) {
570        match &mut self.state {
571            PoolState::Weighted(state) => state.base.balances_live_scaled_18 = balances,
572            PoolState::Stable(state) => state.base.balances_live_scaled_18 = balances,
573            PoolState::ReClammV2(state) => state.base.balances_live_scaled_18 = balances,
574            PoolState::QuantAmm(state) => state.base.balances_live_scaled_18 = balances,
575            PoolState::Base(_) |
576            PoolState::GyroECLP(_) |
577            PoolState::ReClamm(_) |
578            PoolState::LiquidityBootstrapping(_) |
579            PoolState::FixedPriceLBP(_) => {}
580        }
581    }
582}
583
584#[typetag::serde]
585impl ProtocolSim for BalancerV3State {
586    fn fee(&self) -> f64 {
587        u256_to_f64(self.state.base().swap_fee)
588            .map(|fee| fee / WAD)
589            .unwrap_or(0.0)
590    }
591
592    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
593        let index_in = self.token_index(&base.address)?;
594        let index_out = self.token_index(&quote.address)?;
595        let pool_base = self.state.base();
596        let balances = &pool_base.balances_live_scaled_18;
597
598        // Probe a negligible fraction of the pool so the result approximates the marginal price.
599        // `on_swap` is called before the Vault takes the swap fee, so the ratio is pre-fee and the
600        // house-wide fee markup can be applied on top.
601        let probe = (balances[index_in] / U256::from(SPOT_PRICE_PROBE_DIVISOR)).max(U256::from(1));
602        let probe_failed = |e: PoolError| {
603            SimulationError::RecoverableError(format!(
604                "balancer_v3 spot price probe failed for pool {}: {e:?}",
605                self.pool_address
606            ))
607        };
608        let out = self
609            .pool_impl()
610            .map_err(probe_failed)?
611            .on_swap(&SwapParams {
612                swap_kind: SwapKind::GivenIn,
613                token_in_index: index_in,
614                token_out_index: index_out,
615                amount_scaled_18: probe,
616                balances_live_scaled_18: balances.clone(),
617            })
618            .map_err(probe_failed)?;
619
620        // Live balances are already normalized to 18 decimals, so the decimal correction cancels;
621        // what remains is undoing the token rates that scaled them into underlying-value terms.
622        let ratio = u256_to_f64(out)? / u256_to_f64(probe)?;
623        let rate_in = u256_to_f64(pool_base.token_rates[index_in])?;
624        let rate_out = u256_to_f64(pool_base.token_rates[index_out])?;
625        if rate_out == 0.0 {
626            return Err(SimulationError::RecoverableError(format!(
627                "balancer_v3 pool {} reports a zero rate for {}",
628                self.pool_address, quote.address
629            )));
630        }
631        Ok(add_fee_markup(ratio * rate_in / rate_out, self.fee()))
632    }
633
634    fn get_amount_out(
635        &self,
636        amount_in: BigUint,
637        token_in: &Token,
638        token_out: &Token,
639    ) -> Result<GetAmountOutResult, SimulationError> {
640        let index_in = self.token_index(&token_in.address)?;
641        let index_out = self.token_index(&token_out.address)?;
642        let amount_in = biguint_to_u256(&amount_in);
643        let amount_out = self
644            .vault_swap_exact_in(amount_in, &token_in.address, &token_out.address)
645            .map_err(|e| {
646                SimulationError::RecoverableError(format!(
647                    "balancer_v3 swap failed for pool {}: {e:?}",
648                    self.pool_address
649                ))
650            })?;
651        let new_state = self.with_swap_applied(amount_in, amount_out, index_in, index_out)?;
652
653        Ok(GetAmountOutResult::new(
654            u256_to_biguint(amount_out),
655            SWAP_GAS
656                .to_biguint()
657                .expect("u64 fits in BigUint"),
658            Box::new(new_state),
659        ))
660    }
661
662    fn get_limits(
663        &self,
664        sell_token: Bytes,
665        buy_token: Bytes,
666    ) -> Result<(BigUint, BigUint), SimulationError> {
667        let index_in = self.token_index(&sell_token)?;
668        let index_out = self.token_index(&buy_token)?;
669        let base = self.state.base();
670        if base.balances_live_scaled_18[index_in].is_zero() ||
671            base.balances_live_scaled_18[index_out].is_zero()
672        {
673            return Ok((BigUint::ZERO, BigUint::ZERO));
674        }
675
676        let max_in = self.max_swap_amount_in(index_in, index_out)?;
677        if max_in.is_zero() {
678            return Ok((BigUint::ZERO, BigUint::ZERO));
679        }
680        // A pool so close to empty that even its own largest swap trades below the Vault's
681        // minimum is a dust pool with nothing to quote, not a fatal error.
682        let max_out = match self.vault_swap_exact_in(max_in, &sell_token, &buy_token) {
683            Ok(amount_out) => amount_out,
684            Err(PoolError::TradeAmountTooSmall) => return Ok((BigUint::ZERO, BigUint::ZERO)),
685            Err(e) => {
686                return Err(SimulationError::RecoverableError(format!(
687                    "balancer_v3 swap failed for pool {}: {e:?}",
688                    self.pool_address
689                )))
690            }
691        };
692        Ok((u256_to_biguint(max_in), u256_to_biguint(max_out)))
693    }
694
695    fn delta_transition(
696        &mut self,
697        delta: ProtocolStateDelta,
698        _tokens: &std::collections::HashMap<Bytes, Token>,
699        _balances: &Balances,
700    ) -> Result<(), TransitionError> {
701        // The decoder attaches the current block's timestamp to every delta. reCLAMM quotes move
702        // with it, so take it when present and keep the previous one otherwise.
703        if let Some(timestamp) = delta
704            .updated_attributes
705            .get(BLOCK_TIMESTAMP_ATTRIBUTE)
706            .and_then(|raw| raw.as_ref().try_into().ok())
707            .map(u64::from_be_bytes)
708        {
709            self.block_timestamp = timestamp;
710        }
711
712        let engine = create_engine(SHARED_TYCHO_DB.clone(), false)?;
713        let pool = AlloyAddress::from_slice(self.pool_address.as_ref());
714        self.state = vm::refresh_pool_state(&engine, &pool, &self.state, self.block_timestamp)
715            .map_err(TransitionError::SimulationError)?;
716        Ok(())
717    }
718
719    fn clone_box(&self) -> Box<dyn ProtocolSim> {
720        Box::new(self.clone())
721    }
722
723    fn as_any(&self) -> &dyn Any {
724        self
725    }
726
727    fn as_any_mut(&mut self) -> &mut dyn Any {
728        self
729    }
730
731    fn eq(&self, other: &dyn ProtocolSim) -> bool {
732        other
733            .as_any()
734            .downcast_ref::<Self>()
735            .is_some_and(|other| self == other)
736    }
737}
738
739/// `WeightedMath.computeInGivenExactOut` without its own `MAX_OUT_RATIO` guard.
740///
741/// That guard bounds real exact-out swaps; here the formula only inverts `computeOutGivenExactIn`
742/// to find the input a min-balance-derived output ceiling implies. A heavily skewed pool can
743/// legitimately move more than 30% of the output reserve on an exact-in swap.
744fn weighted_in_given_exact_out_unguarded(
745    balance_in: &U256,
746    weight_in: &U256,
747    balance_out: &U256,
748    weight_out: &U256,
749    amount_out: &U256,
750) -> Result<U256, PoolError> {
751    let base = div_up_fixed(balance_out, &(balance_out - amount_out))?;
752    let exponent = div_up_fixed(weight_out, weight_in)?;
753    let power = pow_up_fixed(&base, &exponent)?;
754    let ratio = power - ONE_WAD_SCALED_18;
755    mul_up_fixed(balance_in, &ratio)
756}
757
758/// Converts a live scaled-18 balance back into the token's raw units.
759#[cfg(test)]
760fn raw_balance(
761    base: &balancer_maths_rust::common::types::BasePoolState,
762    index: usize,
763) -> Result<U256, SimulationError> {
764    to_raw_undo_rate_round_down(
765        &base.balances_live_scaled_18[index],
766        &base.scaling_factors[index],
767        &base.token_rates[index],
768    )
769    .map_err(|e| SimulationError::FatalError(format!("balancer_v3 balance rescale failed: {e:?}")))
770}