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; const FULL_DEPOSIT_VALUE: u128 = 32_000_000_000_000_000_000u128;
28
29const 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;
34const 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 pub deposit_contract_balance: U256,
44 pub reth_contract_liquidity: U256,
46 pub deposit_fee: U256,
49 pub deposits_enabled: bool,
50 pub min_deposit_amount: U256,
51 pub max_deposit_pool_size: U256,
52 pub deposit_assigning_enabled: bool,
54 pub deposit_assign_maximum: U256,
56 pub deposit_assign_socialised_maximum: U256,
58 pub megapool_queue_requested_total: U256,
60 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 fn get_reth_value(&self, eth_amount: U256) -> Result<U256, SimulationError> {
104 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 mul_div(net_eth, self.reth_supply, self.total_eth)
109 }
110
111 fn get_eth_value(&self, reth_amount: U256) -> Result<U256, SimulationError> {
113 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 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 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 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 fn compute_deposit_routing(
169 &self,
170 deposit_amount: U256,
171 ) -> Result<(U256, U256), SimulationError> {
172 let target_collateral = mul_div(
174 self.total_eth,
175 self.target_reth_collateral_rate,
176 U256::from(DEPOSIT_FEE_BASE),
177 )?;
178 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 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 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 let vault_cap = self.deposit_contract_balance / full_deposit_value;
211
212 let queue_entries = self.megapool_queue_requested_total / full_deposit_value;
214
215 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 let is_depositing_eth = RocketpoolState::is_depositing_eth("e.address);
237
238 let amount = U256::from(1e18);
241
242 let base_per_quote = if is_depositing_eth {
243 self.assert_deposits_enabled()?;
245 self.get_reth_value(amount)?
246 } else {
247 self.get_eth_value(amount)?
249 };
250
251 let base_per_quote = u256_to_f64(base_per_quote)? / 1e18;
252 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 if is_depositing_eth {
310 gas_used += BASE_DEPOSIT_GAS;
311
312 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 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 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 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 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 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 fn create_state() -> RocketpoolState {
506 RocketpoolState::new(
507 U256::from(100e18), U256::from(200e18), U256::from(50e18), U256::ZERO, U256::from(400_000_000_000_000_000u64), true, U256::ZERO, U256::from(1000e18), false, U256::ZERO, U256::ZERO, U256::ZERO, U256::from(10_000_000_000_000_000u64), )
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 #[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 assert_eq!(
572 state
573 .get_max_deposit_capacity()
574 .unwrap(),
575 U256::from(1500e18)
576 );
577 }
578
579 #[rstest]
582 #[case::all_to_reth(
583 U256::ZERO, U256::from(10_000_000_000_000_000u64), 1_000_000_000_000_000_000u128, 1_000_000_000_000_000_000u128, 0u128, )]
589 #[case::split(
591 U256::ZERO,
592 U256::from(10_000_000_000_000_000u64),
593 10_000_000_000_000_000_000u128, 2_000_000_000_000_000_000u128, 8_000_000_000_000_000_000u128, )]
597 #[case::all_to_vault(
599 U256::from(10_000_000_000_000_000_000u128), U256::from(10_000_000_000_000_000u64),
601 5_000_000_000_000_000_000u128, 0u128,
603 5_000_000_000_000_000_000u128,
604 )]
605 #[case::zero_collateral_rate(
607 U256::ZERO,
608 U256::ZERO, 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 #[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 #[test]
693 fn test_spot_price_deposit() {
694 let state = create_state();
695 let price = state
696 .spot_price(ð_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(), ð_token())
706 .unwrap();
707 assert_ulps_eq!(price, 1.0 / 0.3);
708 }
709
710 #[test]
714 fn test_live_spot_price_withdrawal() {
715 let state = create_state_at_block_24480104();
716 let price = state
717 .spot_price(ð_token(), &reth_token())
718 .unwrap();
719
720 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 #[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(), ð_token())
736 .unwrap();
737
738 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; 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 #[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 assert_eq!(max_sell, BigUint::from(950_000_000_000_000_000_000u128));
764 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 assert_eq!(max_buy, BigUint::from(50_000_000_000_000_000_000u128));
776 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 assert_eq!(max_sell, BigUint::from(112_000_000_000_000_000_000u128));
792 }
793
794 #[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 let res = state.get_amount_out(max_sell.clone(), ð_token(), &reth_token());
808 assert!(res.is_ok(), "max_sell should be accepted");
809
810 let over = max_sell + BigUint::from(1u64);
812 let res = state.get_amount_out(over, ð_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 let res = state.get_amount_out(max_sell.clone(), &reth_token(), ð_token());
827 assert!(res.is_ok(), "max_sell should be accepted");
828
829 let over = max_sell + BigUint::from(1u64);
831 let res = state.get_amount_out(over, &reth_token(), ð_token());
832 assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
833 }
834
835 #[test]
838 fn test_deposit_eth() {
839 let state = create_state();
840 let res = state
842 .get_amount_out(
843 BigUint::from(10_000_000_000_000_000_000u128),
844 ð_token(),
845 &reth_token(),
846 )
847 .unwrap();
848
849 assert_eq!(res.amount, BigUint::from(3_000_000_000_000_000_000u128));
850
851 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 let res = state
868 .get_amount_out(
869 BigUint::from(10_000_000_000_000_000_000u128),
870 &reth_token(),
871 ð_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 #[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), ð_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), ð_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 ð_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 ð_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 let res = state.get_amount_out(
934 BigUint::from(20_000_000_000_000_000_000u128),
935 &reth_token(),
936 ð_token(),
937 );
938 assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
939
940 let res = state
942 .get_amount_out(
943 BigUint::from(15_000_000_000_000_000_000u128),
944 &reth_token(),
945 ð_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 let res = state
959 .get_amount_out(
960 BigUint::from(15_000_000_000_000_000_000u128),
961 &reth_token(),
962 ð_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 #[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); state.deposit_assigning_enabled = true;
985 state.deposit_assign_maximum = U256::from(90u64);
986 state.megapool_queue_requested_total = U256::from(128e18); let res = state
990 .get_amount_out(
991 BigUint::from(100_000_000_000_000_000_000u128),
992 ð_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 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 ð_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 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 ð_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 assert_eq!(new_state.deposit_contract_balance, U256::from(58e18));
1058 }
1059
1060 #[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 state.megapool_queue_requested_total = U256::from(96e18);
1077 state.target_reth_collateral_rate = U256::from(100_000_000_000_000_000u64); let res = state
1081 .get_amount_out(
1082 BigUint::from(100_000_000_000_000_000_000u128),
1083 ð_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 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 state.reth_contract_liquidity = U256::from(10_000_000_000_000_000_000u128);
1116 state
1117 }
1118
1119 #[rstest]
1120 #[case::count_cap_limits(
1123 64_000_000_000_000_000_000u128, 300_000_000_000_000_000_000u128, 128_000_000_000_000_000_000u128, 90u64, 0u64, 64_000_000_000_000_000_000u128, )]
1130 #[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, )]
1140 #[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, )]
1150 #[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, )]
1160 #[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, )]
1170 #[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 #[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 fn create_state_at_block_24480104() -> RocketpoolState {
1212 RocketpoolState::new(
1213 U256::from_str_radix("489a96a246a2e92bbbd1", 16).unwrap(), U256::from_str_radix("540e645ee4119f4d8b9e", 16).unwrap(), U256::from_str_radix("8dcfa9d0071987bb", 16).unwrap(), U256::from_str_radix("c28d2e1d64f99ea24", 16).unwrap(), U256::from_str_radix("1c6bf52634000", 16).unwrap(), true, U256::from_str_radix("2386f26fc10000", 16).unwrap(), U256::from_str_radix("4f68ca6d8cd91c6000000", 16).unwrap(), true, U256::from(90u64), U256::ZERO, U256::from_str_radix("4a60532ad51bf000000", 16).unwrap(), U256::from(10_000_000_000_000_000u64), )
1227 }
1228
1229 #[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, ð_token(), &reth_token())
1244 .unwrap();
1245
1246 let expected_reth_out = BigUint::from(73_382_345_660_413_064_855u128);
1248 assert_eq!(res.amount, expected_reth_out);
1249
1250 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 assert_eq!(new_state.deposit_contract_balance, state.deposit_contract_balance);
1260 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 assert_eq!(new_state.megapool_queue_requested_total, state.megapool_queue_requested_total);
1271 }
1272
1273 #[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(), ð_token())
1291 .unwrap();
1292
1293 let expected_eth_out = BigUint::from(2_912_504_376_202_664_754u128);
1295 assert_eq!(res.amount, expected_eth_out);
1296
1297 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 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}