Skip to main content

tycho_simulation/evm/protocol/rocketpool/
state.rs

1use std::{any::Any, collections::HashMap};
2
3use alloy::primitives::U256;
4use num_bigint::BigUint;
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};
15use tycho_ethereum::BytesCodec;
16
17use crate::evm::protocol::{
18    rocketpool::ETH_ADDRESS,
19    safe_math::{safe_add_u256, safe_sub_u256},
20    u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
21    utils::solidity_math::mul_div,
22};
23
24const DEPOSIT_FEE_BASE: u128 = 1_000_000_000_000_000_000; // 1e18
25
26/// 32 ETH — the hardcoded amount every megapool queue entry requests.
27const FULL_DEPOSIT_VALUE: u128 = 32_000_000_000_000_000_000u128;
28
29// The names of the constants reflect the exact method from the tenderly log.
30const BASE_DEPOSIT_GAS: u64 = 209_000;
31const RETH_MINT_GAS: u64 = 50_000;
32const VAULT_DEPOSIT_OR_EXCESS_GAS: u64 = 20_000;
33const ASSIGN_DEPOSITS_BASE_GAS: u64 = 20_000;
34// peekItem + withdrawEther + assignFunds + dequeueItem
35const GAS_PER_MEGAPOOL_ASSIGNMENT: u64 = 120_000;
36const BASE_WITHDRAWAL_GAS: u64 = 134_000;
37
38#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
39pub struct RocketpoolState {
40    pub reth_supply: U256,
41    pub total_eth: U256,
42    /// ETH available in the deposit pool contract
43    pub deposit_contract_balance: U256,
44    /// ETH available in the rETH contract
45    pub reth_contract_liquidity: U256,
46    /// Deposit fee as %, scaled by DEPOSIT_FEE_BASE, such as 500_000_000_000_000 represents 0.05%
47    /// fee.
48    pub deposit_fee: U256,
49    pub deposits_enabled: bool,
50    pub min_deposit_amount: U256,
51    pub max_deposit_pool_size: U256,
52    /// Whether assigning deposits is enabled (allows using queue capacity)
53    pub deposit_assigning_enabled: bool,
54    /// Maximum number of assignments per deposit
55    pub deposit_assign_maximum: U256,
56    /// The base number of assignments to try per deposit
57    pub deposit_assign_socialised_maximum: U256,
58    /// Total ETH requested across express + standard megapool queues
59    pub megapool_queue_requested_total: U256,
60    /// Target rETH collateral rate (scaled by 1e18, e.g. 0.01e18 = 1%).
61    /// On-chain: RocketDAOProtocolSettingsNetwork.getTargetRethCollateralRate()
62    pub target_reth_collateral_rate: U256,
63}
64
65impl RocketpoolState {
66    #[expect(
67        clippy::too_many_arguments,
68        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
69    )]
70    pub fn new(
71        reth_supply: U256,
72        total_eth: U256,
73        deposit_contract_balance: U256,
74        reth_contract_liquidity: U256,
75        deposit_fee: U256,
76        deposits_enabled: bool,
77        min_deposit_amount: U256,
78        max_deposit_pool_size: U256,
79        deposit_assigning_enabled: bool,
80        deposit_assign_maximum: U256,
81        deposit_assign_socialised_maximum: U256,
82        megapool_queue_requested_total: U256,
83        target_reth_collateral_rate: U256,
84    ) -> Self {
85        Self {
86            reth_supply,
87            total_eth,
88            deposit_contract_balance,
89            reth_contract_liquidity,
90            deposit_fee,
91            deposits_enabled,
92            min_deposit_amount,
93            max_deposit_pool_size,
94            deposit_assigning_enabled,
95            deposit_assign_maximum,
96            deposit_assign_socialised_maximum,
97            megapool_queue_requested_total,
98            target_reth_collateral_rate,
99        }
100    }
101
102    /// Calculates rETH amount out for a given ETH deposit amount.
103    fn get_reth_value(&self, eth_amount: U256) -> Result<U256, SimulationError> {
104        // fee = ethIn * deposit_fee / DEPOSIT_FEE_BASE
105        let fee = mul_div(eth_amount, self.deposit_fee, U256::from(DEPOSIT_FEE_BASE))?;
106        let net_eth = safe_sub_u256(eth_amount, fee)?;
107        // rethOut = netEth * rethSupply / totalEth
108        mul_div(net_eth, self.reth_supply, self.total_eth)
109    }
110
111    /// Calculates ETH amount out for a given rETH burn amount.
112    fn get_eth_value(&self, reth_amount: U256) -> Result<U256, SimulationError> {
113        // ethOut = rethIn * totalEth / rethSupply
114        mul_div(reth_amount, self.total_eth, self.reth_supply)
115    }
116
117    fn is_depositing_eth(token_in: &Bytes) -> bool {
118        token_in.as_ref() == ETH_ADDRESS
119    }
120
121    fn assert_deposits_enabled(&self) -> Result<(), SimulationError> {
122        if !self.deposits_enabled {
123            Err(SimulationError::RecoverableError(
124                "Deposits are currently disabled in Rocketpool".to_string(),
125            ))
126        } else {
127            Ok(())
128        }
129    }
130
131    /// Returns the maximum deposit capacity considering both the base pool size
132    /// and the megapool queue capacity (if deposit_assigning_enabled).
133    ///
134    /// Note: we only model megapool queues here. The legacy minipool queues were
135    /// fully drained before the Saturn (v1.4) upgrade activated, and deposits into
136    /// them are disabled, so their capacity is always zero.
137    fn get_max_deposit_capacity(&self) -> Result<U256, SimulationError> {
138        if self.deposit_assigning_enabled {
139            safe_add_u256(self.max_deposit_pool_size, self.megapool_queue_requested_total)
140        } else {
141            Ok(self.max_deposit_pool_size)
142        }
143    }
144
145    /// Returns the excess balance available for withdrawals from the deposit pool.
146    ///
147    /// ETH requested for queued megapool entries is reserved and cannot be withdrawn.
148    /// Only the surplus above queue requested is available.
149    fn get_deposit_pool_excess_balance(&self) -> Result<U256, SimulationError> {
150        if self.megapool_queue_requested_total >= self.deposit_contract_balance {
151            Ok(U256::ZERO)
152        } else {
153            safe_sub_u256(self.deposit_contract_balance, self.megapool_queue_requested_total)
154        }
155    }
156
157    /// Returns total available liquidity for withdrawals.
158    /// This is the sum of reth_contract_liquidity and the deposit pool excess balance.
159    fn get_total_available_for_withdrawal(&self) -> Result<U256, SimulationError> {
160        let deposit_pool_excess = self.get_deposit_pool_excess_balance()?;
161        safe_add_u256(self.reth_contract_liquidity, deposit_pool_excess)
162    }
163
164    /// Computes how `processDeposit()` routes deposited ETH between the rETH contract
165    /// (collateral buffer) and the deposit pool vault.
166    ///
167    /// Returns `(to_reth_contract, to_deposit_vault)`.
168    fn compute_deposit_routing(
169        &self,
170        deposit_amount: U256,
171    ) -> Result<(U256, U256), SimulationError> {
172        // target_collateral = total_eth * target_reth_collateral_rate / 1e18
173        let target_collateral = mul_div(
174            self.total_eth,
175            self.target_reth_collateral_rate,
176            U256::from(DEPOSIT_FEE_BASE),
177        )?;
178        // Fill the rETH contract up to its target, send the rest to the deposit vault.
179        let shortfall = target_collateral.saturating_sub(self.reth_contract_liquidity);
180        let to_reth = deposit_amount.min(shortfall);
181        let to_vault = deposit_amount - to_reth;
182        Ok((to_reth, to_vault))
183    }
184
185    /// Calculates ETH assigned from the deposit pool to megapool queue entries.
186    ///
187    /// Three constraints bound assignment:
188    ///   1. Count cap:    floor(deposit / 32 ETH) + socialisedMax, ≤ deposit_assign_maximum
189    ///   2. Vault cap:    floor(deposit_contract_balance / 32 ETH)
190    ///   3. Queue depth:  floor(megapool_queue_requested_total / 32 ETH)
191    ///
192    /// The minimum of these three gives the number of entries assigned.
193    /// Total ETH assigned = entries × 32 ETH.
194    fn calculate_assign_deposits(&self, deposit_amount: U256) -> (U256, u64) {
195        if !self.deposit_assigning_enabled ||
196            self.megapool_queue_requested_total
197                .is_zero()
198        {
199            return (U256::ZERO, 0);
200        }
201
202        let full_deposit_value = U256::from(FULL_DEPOSIT_VALUE);
203
204        // Constraint 1: count cap
205        let scaling_count = deposit_amount / full_deposit_value;
206        let count_cap = (self.deposit_assign_socialised_maximum + scaling_count)
207            .min(self.deposit_assign_maximum);
208
209        // Constraint 2: vault balance
210        let vault_cap = self.deposit_contract_balance / full_deposit_value;
211
212        // Constraint 3: queue depth
213        let queue_entries = self.megapool_queue_requested_total / full_deposit_value;
214
215        // Entries assigned = min of all three constraints
216        let entries = count_cap
217            .min(vault_cap)
218            .min(queue_entries);
219
220        (entries * full_deposit_value, entries.try_into().unwrap_or(u64::MAX))
221    }
222}
223
224#[typetag::serde]
225impl ProtocolSim for RocketpoolState {
226    #[expect(
227        clippy::unimplemented,
228        reason = "fee() returns no error and the trait documents the panic for asymmetric fees"
229    )]
230    fn fee(&self) -> f64 {
231        unimplemented!("Rocketpool has asymmetric fees; use spot_price or get_amount_out instead")
232    }
233
234    fn spot_price(&self, _base: &Token, quote: &Token) -> Result<f64, SimulationError> {
235        // As we are computing the amount of quote needed to buy 1 base, we check the quote token.
236        let is_depositing_eth = RocketpoolState::is_depositing_eth(&quote.address);
237
238        // As the protocol has no slippage, we can use a fixed amount for spot price calculation.
239        // We compute how much base we get for 1 quote, then invert to get quote needed for 1 base.
240        let amount = U256::from(1e18);
241
242        let base_per_quote = if is_depositing_eth {
243            // base=rETH, quote=ETH: compute rETH for given ETH
244            self.assert_deposits_enabled()?;
245            self.get_reth_value(amount)?
246        } else {
247            // base=ETH, quote=rETH: compute ETH for given rETH
248            self.get_eth_value(amount)?
249        };
250
251        let base_per_quote = u256_to_f64(base_per_quote)? / 1e18;
252        // Invert to get how much quote needed to buy 1 base
253        Ok(1.0 / base_per_quote)
254    }
255
256    fn get_amount_out(
257        &self,
258        amount_in: BigUint,
259        token_in: &Token,
260        _token_out: &Token,
261    ) -> Result<GetAmountOutResult, SimulationError> {
262        let amount_in = biguint_to_u256(&amount_in);
263        let is_depositing_eth = RocketpoolState::is_depositing_eth(&token_in.address);
264
265        let amount_out = if is_depositing_eth {
266            self.assert_deposits_enabled()?;
267
268            if amount_in < self.min_deposit_amount {
269                return Err(SimulationError::InvalidInput(
270                    format!(
271                        "Deposit amount {} is less than the minimum deposit of {}",
272                        amount_in, self.min_deposit_amount
273                    ),
274                    None,
275                ));
276            }
277
278            let capacity_needed = safe_add_u256(self.deposit_contract_balance, amount_in)?;
279            let max_capacity = self.get_max_deposit_capacity()?;
280            if capacity_needed > max_capacity {
281                return Err(SimulationError::InvalidInput(
282                    format!(
283                        "Deposit would exceed maximum pool size (capacity needed: {}, max: {})",
284                        capacity_needed, max_capacity
285                    ),
286                    None,
287                ));
288            }
289
290            self.get_reth_value(amount_in)?
291        } else {
292            let eth_out = self.get_eth_value(amount_in)?;
293
294            let total_available = self.get_total_available_for_withdrawal()?;
295            if eth_out > total_available {
296                return Err(SimulationError::RecoverableError(format!(
297                    "Withdrawal {} exceeds available liquidity {}",
298                    eth_out, total_available
299                )));
300            }
301
302            eth_out
303        };
304
305        let mut new_state = self.clone();
306        let mut gas_used = 0;
307
308        // Note: total_eth and reth_supply are not updated as they are managed by an oracle.
309        if is_depositing_eth {
310            gas_used += BASE_DEPOSIT_GAS;
311
312            // route ETH between rETH collateral buffer and vault.
313            let (to_reth, to_vault) = new_state.compute_deposit_routing(amount_in)?;
314            new_state.reth_contract_liquidity =
315                safe_add_u256(new_state.reth_contract_liquidity, to_reth)?;
316            new_state.deposit_contract_balance =
317                safe_add_u256(new_state.deposit_contract_balance, to_vault)?;
318            if to_reth > U256::ZERO {
319                gas_used += RETH_MINT_GAS;
320            }
321
322            if to_vault > U256::ZERO {
323                gas_used += VAULT_DEPOSIT_OR_EXCESS_GAS;
324            }
325
326            // Assign deposits: dequeue megapool entries and send ETH from vault to validators.
327            // Both the vault balance and the queue requested are reduced by the same amount.
328            let (eth_assigned, entries) = new_state.calculate_assign_deposits(amount_in);
329
330            if entries > 0 {
331                gas_used += ASSIGN_DEPOSITS_BASE_GAS;
332                gas_used += entries * GAS_PER_MEGAPOOL_ASSIGNMENT;
333            }
334
335            if eth_assigned > U256::ZERO {
336                new_state.deposit_contract_balance =
337                    safe_sub_u256(new_state.deposit_contract_balance, eth_assigned)?;
338                new_state.megapool_queue_requested_total =
339                    safe_sub_u256(new_state.megapool_queue_requested_total, eth_assigned)?;
340            }
341        } else {
342            gas_used = BASE_WITHDRAWAL_GAS;
343            // Withdraw from rETH contract first, spill remainder into deposit pool.
344            let needed_from_deposit_pool =
345                amount_out.saturating_sub(new_state.reth_contract_liquidity);
346            new_state.reth_contract_liquidity = new_state
347                .reth_contract_liquidity
348                .saturating_sub(amount_out);
349            new_state.deposit_contract_balance =
350                safe_sub_u256(new_state.deposit_contract_balance, needed_from_deposit_pool)?;
351        }
352
353        // The ETH withdrawal gas estimation assumes a best case scenario when there is sufficient
354        // liquidity in the rETH contract. Note that there has never been a situation during a
355        // withdrawal when this was not the case, hence the simplified gas estimation.
356
357        Ok(GetAmountOutResult::new(
358            u256_to_biguint(amount_out),
359            BigUint::from(gas_used),
360            Box::new(new_state),
361        ))
362    }
363
364    fn get_limits(
365        &self,
366        sell_token: Bytes,
367        _buy_token: Bytes,
368    ) -> Result<(BigUint, BigUint), SimulationError> {
369        let is_depositing_eth = Self::is_depositing_eth(&sell_token);
370
371        if is_depositing_eth {
372            // ETH -> rETH: max sell = max_deposit_capacity - deposit_contract_balance
373            let max_capacity = self.get_max_deposit_capacity()?;
374            let max_eth_sell = safe_sub_u256(max_capacity, self.deposit_contract_balance)?;
375            let max_reth_buy = self.get_reth_value(max_eth_sell)?;
376            Ok((u256_to_biguint(max_eth_sell), u256_to_biguint(max_reth_buy)))
377        } else {
378            // rETH -> ETH: max buy = total available for withdrawal
379            let max_eth_buy = self.get_total_available_for_withdrawal()?;
380            let max_reth_sell = mul_div(max_eth_buy, self.reth_supply, self.total_eth)?;
381            Ok((u256_to_biguint(max_reth_sell), u256_to_biguint(max_eth_buy)))
382        }
383    }
384
385    fn delta_transition(
386        &mut self,
387        delta: ProtocolStateDelta,
388        _tokens: &HashMap<Bytes, Token>,
389        _balances: &Balances,
390    ) -> Result<(), TransitionError> {
391        self.total_eth = delta
392            .updated_attributes
393            .get("total_eth")
394            .map_or(self.total_eth, U256::from_bytes);
395        self.reth_supply = delta
396            .updated_attributes
397            .get("reth_supply")
398            .map_or(self.reth_supply, U256::from_bytes);
399        self.deposit_contract_balance = delta
400            .updated_attributes
401            .get("deposit_contract_balance")
402            .map_or(self.deposit_contract_balance, U256::from_bytes);
403        self.reth_contract_liquidity = delta
404            .updated_attributes
405            .get("reth_contract_liquidity")
406            .map_or(self.reth_contract_liquidity, U256::from_bytes);
407        self.deposits_enabled = delta
408            .updated_attributes
409            .get("deposits_enabled")
410            .map_or(self.deposits_enabled, |val| !U256::from_bytes(val).is_zero());
411        self.deposit_assigning_enabled = delta
412            .updated_attributes
413            .get("deposit_assigning_enabled")
414            .map_or(self.deposit_assigning_enabled, |val| !U256::from_bytes(val).is_zero());
415        self.deposit_fee = delta
416            .updated_attributes
417            .get("deposit_fee")
418            .map_or(self.deposit_fee, U256::from_bytes);
419        self.min_deposit_amount = delta
420            .updated_attributes
421            .get("min_deposit_amount")
422            .map_or(self.min_deposit_amount, U256::from_bytes);
423        self.max_deposit_pool_size = delta
424            .updated_attributes
425            .get("max_deposit_pool_size")
426            .map_or(self.max_deposit_pool_size, U256::from_bytes);
427        self.deposit_assign_maximum = delta
428            .updated_attributes
429            .get("deposit_assign_maximum")
430            .map_or(self.deposit_assign_maximum, U256::from_bytes);
431        self.deposit_assign_socialised_maximum = delta
432            .updated_attributes
433            .get("deposit_assign_socialised_maximum")
434            .map_or(self.deposit_assign_socialised_maximum, U256::from_bytes);
435        self.megapool_queue_requested_total = delta
436            .updated_attributes
437            .get("megapool_queue_requested_total")
438            .map_or(self.megapool_queue_requested_total, U256::from_bytes);
439        self.target_reth_collateral_rate = delta
440            .updated_attributes
441            .get("target_reth_collateral_rate")
442            .map_or(self.target_reth_collateral_rate, U256::from_bytes);
443
444        Ok(())
445    }
446
447    fn clone_box(&self) -> Box<dyn ProtocolSim> {
448        Box::new(self.clone())
449    }
450
451    fn as_any(&self) -> &dyn Any {
452        self
453    }
454
455    fn as_any_mut(&mut self) -> &mut dyn Any {
456        self
457    }
458
459    fn eq(&self, other: &dyn ProtocolSim) -> bool {
460        if let Some(other_state) = other.as_any().downcast_ref::<Self>() {
461            self == other_state
462        } else {
463            false
464        }
465    }
466
467    fn query_pool_swap(
468        &self,
469        params: &tycho_common::simulation::protocol_sim::QueryPoolSwapParams,
470    ) -> Result<tycho_common::simulation::protocol_sim::PoolSwap, SimulationError> {
471        crate::evm::query_pool_swap::query_pool_swap(self, params)
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use std::{
478        collections::{HashMap, HashSet},
479        str::FromStr,
480    };
481
482    use approx::assert_ulps_eq;
483    use num_bigint::BigUint;
484    use rstest::rstest;
485    use tycho_common::{
486        dto::ProtocolStateDelta,
487        hex_bytes::Bytes,
488        models::{token::Token, Chain},
489        simulation::{
490            errors::SimulationError,
491            protocol_sim::{Balances, ProtocolSim},
492        },
493    };
494
495    use super::*;
496
497    /// Helper function to create a RocketpoolState with easy-to-compute defaults for testing.
498    /// - Exchange rate: 1 rETH = 2 ETH (100 rETH backed by 200 ETH)
499    /// - Deposit fee: 40%
500    /// - Deposit contract balance: 50 ETH
501    /// - rETH contract liquidity: 0 ETH
502    /// - Max pool size: 1000 ETH
503    /// - Assign deposits enabled: false
504    /// - Target rETH collateral rate: 1% (0.01e18)
505    fn create_state() -> RocketpoolState {
506        RocketpoolState::new(
507            U256::from(100e18), // reth_supply: 100 rETH
508            U256::from(200e18), /* total_eth: 200 ETH (1 rETH =
509                                 * 2 ETH) */
510            U256::from(50e18), // deposit_contract_balance: 50 ETH
511            U256::ZERO,        // reth_contract_liquidity: 0 ETH
512            U256::from(400_000_000_000_000_000u64), // deposit_fee: 40% (0.4e18)
513            true,              // deposits_enabled
514            U256::ZERO,        // min_deposit_amount
515            U256::from(1000e18), // max_deposit_pool_size: 1000 ETH
516            false,             // deposit_assigning_enabled
517            U256::ZERO,        // deposit_assign_maximum
518            U256::ZERO,        // deposit_assign_socialised_maximum
519            U256::ZERO,        // megapool_queue_requested_total
520            U256::from(10_000_000_000_000_000u64), // target_reth_collateral_rate: 1%
521        )
522    }
523
524    fn eth_token() -> Token {
525        Token::new(&Bytes::from(ETH_ADDRESS), "ETH", 18, 0, &[Some(100_000)], Chain::Ethereum, 100)
526    }
527
528    fn reth_token() -> Token {
529        Token::new(
530            &Bytes::from_str("0xae78736Cd615f374D3085123A210448E74Fc6393").unwrap(),
531            "rETH",
532            18,
533            0,
534            &[Some(100_000)],
535            Chain::Ethereum,
536            100,
537        )
538    }
539
540    // ============ Max Deposit Capacity Tests ============
541
542    #[test]
543    fn test_max_capacity_assign_disabled() {
544        let state = create_state();
545        assert_eq!(
546            state
547                .get_max_deposit_capacity()
548                .unwrap(),
549            U256::from(1000e18)
550        );
551    }
552
553    #[test]
554    fn test_max_capacity_assign_enabled_empty_queue() {
555        let mut state = create_state();
556        state.deposit_assigning_enabled = true;
557        assert_eq!(
558            state
559                .get_max_deposit_capacity()
560                .unwrap(),
561            U256::from(1000e18)
562        );
563    }
564
565    #[test]
566    fn test_max_capacity_assign_enabled_with_queue() {
567        let mut state = create_state();
568        state.deposit_assigning_enabled = true;
569        state.megapool_queue_requested_total = U256::from(500e18);
570        // 1000 + 500 = 1500 ETH
571        assert_eq!(
572            state
573                .get_max_deposit_capacity()
574                .unwrap(),
575            U256::from(1500e18)
576        );
577    }
578
579    // ============ Deposit Routing Tests ============
580
581    #[rstest]
582    #[case::all_to_reth(
583        U256::ZERO,  // reth_contract_liquidity
584        U256::from(10_000_000_000_000_000u64),  // target_reth_collateral_rate: 1%
585        1_000_000_000_000_000_000u128,  // deposit: 1 ETH
586        1_000_000_000_000_000_000u128,  // expected to_reth
587        0u128,  // expected to_vault
588    )]
589    // shortfall (2 ETH) < deposit (10 ETH) → split
590    #[case::split(
591        U256::ZERO,
592        U256::from(10_000_000_000_000_000u64),
593        10_000_000_000_000_000_000u128,  // deposit: 10 ETH
594        2_000_000_000_000_000_000u128,   // to_reth: 2 ETH (shortfall)
595        8_000_000_000_000_000_000u128,   // to_vault: 8 ETH
596    )]
597    // no shortfall (liquidity 10 ETH > target 2 ETH) → all to vault
598    #[case::all_to_vault(
599        U256::from(10_000_000_000_000_000_000u128),  // liquidity: 10 ETH > 2 ETH target
600        U256::from(10_000_000_000_000_000u64),
601        5_000_000_000_000_000_000u128,  // deposit: 5 ETH
602        0u128,
603        5_000_000_000_000_000_000u128,
604    )]
605    // zero collateral rate → all to vault
606    #[case::zero_collateral_rate(
607        U256::ZERO,
608        U256::ZERO,  // target_reth_collateral_rate: 0%
609        5_000_000_000_000_000_000u128,
610        0u128,
611        5_000_000_000_000_000_000u128,
612    )]
613    fn test_deposit_routing(
614        #[case] reth_contract_liquidity: U256,
615        #[case] target_reth_collateral_rate: U256,
616        #[case] deposit: u128,
617        #[case] expected_to_reth: u128,
618        #[case] expected_to_vault: u128,
619    ) {
620        let mut state = create_state();
621        state.reth_contract_liquidity = reth_contract_liquidity;
622        state.target_reth_collateral_rate = target_reth_collateral_rate;
623
624        let (to_reth, to_vault) = state
625            .compute_deposit_routing(U256::from(deposit))
626            .unwrap();
627
628        assert_eq!(to_reth, U256::from(expected_to_reth));
629        assert_eq!(to_vault, U256::from(expected_to_vault));
630    }
631
632    // ============ Delta Transition Tests ============
633
634    #[test]
635    fn test_delta_transition_basic() {
636        let mut state = create_state();
637
638        let attributes: HashMap<String, Bytes> = [
639            ("total_eth", U256::from(300u64)),
640            ("reth_supply", U256::from(150u64)),
641            ("deposit_contract_balance", U256::from(100u64)),
642            ("reth_contract_liquidity", U256::from(20u64)),
643        ]
644        .into_iter()
645        .map(|(k, v)| (k.to_string(), Bytes::from(v.to_be_bytes_vec())))
646        .collect();
647
648        let delta = ProtocolStateDelta {
649            component_id: "Rocketpool".to_owned(),
650            updated_attributes: attributes,
651            deleted_attributes: HashSet::new(),
652        };
653
654        state
655            .delta_transition(delta, &HashMap::new(), &Balances::default())
656            .unwrap();
657
658        assert_eq!(state.total_eth, U256::from(300u64));
659        assert_eq!(state.reth_supply, U256::from(150u64));
660        assert_eq!(state.deposit_contract_balance, U256::from(100u64));
661        assert_eq!(state.reth_contract_liquidity, U256::from(20u64));
662    }
663
664    #[test]
665    fn test_delta_transition_megapool_fields() {
666        let mut state = create_state();
667
668        let attributes: HashMap<String, Bytes> = [
669            ("megapool_queue_requested_total", U256::from(1000u64)),
670            ("target_reth_collateral_rate", U256::from(20_000_000_000_000_000u64)),
671        ]
672        .into_iter()
673        .map(|(k, v)| (k.to_string(), Bytes::from(v.to_be_bytes_vec())))
674        .collect();
675
676        let delta = ProtocolStateDelta {
677            component_id: "Rocketpool".to_owned(),
678            updated_attributes: attributes,
679            deleted_attributes: HashSet::new(),
680        };
681
682        state
683            .delta_transition(delta, &HashMap::new(), &Balances::default())
684            .unwrap();
685
686        assert_eq!(state.megapool_queue_requested_total, U256::from(1000u64));
687        assert_eq!(state.target_reth_collateral_rate, U256::from(20_000_000_000_000_000u64));
688    }
689
690    // ============ Spot Price Tests ============
691
692    #[test]
693    fn test_spot_price_deposit() {
694        let state = create_state();
695        let price = state
696            .spot_price(&eth_token(), &reth_token())
697            .unwrap();
698        assert_ulps_eq!(price, 0.5);
699    }
700
701    #[test]
702    fn test_spot_price_withdraw() {
703        let state = create_state();
704        let price = state
705            .spot_price(&reth_token(), &eth_token())
706            .unwrap();
707        assert_ulps_eq!(price, 1.0 / 0.3);
708    }
709
710    /// Validate withdrawal spot price against on-chain getEthValue(1e18) at block 24480104.
711    /// On-chain: getEthValue(1e18) = 1157737589816937166 → 1 rETH = 1.1577... ETH.
712    /// Our spot_price(ETH, rETH) should return 1/1.1577... = 0.8637... (rETH per ETH).
713    #[test]
714    fn test_live_spot_price_withdrawal() {
715        let state = create_state_at_block_24480104();
716        let price = state
717            .spot_price(&eth_token(), &reth_token())
718            .unwrap();
719
720        // Expected from on-chain getEthValue(1e18) = 1157737589816937166
721        let on_chain_eth_value = 1_157_737_589_816_937_166f64;
722        let expected = 1e18 / on_chain_eth_value;
723        assert_ulps_eq!(price, expected, max_ulps = 10);
724    }
725
726    /// Validate deposit spot price against on-chain getRethValue(1e18) at block 24480104.
727    /// On-chain: getRethValue(1e18) = 863753590447141981 (no deposit fee).
728    /// Our spot_price(rETH, ETH) applies the 0.05% deposit fee on top.
729    #[test]
730    fn test_live_spot_price_deposit() {
731        use crate::evm::protocol::utils::add_fee_markup;
732
733        let state = create_state_at_block_24480104();
734        let price = state
735            .spot_price(&reth_token(), &eth_token())
736            .unwrap();
737
738        // On-chain getRethValue(1e18) = 863753590447141981 (no fee)
739        // → exchange rate without fee = 1e18 / 863753590447141981
740        let on_chain_reth_value = 863_753_590_447_141_981f64;
741        let rate_without_fee = 1e18 / on_chain_reth_value;
742        let fee = 500_000_000_000_000f64 / DEPOSIT_FEE_BASE as f64; // 0.05%
743        let expected = add_fee_markup(rate_without_fee, fee);
744        assert_ulps_eq!(price, expected, max_ulps = 10);
745    }
746
747    #[test]
748    fn test_fee_panics() {
749        let state = create_state();
750        let result = std::panic::catch_unwind(|| state.fee());
751        assert!(result.is_err());
752    }
753
754    // ============ Get Limits Tests ============
755
756    #[test]
757    fn test_limits_deposit() {
758        let state = create_state();
759        let (max_sell, max_buy) = state
760            .get_limits(eth_token().address, reth_token().address)
761            .unwrap();
762        // max_sell = 1000 - 50 = 950 ETH
763        assert_eq!(max_sell, BigUint::from(950_000_000_000_000_000_000u128));
764        // max_buy = 950 * 0.6 * 100/200 = 285 rETH
765        assert_eq!(max_buy, BigUint::from(285_000_000_000_000_000_000u128));
766    }
767
768    #[test]
769    fn test_limits_withdrawal() {
770        let state = create_state();
771        let (max_sell, max_buy) = state
772            .get_limits(reth_token().address, eth_token().address)
773            .unwrap();
774        // max_buy = liquidity = 50 ETH
775        assert_eq!(max_buy, BigUint::from(50_000_000_000_000_000_000u128));
776        // max_sell = 50 * 100/200 = 25 rETH
777        assert_eq!(max_sell, BigUint::from(25_000_000_000_000_000_000u128));
778    }
779
780    #[test]
781    fn test_limits_with_megapool_queue() {
782        let mut state = create_state();
783        state.max_deposit_pool_size = U256::from(100e18);
784        state.deposit_assigning_enabled = true;
785        state.megapool_queue_requested_total = U256::from(62e18);
786
787        let (max_sell, _) = state
788            .get_limits(eth_token().address, reth_token().address)
789            .unwrap();
790        // max_capacity = 100 + 62 = 162 ETH; max_sell = 162 - 50 = 112 ETH
791        assert_eq!(max_sell, BigUint::from(112_000_000_000_000_000_000u128));
792    }
793
794    // ============ Limits Boundary Consistency Tests ============
795
796    #[test]
797    fn test_limits_deposit_boundary_accepted() {
798        let mut state = create_state();
799        state.deposit_assigning_enabled = true;
800        state.megapool_queue_requested_total = U256::from(64e18);
801
802        let (max_sell, _) = state
803            .get_limits(eth_token().address, reth_token().address)
804            .unwrap();
805
806        // Depositing exactly max_sell should succeed
807        let res = state.get_amount_out(max_sell.clone(), &eth_token(), &reth_token());
808        assert!(res.is_ok(), "max_sell should be accepted");
809
810        // Depositing max_sell + 1 wei should fail
811        let over = max_sell + BigUint::from(1u64);
812        let res = state.get_amount_out(over, &eth_token(), &reth_token());
813        assert!(matches!(res, Err(SimulationError::InvalidInput(_, _))));
814    }
815
816    #[test]
817    fn test_limits_withdrawal_boundary_accepted() {
818        let mut state = create_state();
819        state.reth_contract_liquidity = U256::from(30e18);
820
821        let (max_sell, _) = state
822            .get_limits(reth_token().address, eth_token().address)
823            .unwrap();
824
825        // Withdrawing exactly max_sell should succeed
826        let res = state.get_amount_out(max_sell.clone(), &reth_token(), &eth_token());
827        assert!(res.is_ok(), "max_sell should be accepted");
828
829        // Withdrawing max_sell + 1 wei should fail
830        let over = max_sell + BigUint::from(1u64);
831        let res = state.get_amount_out(over, &reth_token(), &eth_token());
832        assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
833    }
834
835    // ============ Get Amount Out - Happy Path Tests ============
836
837    #[test]
838    fn test_deposit_eth() {
839        let state = create_state();
840        // Deposit 10 ETH: fee=4, net=6 → 6*100/200 = 3 rETH
841        let res = state
842            .get_amount_out(
843                BigUint::from(10_000_000_000_000_000_000u128),
844                &eth_token(),
845                &reth_token(),
846            )
847            .unwrap();
848
849        assert_eq!(res.amount, BigUint::from(3_000_000_000_000_000_000u128));
850
851        // Collateral routing: target = 200e18 * 1e16 / 1e18 = 2e18.
852        // Shortfall = 2e18 - 0 = 2e18. to_reth = min(10, 2) = 2, to_vault = 8.
853        // deposit_contract_balance = 50 + 8 = 58 ETH
854        let new_state = res
855            .new_state
856            .as_any()
857            .downcast_ref::<RocketpoolState>()
858            .unwrap();
859        assert_eq!(new_state.deposit_contract_balance, U256::from(58e18));
860        assert_eq!(new_state.reth_contract_liquidity, U256::from(2e18));
861    }
862
863    #[test]
864    fn test_withdraw_reth() {
865        let state = create_state();
866        // Withdraw 10 rETH: 10*200/100 = 20 ETH
867        let res = state
868            .get_amount_out(
869                BigUint::from(10_000_000_000_000_000_000u128),
870                &reth_token(),
871                &eth_token(),
872            )
873            .unwrap();
874
875        assert_eq!(res.amount, BigUint::from(20_000_000_000_000_000_000u128));
876
877        let new_state = res
878            .new_state
879            .as_any()
880            .downcast_ref::<RocketpoolState>()
881            .unwrap();
882        assert_eq!(new_state.deposit_contract_balance, U256::from(30e18));
883    }
884
885    // ============ Get Amount Out - Error Cases Tests ============
886
887    #[test]
888    fn test_deposit_disabled() {
889        let mut state = create_state();
890        state.deposits_enabled = false;
891        let res = state.get_amount_out(BigUint::from(10u64), &eth_token(), &reth_token());
892        assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
893    }
894
895    #[test]
896    fn test_deposit_below_minimum() {
897        let mut state = create_state();
898        state.min_deposit_amount = U256::from(100u64);
899        let res = state.get_amount_out(BigUint::from(50u64), &eth_token(), &reth_token());
900        assert!(matches!(res, Err(SimulationError::InvalidInput(_, _))));
901    }
902
903    #[test]
904    fn test_deposit_exceeds_max_pool() {
905        let mut state = create_state();
906        state.max_deposit_pool_size = U256::from(60e18);
907        let res = state.get_amount_out(
908            BigUint::from(20_000_000_000_000_000_000u128),
909            &eth_token(),
910            &reth_token(),
911        );
912        assert!(matches!(res, Err(SimulationError::InvalidInput(_, _))));
913    }
914
915    #[test]
916    fn test_withdrawal_insufficient_liquidity() {
917        let state = create_state();
918        let res = state.get_amount_out(
919            BigUint::from(30_000_000_000_000_000_000u128),
920            &reth_token(),
921            &eth_token(),
922        );
923        assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
924    }
925
926    #[test]
927    fn test_withdrawal_limited_by_queue() {
928        let mut state = create_state();
929        state.deposit_contract_balance = U256::from(100e18);
930        state.megapool_queue_requested_total = U256::from(62e18);
931
932        // excess = 100 - 62 = 38 ETH; try withdraw 20 rETH = 40 ETH > 38
933        let res = state.get_amount_out(
934            BigUint::from(20_000_000_000_000_000_000u128),
935            &reth_token(),
936            &eth_token(),
937        );
938        assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
939
940        // Withdraw 15 rETH = 30 ETH <= 38 should work
941        let res = state
942            .get_amount_out(
943                BigUint::from(15_000_000_000_000_000_000u128),
944                &reth_token(),
945                &eth_token(),
946            )
947            .unwrap();
948        assert_eq!(res.amount, BigUint::from(30_000_000_000_000_000_000u128));
949    }
950
951    #[test]
952    fn test_withdrawal_uses_both_pools() {
953        let mut state = create_state();
954        state.reth_contract_liquidity = U256::from(10e18);
955        state.deposit_contract_balance = U256::from(50e18);
956
957        // Withdraw 15 rETH = 30 ETH (more than reth_contract_liquidity of 10 ETH)
958        let res = state
959            .get_amount_out(
960                BigUint::from(15_000_000_000_000_000_000u128),
961                &reth_token(),
962                &eth_token(),
963            )
964            .unwrap();
965
966        assert_eq!(res.amount, BigUint::from(30_000_000_000_000_000_000u128));
967
968        let new_state = res
969            .new_state
970            .as_any()
971            .downcast_ref::<RocketpoolState>()
972            .unwrap();
973        assert_eq!(new_state.reth_contract_liquidity, U256::ZERO);
974        assert_eq!(new_state.deposit_contract_balance, U256::from(30e18));
975    }
976
977    // ============ Assign Deposits Tests ============
978
979    #[test]
980    fn test_assign_deposits_with_queue() {
981        let mut state = create_state();
982        state.deposit_contract_balance = U256::from(200e18);
983        state.reth_contract_liquidity = U256::from(10e18); // above 1% target, no shortfall
984        state.deposit_assigning_enabled = true;
985        state.deposit_assign_maximum = U256::from(90u64);
986        state.megapool_queue_requested_total = U256::from(128e18); // 4 entries of 32 ETH
987
988        // Deposit 100 ETH
989        let res = state
990            .get_amount_out(
991                BigUint::from(100_000_000_000_000_000_000u128),
992                &eth_token(),
993                &reth_token(),
994            )
995            .unwrap();
996
997        let new_state = res
998            .new_state
999            .as_any()
1000            .downcast_ref::<RocketpoolState>()
1001            .unwrap();
1002        // Collateral routing: target = 200e18 * 0.01 = 2e18.
1003        // Shortfall = 2e18 - 10e18 = 0 (already above target). to_reth=0, to_vault=100.
1004        // vault after routing = 200 + 100 = 300 ETH.
1005        //
1006        // Assignment: scaling_count = 100/32 = 3.
1007        // count_cap = min(0 + 3, 90) = 3.
1008        // vault_cap = 300/32 = 9. queue_entries = 128/32 = 4.
1009        // entries = min(3, 9, 4) = 3. assigned = 3 * 32 = 96 ETH.
1010        // vault after = 300 - 96 = 204. queue after = 128 - 96 = 32.
1011        assert_eq!(new_state.deposit_contract_balance, U256::from(204e18));
1012        assert_eq!(new_state.megapool_queue_requested_total, U256::from(32e18));
1013    }
1014
1015    #[test]
1016    fn test_assign_deposits_empty_queue() {
1017        let mut state = create_state();
1018        state.deposit_assigning_enabled = true;
1019
1020        let res = state
1021            .get_amount_out(
1022                BigUint::from(10_000_000_000_000_000_000u128),
1023                &eth_token(),
1024                &reth_token(),
1025            )
1026            .unwrap();
1027
1028        let new_state = res
1029            .new_state
1030            .as_any()
1031            .downcast_ref::<RocketpoolState>()
1032            .unwrap();
1033        // No queue, no assignment. Routing: to_reth=2, to_vault=8. Balance = 50+8 = 58.
1034        assert_eq!(new_state.deposit_contract_balance, U256::from(58e18));
1035    }
1036
1037    #[test]
1038    fn test_assign_deposits_disabled() {
1039        let mut state = create_state();
1040        state.deposit_assigning_enabled = false;
1041        state.megapool_queue_requested_total = U256::from(100e18);
1042
1043        let res = state
1044            .get_amount_out(
1045                BigUint::from(10_000_000_000_000_000_000u128),
1046                &eth_token(),
1047                &reth_token(),
1048            )
1049            .unwrap();
1050
1051        let new_state = res
1052            .new_state
1053            .as_any()
1054            .downcast_ref::<RocketpoolState>()
1055            .unwrap();
1056        // Assign disabled, no assignment. Routing: to_reth=2, to_vault=8. Balance = 50+8 = 58.
1057        assert_eq!(new_state.deposit_contract_balance, U256::from(58e18));
1058    }
1059
1060    /// Full flow: deposit splits between collateral buffer and vault, then assignment drains vault.
1061    /// Exercises the combined routing + assignment path that is unique to Saturn v1.4.
1062    ///
1063    /// Setup: shortfall = 20 ETH, deposit = 100 ETH, vault = 50 ETH, queue = 96 ETH (3 entries).
1064    /// Routing: to_reth = 20 (fills shortfall), to_vault = 80. Vault after = 50 + 80 = 130 ETH.
1065    /// Assignment: scaling_count = 100/32 = 3, count_cap = min(3, 90) = 3.
1066    ///   vault_cap = 130/32 = 4. queue = 96/32 = 3. entries = min(3, 4, 3) = 3. assigned = 96 ETH.
1067    /// Final: vault = 130 - 96 = 34, queue = 96 - 96 = 0, reth_liq = 0 + 20 = 20.
1068    #[test]
1069    fn test_deposit_split_routing_with_assignment() {
1070        let mut state = create_state();
1071        state.reth_contract_liquidity = U256::ZERO;
1072        state.deposit_contract_balance = U256::from(50e18);
1073        state.deposit_assigning_enabled = true;
1074        state.deposit_assign_maximum = U256::from(90u64);
1075        // 3 entries
1076        state.megapool_queue_requested_total = U256::from(96e18);
1077        // target = 200e18 * 10% / 1e18 = 20 ETH → shortfall = 20 - 0 = 20
1078        state.target_reth_collateral_rate = U256::from(100_000_000_000_000_000u64); // 10%
1079
1080        let res = state
1081            .get_amount_out(
1082                BigUint::from(100_000_000_000_000_000_000u128),
1083                &eth_token(),
1084                &reth_token(),
1085            )
1086            .unwrap();
1087
1088        let new_state = res
1089            .new_state
1090            .as_any()
1091            .downcast_ref::<RocketpoolState>()
1092            .unwrap();
1093        assert_eq!(new_state.reth_contract_liquidity, U256::from(20e18));
1094        assert_eq!(new_state.deposit_contract_balance, U256::from(34e18));
1095        assert_eq!(new_state.megapool_queue_requested_total, U256::ZERO);
1096    }
1097
1098    // ============ Assign Deposits — Constraint Unit Tests ============
1099
1100    /// Helper: create a state pre-configured for assignment tests.
1101    /// Deposits enabled, high max, collateral already met (no routing interference).
1102    fn create_assign_state(
1103        deposit_contract_balance: U256,
1104        megapool_queue_requested_total: U256,
1105        deposit_assign_maximum: U256,
1106        deposit_assign_socialised_maximum: U256,
1107    ) -> RocketpoolState {
1108        let mut state = create_state();
1109        state.deposit_assigning_enabled = true;
1110        state.deposit_contract_balance = deposit_contract_balance;
1111        state.megapool_queue_requested_total = megapool_queue_requested_total;
1112        state.deposit_assign_maximum = deposit_assign_maximum;
1113        state.deposit_assign_socialised_maximum = deposit_assign_socialised_maximum;
1114        // Put liquidity above target so routing sends everything to vault
1115        state.reth_contract_liquidity = U256::from(10_000_000_000_000_000_000u128);
1116        state
1117    }
1118
1119    #[rstest]
1120    // Count cap limits: deposit=64 ETH (2 entries), vault=300, queue=128 (4), max=90
1121    // count_cap = min(0 + 2, 90) = 2; vault_cap = 9; queue = 4 → 2 entries
1122    #[case::count_cap_limits(
1123        64_000_000_000_000_000_000u128,   // deposit
1124        300_000_000_000_000_000_000u128,  // vault
1125        128_000_000_000_000_000_000u128,  // queue
1126        90u64,                            // max
1127        0u64,                             // socialised
1128        64_000_000_000_000_000_000u128,   // expected: 2 * 32 ETH
1129    )]
1130    // Vault cap limits: deposit=200 ETH (6 entries), vault=64 (2), queue=192 (6), max=90
1131    // count_cap = 6; vault_cap = 2; queue = 6 → 2 entries
1132    #[case::vault_cap_limits(
1133        200_000_000_000_000_000_000u128,
1134        64_000_000_000_000_000_000u128,
1135        192_000_000_000_000_000_000u128,
1136        90u64,
1137        0u64,
1138        64_000_000_000_000_000_000u128,   // 2 * 32 ETH
1139    )]
1140    // Queue depth limits: deposit=200 ETH (6), vault=300 (9), queue=64 (2), max=90
1141    // count_cap = 6; vault_cap = 9; queue = 2 → 2 entries
1142    #[case::queue_depth_limits(
1143        200_000_000_000_000_000_000u128,
1144        300_000_000_000_000_000_000u128,
1145        64_000_000_000_000_000_000u128,
1146        90u64,
1147        0u64,
1148        64_000_000_000_000_000_000u128,   // 2 * 32 ETH
1149    )]
1150    // Max cap limits: deposit=200 ETH (6), vault=300 (9), queue=192 (6), max=3
1151    // count_cap = min(6, 3) = 3; vault_cap = 9; queue = 6 → 3 entries
1152    #[case::max_cap_limits(
1153        200_000_000_000_000_000_000u128,
1154        300_000_000_000_000_000_000u128,
1155        192_000_000_000_000_000_000u128,
1156        3u64,
1157        0u64,
1158        96_000_000_000_000_000_000u128,   // 3 * 32 ETH
1159    )]
1160    // Socialised max: deposit=10 ETH (<32, scaling=0), socialised=2, vault=200, queue=128, max=90
1161    // count_cap = min(0 + 2, 90) = 2; vault_cap = 6; queue = 4 → 2 entries
1162    #[case::socialised_max(
1163        10_000_000_000_000_000_000u128,
1164        200_000_000_000_000_000_000u128,
1165        128_000_000_000_000_000_000u128,
1166        90u64,
1167        2u64,
1168        64_000_000_000_000_000_000u128,   // 2 * 32 ETH
1169    )]
1170    // Small deposit, no socialised: deposit=10 ETH, socialised=0 → scaling=0, count_cap=0
1171    #[case::small_deposit_no_assignment(
1172        10_000_000_000_000_000_000u128,
1173        200_000_000_000_000_000_000u128,
1174        128_000_000_000_000_000_000u128,
1175        90u64,
1176        0u64,
1177        0u128
1178    )]
1179    // Vault below 32 ETH: deposit=100 ETH, vault=20, queue=128, max=90
1180    // vault_cap = 20/32 = 0 → 0 entries
1181    #[case::vault_below_32(
1182        100_000_000_000_000_000_000u128,
1183        20_000_000_000_000_000_000u128,
1184        128_000_000_000_000_000_000u128,
1185        90u64,
1186        0u64,
1187        0u128
1188    )]
1189    fn test_assign_constraint(
1190        #[case] deposit: u128,
1191        #[case] vault: u128,
1192        #[case] queue: u128,
1193        #[case] max: u64,
1194        #[case] socialised: u64,
1195        #[case] expected_assigned: u128,
1196    ) {
1197        let state = create_assign_state(
1198            U256::from(vault),
1199            U256::from(queue),
1200            U256::from(max),
1201            U256::from(socialised),
1202        );
1203        let (assigned, _gas_used) = state.calculate_assign_deposits(U256::from(deposit));
1204        assert_eq!(assigned, U256::from(expected_assigned));
1205    }
1206
1207    // ============ Live Post-Saturn Transaction Tests ============
1208
1209    /// State at block 24480104 (just before first post-Saturn deposit).
1210    /// Verified against on-chain data via cast calls at this block.
1211    fn create_state_at_block_24480104() -> RocketpoolState {
1212        RocketpoolState::new(
1213            U256::from_str_radix("489a96a246a2e92bbbd1", 16).unwrap(), // reth_supply
1214            U256::from_str_radix("540e645ee4119f4d8b9e", 16).unwrap(), // total_eth
1215            U256::from_str_radix("8dcfa9d0071987bb", 16).unwrap(),     // deposit_contract_balance
1216            U256::from_str_radix("c28d2e1d64f99ea24", 16).unwrap(),    // reth_contract_liquidity
1217            U256::from_str_radix("1c6bf52634000", 16).unwrap(),        // deposit_fee (0.05%)
1218            true,                                                      // deposits_enabled
1219            U256::from_str_radix("2386f26fc10000", 16).unwrap(),       // min_deposit_amount
1220            U256::from_str_radix("4f68ca6d8cd91c6000000", 16).unwrap(), // max_deposit_pool_size
1221            true,                                                      // deposit_assigning_enabled
1222            U256::from(90u64),                                         // deposit_assign_maximum
1223            U256::ZERO, // deposit_assign_socialised_maximum
1224            U256::from_str_radix("4a60532ad51bf000000", 16).unwrap(), /* megapool_queue_requested_total */
1225            U256::from(10_000_000_000_000_000u64), // target_reth_collateral_rate: 1%
1226        )
1227    }
1228
1229    /// Test against real v1.4 deposit transaction.
1230    /// Tx 0xe0f1db165b621cb1e50b629af9d47e064be464fbcc7f2bcba3df1d27dbb916be at block 24480105.
1231    /// User deposited 85 ETH and received 73382345660413064855 rETH (0.05% fee applied).
1232    ///
1233    /// On-chain, the 85 ETH went entirely to the rETH collateral buffer because
1234    /// the collateral shortfall (target ~3965 ETH vs ~224 ETH held) far exceeds 85 ETH.
1235    /// The vault balance (deposit_contract_balance) was unchanged at ~10.22 ETH,
1236    /// which is < 32 ETH so no queue entries were assigned.
1237    #[test]
1238    fn test_live_deposit_post_saturn() {
1239        let state = create_state_at_block_24480104();
1240
1241        let deposit_amount = BigUint::from(85_000_000_000_000_000_000u128);
1242        let res = state
1243            .get_amount_out(deposit_amount, &eth_token(), &reth_token())
1244            .unwrap();
1245
1246        // Output amount: exact match with on-chain result
1247        let expected_reth_out = BigUint::from(73_382_345_660_413_064_855u128);
1248        assert_eq!(res.amount, expected_reth_out);
1249
1250        // Post-state: now matches on-chain behavior.
1251        let new_state = res
1252            .new_state
1253            .as_any()
1254            .downcast_ref::<RocketpoolState>()
1255            .unwrap();
1256        assert_eq!(new_state.total_eth, state.total_eth);
1257        assert_eq!(new_state.reth_supply, state.reth_supply);
1258        // deposit_contract_balance unchanged — all 85 ETH went to rETH collateral buffer
1259        assert_eq!(new_state.deposit_contract_balance, state.deposit_contract_balance);
1260        // rETH contract liquidity increased by the full 85 ETH
1261        assert_eq!(
1262            new_state.reth_contract_liquidity,
1263            safe_add_u256(
1264                state.reth_contract_liquidity,
1265                U256::from(85_000_000_000_000_000_000u128)
1266            )
1267            .unwrap()
1268        );
1269        // Queue unchanged — vault had < 32 ETH, no assignment possible
1270        assert_eq!(new_state.megapool_queue_requested_total, state.megapool_queue_requested_total);
1271    }
1272
1273    /// Test against real v1.4 burn transaction.
1274    /// Tx 0x6e70e11475c158ca5f88a6d370dfef90eee6d696dd569c3eaab7d244c7b4a20f at block 24481338.
1275    /// User burned 2515686112138065226 rETH and received 2912504376202664754 ETH.
1276    ///
1277    /// Reuses `create_state_at_block_24480104` (~1200 blocks before the burn) because:
1278    ///   - `total_eth` and `reth_supply` are oracle-reported values (from rocketNetworkBalances)
1279    ///     updated only by oracle submissions (daily). Verified identical at both blocks:
1280    ///     getTotalETHBalance() = 396944271446898073504670, getTotalRETHSupply() =
1281    ///     342862039669683153255377.
1282    ///   - The burn amount (2.91 ETH) is sourced entirely from `reth_contract_liquidity` (224 ETH),
1283    ///     so `deposit_contract_balance` and `megapool_queue_requested_total` are not involved.
1284    #[test]
1285    fn test_live_burn_post_saturn() {
1286        let state = create_state_at_block_24480104();
1287
1288        let burn_amount = BigUint::from(2_515_686_112_138_065_226u128);
1289        let res = state
1290            .get_amount_out(burn_amount, &reth_token(), &eth_token())
1291            .unwrap();
1292
1293        // Output amount: exact match with on-chain getEthValue(burnAmount) at block 24481337
1294        let expected_eth_out = BigUint::from(2_912_504_376_202_664_754u128);
1295        assert_eq!(res.amount, expected_eth_out);
1296
1297        // Post-state: verify oracle values unchanged and liquidity decreased
1298        let new_state = res
1299            .new_state
1300            .as_any()
1301            .downcast_ref::<RocketpoolState>()
1302            .unwrap();
1303        assert_eq!(new_state.total_eth, state.total_eth);
1304        assert_eq!(new_state.reth_supply, state.reth_supply);
1305        // 2.91 ETH withdrawn entirely from reth_contract_liquidity (224 ETH available)
1306        assert_eq!(
1307            new_state.reth_contract_liquidity,
1308            safe_sub_u256(state.reth_contract_liquidity, U256::from(2_912_504_376_202_664_754u128))
1309                .unwrap()
1310        );
1311        assert_eq!(new_state.deposit_contract_balance, state.deposit_contract_balance);
1312    }
1313}