1use 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
47const WAD: f64 = 1e18;
49const SWAP_GAS: u64 = 210_000;
52const SPOT_PRICE_PROBE_DIVISOR: u64 = 1_000_000;
54const BLOCK_TIMESTAMP_ATTRIBUTE: &str = "block_timestamp";
56const MAX_VAULT_BALANCE: U256 = U256::from_limbs([u64::MAX, u64::MAX, 0, 0]);
59const MAX_TOKEN_OUT_RATIO: U256 = U256::from_limbs([990_000_000_000_000_000, 0, 0, 0]);
62const STABLE_MAX_IMBALANCE_RATIO: U256 = U256::from_limbs([10_000, 0, 0, 0]);
67
68#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76pub struct BalancerV3State {
77 pool_address: Bytes,
79 tokens: Vec<Bytes>,
82 min_token_balances: Vec<U256>,
86 block_timestamp: u64,
89 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 #[cfg(test)]
106 pub(super) fn token_addresses(&self) -> &[Bytes] {
107 &self.tokens
108 }
109
110 #[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 #[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 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 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 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(&input, &self.state, self.pool_impl()?.as_ref(), &DefaultHook::new(), None)
186 }
187
188 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 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 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 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 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 return Ok(ratio_cap);
368 };
369
370 if balances[index_in] + U256::from(1) < min_in {
373 return Ok(U256::ZERO);
374 }
375 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 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 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 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 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 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 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("e.address)?;
595 let pool_base = self.state.base();
596 let balances = &pool_base.balances_live_scaled_18;
597
598 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 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 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 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
739fn 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#[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}