Skip to main content

tycho_simulation/evm/protocol/lido_v4/
state.rs

1use std::{any::Any, collections::HashMap};
2
3use alloy::primitives::U256;
4use hex_literal::hex;
5use num_bigint::BigUint;
6use serde::{Deserialize, Serialize};
7use tycho_common::{
8    dto::ProtocolStateDelta,
9    models::token::Token,
10    simulation::{
11        errors::{SimulationError, TransitionError},
12        protocol_sim::{Balances, BlockContext, GetAmountOutResult, ProtocolSim},
13    },
14    Bytes,
15};
16
17use crate::evm::protocol::{
18    safe_math::{safe_add_u256, safe_mul_u256, safe_sub_u256},
19    u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
20};
21
22/// One component covers the whole venue: stETH mints, and wstETH wraps, unwraps and mints
23/// through `receive()`. Keyed by stETH, the contract that holds the pool.
24pub const STETH_COMPONENT_ID: &str = "0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84";
25
26pub const STETH_ADDRESS: [u8; 20] = hex!("ae7ab96520de3a18e5e111b5eaab095312d7fe84");
27pub const WSTETH_ADDRESS: [u8; 20] = hex!("7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0");
28pub const ETH_ADDRESS: [u8; 20] = hex!("0000000000000000000000000000000000000000");
29
30/// Slice views of the addresses above, so a swap direction can be matched as a tuple.
31const ETH: &[u8] = &ETH_ADDRESS;
32const STETH: &[u8] = &STETH_ADDRESS;
33const WSTETH: &[u8] = &WSTETH_ADDRESS;
34
35// One attribute per value Lido names. The substreams package unpacks the storage words, so
36// each of these carries a single scalar.
37pub const TOTAL_SHARES_ATTR: &str = "total_shares";
38pub const EXTERNAL_SHARES_ATTR: &str = "external_shares";
39pub const BUFFERED_ETHER_ATTR: &str = "buffered_ether";
40pub const DEPOSITED_POST_REPORT_ATTR: &str = "deposited_post_report";
41pub const CL_VALIDATORS_BALANCE_ATTR: &str = "cl_validators_balance";
42pub const CL_PENDING_BALANCE_ATTR: &str = "cl_pending_balance";
43pub const PREV_STAKE_BLOCK_NUMBER_ATTR: &str = "prev_stake_block_number";
44pub const PREV_STAKE_LIMIT_ATTR: &str = "prev_stake_limit";
45pub const MAX_STAKE_LIMIT_GROWTH_BLOCKS_ATTR: &str = "max_stake_limit_growth_blocks";
46pub const MAX_STAKE_LIMIT_ATTR: &str = "max_stake_limit";
47pub const WSTETH_SHARES_ATTR: &str = "wsteth_shares";
48
49const UINT128_MAX_EXCLUSIVE: u128 = u128::MAX;
50
51// Gas each venue call costs, measured on a mainnet fork at block 25990000 from an account
52// trading for the first time, so every balance slot the call touches is cold. The 21,000
53// intrinsic and the calldata are left out: the router pays those once for the whole
54// transaction, and `estimate_gas_usage` adds the transfers around the leg separately.
55//
56// `wstETH.receive()` submits ETH and mints wstETH in one call. `wrap` additionally reads and
57// updates the stETH allowance during `transferFrom`.
58const SUBMIT_GAS: u64 = 83_000;
59const SUBMIT_AND_WRAP_GAS: u64 = 97_000;
60const WRAP_GAS: u64 = 103_000;
61const UNWRAP_GAS: u64 = 80_000;
62
63#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
64pub struct LidoV4State {
65    /// Height of the block a quote is expected to execute in, maintained by `apply_block`.
66    ///
67    /// The stake limit accrues per block, so this tracks the chain head: `apply_block` advances
68    /// it on every message, including the blocks where stETH storage does not move, which are
69    /// most of them.
70    execution_block_number: u64,
71    total_shares: U256,
72    external_shares: U256,
73    buffered_ether: U256,
74    /// ETH sent to the deposit contract since the last oracle report; the next report moves it
75    /// into the consensus-layer balances below.
76    deposited_post_report: U256,
77    cl_validators_balance: U256,
78    cl_pending_balance: U256,
79    staking_state: StakingState,
80    /// `sharesOf(wstETH)`, i.e. the shares the wrapper holds. Bounds how much can be unwrapped.
81    wsteth_shares: U256,
82}
83
84/// Lido stores amounts as uint128 or narrower, so anything wider is a malformed input rather
85/// than a trade the venue could serve.
86fn validate_u128_bound(name: &str, value: U256) -> Result<(), SimulationError> {
87    if value >= U256::from(UINT128_MAX_EXCLUSIVE) {
88        return Err(SimulationError::InvalidInput(format!("{name} exceeds uint128 bound"), None));
89    }
90    Ok(())
91}
92
93/// Bytes an attribute occupies on the wire: the width of the stETH storage field the substreams
94/// package unpacks it from. The balances and share counts are `getLowAndHighUint128` halves, the
95/// stake limit fields are laid out by `StakeLimitUtils`, and `sharesOf(wstETH)` is a whole word.
96fn attribute_width(name: &str) -> Option<usize> {
97    match name {
98        TOTAL_SHARES_ATTR |
99        EXTERNAL_SHARES_ATTR |
100        BUFFERED_ETHER_ATTR |
101        DEPOSITED_POST_REPORT_ATTR |
102        CL_VALIDATORS_BALANCE_ATTR |
103        CL_PENDING_BALANCE_ATTR => Some(16),
104        PREV_STAKE_LIMIT_ATTR | MAX_STAKE_LIMIT_ATTR => Some(12),
105        PREV_STAKE_BLOCK_NUMBER_ATTR | MAX_STAKE_LIMIT_GROWTH_BLOCKS_ATTR => Some(4),
106        WSTETH_SHARES_ATTR => Some(32),
107        _ => None,
108    }
109}
110
111/// Reads a big-endian attribute, refusing one wider than its storage field. The package emits
112/// minimal-length values, so a wider one is malformed, and the `Err` names it for the caller to
113/// report.
114pub(super) fn decode_attribute(name: &str, value: &[u8]) -> Result<U256, String> {
115    let Some(width) = attribute_width(name) else {
116        return Err(format!("{name} is not a Lido V4 attribute"));
117    };
118    if value.len() > width {
119        return Err(format!("{name} is {} bytes, wider than its {width}-byte field", value.len()));
120    }
121    Ok(U256::from_be_slice(value))
122}
123
124/// `decode_attribute` for the two 32-bit block counters in `StakeLimitUtils`.
125pub(super) fn decode_u32_attribute(name: &str, value: &[u8]) -> Result<u32, String> {
126    let value = decode_attribute(name, value)?;
127    u32::try_from(value).map_err(|_out_of_range| format!("{name} does not fit in 32 bits"))
128}
129
130#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
131pub struct StakingState {
132    prev_stake_block_number: u32,
133    prev_stake_limit: U256,
134    max_stake_limit_growth_blocks: u32,
135    max_stake_limit: U256,
136}
137
138impl LidoV4State {
139    #[expect(
140        clippy::too_many_arguments,
141        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
142    )]
143    pub fn new(
144        execution_block_number: u64,
145        total_shares: U256,
146        external_shares: U256,
147        buffered_ether: U256,
148        deposited_post_report: U256,
149        cl_validators_balance: U256,
150        cl_pending_balance: U256,
151        staking_state: StakingState,
152        wsteth_shares: U256,
153    ) -> Self {
154        Self {
155            execution_block_number,
156            total_shares,
157            external_shares,
158            buffered_ether,
159            deposited_post_report,
160            cl_validators_balance,
161            cl_pending_balance,
162            staking_state,
163            wsteth_shares,
164        }
165    }
166
167    fn internal_shares(&self) -> Result<U256, SimulationError> {
168        if self.external_shares > self.total_shares {
169            return Err(SimulationError::FatalError(
170                "external shares exceed total shares".to_string(),
171            ));
172        }
173        Ok(self.total_shares - self.external_shares)
174    }
175
176    /// `Lido._getInternalEther()`: buffered ether plus every balance counted on the consensus
177    /// layer - active validators, deposits pending activation, and deposits made since the last
178    /// oracle report. Each term is one half of a word read through `getLowAndHighUint128`, which
179    /// masks it to 128 bits, and `decode_attribute` holds it to that width, so four of them sum
180    /// below 2^130.
181    fn internal_ether(&self) -> U256 {
182        self.buffered_ether +
183            self.cl_validators_balance +
184            self.cl_pending_balance +
185            self.deposited_post_report
186    }
187
188    fn shares_for_pooled_eth(&self, eth_amount: U256) -> Result<U256, SimulationError> {
189        validate_u128_bound("eth amount", eth_amount)?;
190        let denominator = self.internal_shares()?;
191        let numerator = self.internal_ether();
192        if denominator.is_zero() || numerator.is_zero() {
193            return Err(SimulationError::FatalError("invalid Lido share rate state".to_string()));
194        }
195        Ok(safe_mul_u256(eth_amount, denominator)? / numerator)
196    }
197
198    fn pooled_eth_by_shares(&self, shares_amount: U256) -> Result<U256, SimulationError> {
199        validate_u128_bound("shares amount", shares_amount)?;
200        let numerator = self.internal_ether();
201        let denominator = self.internal_shares()?;
202        if denominator.is_zero() || numerator.is_zero() {
203            return Err(SimulationError::FatalError("invalid Lido share rate state".to_string()));
204        }
205        Ok(safe_mul_u256(shares_amount, numerator)? / denominator)
206    }
207
208    /// `stETH.totalSupply()`: `Lido._getTotalPooledEther()`, the internal ether plus the ether
209    /// backing shares minted outside the protocol, valued at the internal share rate.
210    fn total_pooled_ether(&self) -> Result<U256, SimulationError> {
211        let external_ether = self.pooled_eth_by_shares(self.external_shares)?;
212        safe_add_u256(self.internal_ether(), external_ether)
213    }
214
215    /// Caps deposits by staking capacity and the remaining uint128 storage capacity.
216    fn deposit_limit(&self) -> Result<U256, SimulationError> {
217        let cap = U256::from(u128::MAX);
218        let max_input = cap - U256::ONE;
219        let shares = self.internal_shares()?;
220        if shares.is_zero() || self.internal_ether().is_zero() {
221            return Err(SimulationError::FatalError("invalid Lido share rate state".to_string()));
222        }
223        let share_headroom = safe_sub_u256(cap, self.total_shares)?;
224        // The product can exceed 256 bits. Floor division gives a conservative deposit
225        // whose minted shares fit the field; cap before converting back to U256.
226        let share_capacity = u256_to_biguint(share_headroom) *
227            u256_to_biguint(self.internal_ether()) /
228            u256_to_biguint(shares);
229        let share_capacity = biguint_to_u256(&share_capacity.min(u256_to_biguint(max_input)));
230        Ok(self
231            .staking_state
232            .current_limit(self.execution_block_number)
233            .min(max_input)
234            .min(safe_sub_u256(cap, self.buffered_ether)?)
235            .min(share_capacity))
236    }
237
238    fn check_deposit_limit(&self, amount: U256) -> Result<(), SimulationError> {
239        if amount > self.deposit_limit()? {
240            return Err(SimulationError::RecoverableError("DEPOSIT_LIMIT".to_string()));
241        }
242        Ok(())
243    }
244
245    fn amount_out_eth_to_steth(
246        &self,
247        amount_in: U256,
248    ) -> Result<GetAmountOutResult, SimulationError> {
249        let shares_amount = self.shares_for_pooled_eth(amount_in)?;
250        let mut new_state = self.clone();
251        new_state
252            .staking_state
253            .decrease(amount_in, new_state.execution_block_number)?;
254        self.check_deposit_limit(amount_in)?;
255        new_state.total_shares = safe_add_u256(new_state.total_shares, shares_amount)?;
256        new_state.buffered_ether = safe_add_u256(new_state.buffered_ether, amount_in)?;
257        let amount_out = new_state.pooled_eth_by_shares(shares_amount)?;
258        Ok(GetAmountOutResult::new(
259            u256_to_biguint(amount_out),
260            BigUint::from(SUBMIT_GAS),
261            Box::new(new_state),
262        ))
263    }
264
265    fn amount_out_steth_to_wsteth(
266        &self,
267        amount_in: U256,
268    ) -> Result<GetAmountOutResult, SimulationError> {
269        if amount_in > self.total_pooled_ether()? {
270            return Err(SimulationError::RecoverableError("STETH_SUPPLY_EXCEEDED".to_string()));
271        }
272        let amount_out = self.shares_for_pooled_eth(amount_in)?;
273        // `wrap` pulls the stETH into the wrapper, so the shares it holds grow by what it minted.
274        let mut new_state = self.clone();
275        new_state.wsteth_shares = safe_add_u256(new_state.wsteth_shares, amount_out)?;
276        Ok(GetAmountOutResult::new(
277            u256_to_biguint(amount_out),
278            BigUint::from(WRAP_GAS),
279            Box::new(new_state),
280        ))
281    }
282
283    /// ETH -> wstETH through the wrapper's `receive()`: it submits the ETH and mints exactly the
284    /// shares `submit` returned, so the output is that share count.
285    fn amount_out_eth_to_wsteth(
286        &self,
287        amount_in: U256,
288    ) -> Result<GetAmountOutResult, SimulationError> {
289        let shares_amount = self.shares_for_pooled_eth(amount_in)?;
290        let mut new_state = self.clone();
291        new_state
292            .staking_state
293            .decrease(amount_in, new_state.execution_block_number)?;
294        self.check_deposit_limit(amount_in)?;
295        new_state.total_shares = safe_add_u256(new_state.total_shares, shares_amount)?;
296        new_state.buffered_ether = safe_add_u256(new_state.buffered_ether, amount_in)?;
297        // The submitted stETH lands on the wrapper, so its share balance grows with the mint.
298        new_state.wsteth_shares = safe_add_u256(new_state.wsteth_shares, shares_amount)?;
299        Ok(GetAmountOutResult::new(
300            u256_to_biguint(shares_amount),
301            BigUint::from(SUBMIT_AND_WRAP_GAS),
302            Box::new(new_state),
303        ))
304    }
305
306    fn unwrap_limit(&self) -> Result<U256, SimulationError> {
307        let max_input = U256::from(UINT128_MAX_EXCLUSIVE) - U256::ONE;
308        // stETH.transfer converts its nominal amount back to shares and bounds that amount.
309        Ok(self
310            .wsteth_shares
311            .min(max_input)
312            .min(self.shares_for_pooled_eth(max_input)?))
313    }
314
315    fn amount_out_wsteth_to_steth(
316        &self,
317        amount_in: U256,
318    ) -> Result<GetAmountOutResult, SimulationError> {
319        // The wrapper must hold enough shares, and the nominal stETH transfer must fit
320        // the contract's conversion bound. `get_limits` applies the same cap.
321        if amount_in > self.unwrap_limit()? {
322            return Err(SimulationError::RecoverableError("UNWRAP_LIMIT".to_string()));
323        }
324        let amount_out = self.pooled_eth_by_shares(amount_in)?;
325        // `unwrap` burns the caller's wstETH and pays out `amount_out` stETH, and `transfer`
326        // re-derives the shares that amount is worth. Both conversions round down, so what
327        // leaves the wrapper is what the round trip resolves to.
328        let mut new_state = self.clone();
329        let shares_paid_out = self.shares_for_pooled_eth(amount_out)?;
330        new_state.wsteth_shares = safe_sub_u256(new_state.wsteth_shares, shares_paid_out)?;
331        // A receiver's balance increase is at least the value of the transferred shares.
332        let amount_out = self.pooled_eth_by_shares(shares_paid_out)?;
333        Ok(GetAmountOutResult::new(
334            u256_to_biguint(amount_out),
335            BigUint::from(UNWRAP_GAS),
336            Box::new(new_state),
337        ))
338    }
339}
340
341impl StakingState {
342    pub(crate) fn new(
343        prev_stake_block_number: u32,
344        prev_stake_limit: U256,
345        max_stake_limit_growth_blocks: u32,
346        max_stake_limit: U256,
347    ) -> Self {
348        Self {
349            prev_stake_block_number,
350            prev_stake_limit,
351            max_stake_limit_growth_blocks,
352            max_stake_limit,
353        }
354    }
355
356    fn is_staking_paused(&self) -> bool {
357        self.prev_stake_block_number == 0
358    }
359
360    fn is_staking_limit_set(&self) -> bool {
361        !self.max_stake_limit.is_zero()
362    }
363
364    fn calculate_current_stake_limit(&self, block_number: u64) -> U256 {
365        let stake_limit_inc_per_block = if self.max_stake_limit_growth_blocks != 0 {
366            self.max_stake_limit / U256::from(self.max_stake_limit_growth_blocks)
367        } else {
368            U256::ZERO
369        };
370
371        let blocks_passed = block_number.saturating_sub(self.prev_stake_block_number as u64);
372        let change = U256::from(blocks_passed) * stake_limit_inc_per_block;
373
374        if self.prev_stake_limit < self.max_stake_limit {
375            (self.prev_stake_limit + change).min(self.max_stake_limit)
376        } else {
377            self.prev_stake_limit
378                .saturating_sub(change)
379                .max(self.max_stake_limit)
380        }
381    }
382
383    fn current_limit(&self, block_number: u64) -> U256 {
384        if self.is_staking_paused() {
385            U256::ZERO
386        } else if !self.is_staking_limit_set() {
387            U256::from(UINT128_MAX_EXCLUSIVE) - U256::ONE
388        } else {
389            self.calculate_current_stake_limit(block_number)
390        }
391    }
392
393    fn decrease(&mut self, amount: U256, block_number: u64) -> Result<(), SimulationError> {
394        if self.is_staking_paused() {
395            return Err(SimulationError::RecoverableError("STAKING_PAUSED".to_string()));
396        }
397
398        if self.is_staking_limit_set() {
399            let current_stake_limit = self.calculate_current_stake_limit(block_number);
400            if amount > current_stake_limit {
401                return Err(SimulationError::RecoverableError("STAKE_LIMIT".to_string()));
402            }
403            self.prev_stake_limit = current_stake_limit - amount;
404            // Lido stores prevStakeBlockNumber as a uint32: the low 32 bits of the block number.
405            self.prev_stake_block_number = (block_number & 0xFFFF_FFFF) as u32;
406        }
407
408        Ok(())
409    }
410}
411
412#[typetag::serde]
413impl ProtocolSim for LidoV4State {
414    fn fee(&self) -> f64 {
415        0f64
416    }
417
418    /// Prices exactly the four directions the venue performs. stETH -> ETH and wstETH -> ETH run
419    /// through the asynchronous withdrawal queue, so they have no rate here, matching the zero
420    /// limit `get_limits` reports for them.
421    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
422        let quote_unit_f64 = u256_to_f64(U256::from(10).pow(U256::from(quote.decimals)))?;
423        let base_unit = U256::from(10).pow(U256::from(base.decimals));
424        let to_price = |amount_out: U256| -> Result<f64, SimulationError> {
425            Ok(u256_to_f64(amount_out)? / quote_unit_f64)
426        };
427
428        match (base.address.as_ref(), quote.address.as_ref()) {
429            // Submitting mints shares, and the depositor holds the stETH balance those shares
430            // are worth. Taken from the share rate, which holds while staking is paused or its
431            // limit is exhausted: those bound capacity, not price.
432            (ETH, STETH) => {
433                to_price(self.pooled_eth_by_shares(self.shares_for_pooled_eth(base_unit)?)?)
434            }
435            // Submitting ETH mints shares worth the ETH, and wrapping stETH mints shares worth the
436            // stETH - the same conversion either way, since submit is at parity.
437            (ETH | STETH, WSTETH) => to_price(self.shares_for_pooled_eth(base_unit)?),
438            (WSTETH, STETH) => to_price(self.pooled_eth_by_shares(base_unit)?),
439            _ => Err(SimulationError::FatalError("unsupported spot price".to_string())),
440        }
441    }
442
443    fn get_amount_out(
444        &self,
445        amount_in: BigUint,
446        token_in: &Token,
447        token_out: &Token,
448    ) -> Result<GetAmountOutResult, SimulationError> {
449        if amount_in.bits() > 128 {
450            return Err(SimulationError::InvalidInput(
451                "amount exceeds uint128 bound".to_string(),
452                None,
453            ));
454        }
455        let amount_in = biguint_to_u256(&amount_in);
456        validate_u128_bound("amount", amount_in)?;
457        // Every direction reverts on a zero amount: `submit` with ZERO_DEPOSIT, and the wrapper
458        // with its own zero-amount guards.
459        if amount_in.is_zero() {
460            return Err(SimulationError::RecoverableError("ZERO_AMOUNT".to_string()));
461        }
462
463        let result = match (token_in.address.as_ref(), token_out.address.as_ref()) {
464            (ETH, STETH) => self.amount_out_eth_to_steth(amount_in),
465            (STETH, WSTETH) => self.amount_out_steth_to_wsteth(amount_in),
466            (WSTETH, STETH) => self.amount_out_wsteth_to_steth(amount_in),
467            (ETH, WSTETH) => self.amount_out_eth_to_wsteth(amount_in),
468            _ => Err(SimulationError::FatalError("unsupported swap".to_string())),
469        }?;
470        if result.amount == BigUint::ZERO {
471            return Err(SimulationError::RecoverableError("ZERO_OUTPUT".to_string()));
472        }
473        Ok(result)
474    }
475
476    fn get_limits(
477        &self,
478        sell_token: Bytes,
479        buy_token: Bytes,
480    ) -> Result<(BigUint, BigUint), SimulationError> {
481        let max_input = U256::from(UINT128_MAX_EXCLUSIVE) - U256::ONE;
482        let max_sell = match (sell_token.as_ref(), buy_token.as_ref()) {
483            (ETH, STETH | WSTETH) => self.deposit_limit()?,
484            (STETH, WSTETH) => self
485                .total_pooled_ether()?
486                .min(max_input),
487            (WSTETH, STETH) => self.unwrap_limit()?,
488            // Unstaking requires the asynchronous withdrawal queue.
489            (STETH, ETH) | (WSTETH, ETH) => U256::ZERO,
490            _ => return Err(SimulationError::FatalError("unsupported swap".to_string())),
491        };
492        if max_sell.is_zero() {
493            return Ok((BigUint::ZERO, BigUint::ZERO));
494        }
495        let max_buy = match (sell_token.as_ref(), buy_token.as_ref()) {
496            (ETH, STETH) => {
497                self.amount_out_eth_to_steth(max_sell)?
498                    .amount
499            }
500            (ETH, WSTETH) => {
501                self.amount_out_eth_to_wsteth(max_sell)?
502                    .amount
503            }
504            (STETH, WSTETH) => {
505                self.amount_out_steth_to_wsteth(max_sell)?
506                    .amount
507            }
508            (WSTETH, STETH) => {
509                self.amount_out_wsteth_to_steth(max_sell)?
510                    .amount
511            }
512            _ => return Err(SimulationError::FatalError("unsupported swap".to_string())),
513        };
514        if max_buy == BigUint::ZERO {
515            return Ok((BigUint::ZERO, BigUint::ZERO));
516        }
517        Ok((u256_to_biguint(max_sell), max_buy))
518    }
519
520    fn delta_transition(
521        &mut self,
522        delta: ProtocolStateDelta,
523        _tokens: &HashMap<Bytes, Token>,
524        _balances: &Balances,
525    ) -> Result<(), TransitionError> {
526        let read = |name: &str| -> Result<Option<U256>, TransitionError> {
527            delta
528                .updated_attributes
529                .get(name)
530                .map(|value| decode_attribute(name, value))
531                .transpose()
532                .map_err(TransitionError::DecodeError)
533        };
534        let read_u32 = |name: &str| -> Result<Option<u32>, TransitionError> {
535            delta
536                .updated_attributes
537                .get(name)
538                .map(|value| decode_u32_attribute(name, value))
539                .transpose()
540                .map_err(TransitionError::DecodeError)
541        };
542
543        // Decode all fields before mutation so invalid deltas leave a consistent quote state.
544        let total_shares = read(TOTAL_SHARES_ATTR)?;
545        let external_shares = read(EXTERNAL_SHARES_ATTR)?;
546        let buffered_ether = read(BUFFERED_ETHER_ATTR)?;
547        let deposited_post_report = read(DEPOSITED_POST_REPORT_ATTR)?;
548        let cl_validators_balance = read(CL_VALIDATORS_BALANCE_ATTR)?;
549        let cl_pending_balance = read(CL_PENDING_BALANCE_ATTR)?;
550        let wsteth_shares = read(WSTETH_SHARES_ATTR)?;
551        let prev_stake_block_number = read_u32(PREV_STAKE_BLOCK_NUMBER_ATTR)?;
552        let prev_stake_limit = read(PREV_STAKE_LIMIT_ATTR)?;
553        let max_stake_limit_growth_blocks = read_u32(MAX_STAKE_LIMIT_GROWTH_BLOCKS_ATTR)?;
554        let max_stake_limit = read(MAX_STAKE_LIMIT_ATTR)?;
555
556        if let Some(value) = total_shares {
557            self.total_shares = value;
558        }
559        if let Some(value) = external_shares {
560            self.external_shares = value;
561        }
562        if let Some(value) = buffered_ether {
563            self.buffered_ether = value;
564        }
565        if let Some(value) = deposited_post_report {
566            self.deposited_post_report = value;
567        }
568        if let Some(value) = cl_validators_balance {
569            self.cl_validators_balance = value;
570        }
571        if let Some(value) = cl_pending_balance {
572            self.cl_pending_balance = value;
573        }
574        if let Some(value) = wsteth_shares {
575            self.wsteth_shares = value;
576        }
577        if let Some(value) = prev_stake_block_number {
578            self.staking_state
579                .prev_stake_block_number = value;
580        }
581        if let Some(value) = prev_stake_limit {
582            self.staking_state.prev_stake_limit = value;
583        }
584        if let Some(value) = max_stake_limit_growth_blocks {
585            self.staking_state
586                .max_stake_limit_growth_blocks = value;
587        }
588        if let Some(value) = max_stake_limit {
589            self.staking_state.max_stake_limit = value;
590        }
591        Ok(())
592    }
593
594    /// Advances to the block a quote would execute in, so the stake limit keeps accruing on the
595    /// blocks where Lido's own storage did not move.
596    ///
597    /// Re-emits only when the resolved limit actually changed: a repeated block short-circuits,
598    /// and once the limit has settled at `max_stake_limit` further blocks cost one virtual call
599    /// and no clone.
600    fn apply_block(&mut self, block: &BlockContext) -> bool {
601        let number = block.number();
602        if number == self.execution_block_number {
603            return false;
604        }
605        let limit_before = self
606            .staking_state
607            .current_limit(self.execution_block_number);
608        self.execution_block_number = number;
609        limit_before != self.staking_state.current_limit(number)
610    }
611
612    fn query_pool_swap(
613        &self,
614        params: &tycho_common::simulation::protocol_sim::QueryPoolSwapParams,
615    ) -> Result<tycho_common::simulation::protocol_sim::PoolSwap, SimulationError> {
616        crate::evm::query_pool_swap::query_pool_swap(self, params)
617    }
618
619    fn clone_box(&self) -> Box<dyn ProtocolSim> {
620        Box::new(self.clone())
621    }
622
623    fn as_any(&self) -> &dyn Any {
624        self
625    }
626
627    fn as_any_mut(&mut self) -> &mut dyn Any {
628        self
629    }
630
631    fn eq(&self, other: &dyn ProtocolSim) -> bool {
632        other.as_any().downcast_ref::<Self>() == Some(self)
633    }
634}
635
636#[cfg(test)]
637mod tests {
638    /// The attributes the component carries, in the order the decoder reads them.
639    pub(super) const COMPONENT_ATTRS: [&str; 11] = [
640        TOTAL_SHARES_ATTR,
641        EXTERNAL_SHARES_ATTR,
642        BUFFERED_ETHER_ATTR,
643        DEPOSITED_POST_REPORT_ATTR,
644        CL_VALIDATORS_BALANCE_ATTR,
645        CL_PENDING_BALANCE_ATTR,
646        PREV_STAKE_BLOCK_NUMBER_ATTR,
647        PREV_STAKE_LIMIT_ATTR,
648        MAX_STAKE_LIMIT_GROWTH_BLOCKS_ATTR,
649        MAX_STAKE_LIMIT_ATTR,
650        WSTETH_SHARES_ATTR,
651    ];
652    use std::collections::HashMap;
653
654    use tycho_client::feed::BlockHeader;
655    use tycho_common::{
656        dto::ProtocolStateDelta,
657        models::{
658            protocol::{ProtocolComponent, ProtocolComponentState},
659            Chain,
660        },
661        simulation::errors::{SimulationError, TransitionError},
662        Bytes,
663    };
664
665    use super::*;
666    use crate::{
667        evm::protocol::test_utils::try_decode_snapshot_with_defaults,
668        protocol::{errors::InvalidSnapshotError, models::TryFromWithBlock},
669    };
670
671    fn eth_token() -> Token {
672        Token::new(&Bytes::from(ETH_ADDRESS), "ETH", 18, 0, &[], Chain::Ethereum, 100)
673    }
674
675    fn steth_token() -> Token {
676        Token::new(&Bytes::from(STETH_ADDRESS), "stETH", 18, 0, &[], Chain::Ethereum, 75)
677    }
678
679    fn wsteth_token() -> Token {
680        Token::new(&Bytes::from(WSTETH_ADDRESS), "wstETH", 18, 0, &[], Chain::Ethereum, 100)
681    }
682
683    fn sample_staking_state() -> StakingState {
684        StakingState {
685            prev_stake_block_number: 24_083_113,
686            prev_stake_limit: U256::from(1_000u64) * U256::from(10).pow(U256::from(18)),
687            max_stake_limit_growth_blocks: 10,
688            max_stake_limit: U256::from(1_000u64) * U256::from(10).pow(U256::from(18)),
689        }
690    }
691
692    fn sample_state() -> LidoV4State {
693        LidoV4State::new(
694            24_083_113,
695            U256::from_str_radix("6696604823358181328750512", 10).unwrap(),
696            U256::from_str_radix("80758346894447149184", 10).unwrap(),
697            U256::from_str_radix("658338852056838456032283", 10).unwrap(),
698            U256::from(30_560u64) * U256::from(10).pow(U256::from(18)),
699            U256::from_str_radix("21114116614166341429013364", 10).unwrap(),
700            U256::ZERO,
701            sample_staking_state(),
702            sample_wsteth_shares(),
703        )
704    }
705
706    /// The shares the wstETH wrapper holds - a little under half the pool.
707    fn sample_wsteth_shares() -> U256 {
708        U256::from_str_radix("2960000000000000000000000", 10).unwrap()
709    }
710
711    /// Encodes an attribute the way the substreams package does: big-endian with no leading zero
712    /// bytes, and a single zero byte for zero.
713    fn attribute(value: U256) -> Bytes {
714        let bytes = value.to_be_bytes_vec();
715        let start = bytes
716            .iter()
717            .position(|byte| *byte != 0)
718            .unwrap_or(bytes.len() - 1);
719        Bytes::from(bytes[start..].to_vec())
720    }
721
722    fn snapshot() -> tycho_client::feed::synchronizer::ComponentWithState {
723        let state = sample_state();
724        let staking = sample_staking_state();
725        let attributes: HashMap<String, Bytes> = [
726            (TOTAL_SHARES_ATTR, state.total_shares),
727            (EXTERNAL_SHARES_ATTR, state.external_shares),
728            (BUFFERED_ETHER_ATTR, state.buffered_ether),
729            (DEPOSITED_POST_REPORT_ATTR, state.deposited_post_report),
730            (CL_VALIDATORS_BALANCE_ATTR, state.cl_validators_balance),
731            (CL_PENDING_BALANCE_ATTR, state.cl_pending_balance),
732            (WSTETH_SHARES_ATTR, sample_wsteth_shares()),
733            (PREV_STAKE_BLOCK_NUMBER_ATTR, U256::from(staking.prev_stake_block_number)),
734            (PREV_STAKE_LIMIT_ATTR, staking.prev_stake_limit),
735            (MAX_STAKE_LIMIT_GROWTH_BLOCKS_ATTR, U256::from(staking.max_stake_limit_growth_blocks)),
736            (MAX_STAKE_LIMIT_ATTR, staking.max_stake_limit),
737        ]
738        .into_iter()
739        .map(|(name, value)| (name.to_string(), attribute(value)))
740        .collect();
741        let component_id = STETH_COMPONENT_ID.to_string();
742
743        tycho_client::feed::synchronizer::ComponentWithState {
744            state: ProtocolComponentState {
745                component_id: component_id.clone(),
746                attributes,
747                balances: HashMap::new(),
748            },
749            component: ProtocolComponent {
750                id: component_id,
751                protocol_system: "lido_v4".to_string(),
752                protocol_type_name: "lido_v4_pool".to_string(),
753                chain: Chain::Ethereum,
754                tokens: Vec::new(),
755                contract_addresses: Vec::new(),
756                static_attributes: HashMap::new(),
757                change: Default::default(),
758                creation_tx: Bytes::new(),
759                created_at: chrono::DateTime::UNIX_EPOCH.naive_utc(),
760            },
761            component_tvl: None,
762            entrypoints: Vec::new(),
763        }
764    }
765
766    /// One component carries every attribute, so the decoded state is complete for all four
767    /// directions - the stake limit that bounds the two submit paths and the wrapper's shares
768    /// that bound unwrapping.
769    #[tokio::test]
770    async fn decoder_reads_the_snapshot() {
771        let state = try_decode_snapshot_with_defaults::<LidoV4State>(snapshot())
772            .await
773            .unwrap();
774        let expected = sample_state();
775
776        assert_eq!(state.total_shares, expected.total_shares);
777        assert_eq!(state.external_shares, expected.external_shares);
778        assert_eq!(state.buffered_ether, expected.buffered_ether);
779        assert_eq!(state.deposited_post_report, expected.deposited_post_report);
780        assert_eq!(state.cl_validators_balance, expected.cl_validators_balance);
781        assert_eq!(state.cl_pending_balance, expected.cl_pending_balance);
782        assert_eq!(state.staking_state, expected.staking_state);
783        assert_eq!(state.wsteth_shares, expected.wsteth_shares);
784    }
785
786    /// A whole word where the package emits a `getLowAndHighUint128` half cannot be a value the
787    /// package produced, so the decoder reports it by name.
788    #[tokio::test]
789    async fn decoder_rejects_an_attribute_wider_than_its_field() {
790        let mut snapshot = snapshot();
791        snapshot.state.attributes.insert(
792            TOTAL_SHARES_ATTR.to_string(),
793            Bytes::from(
794                sample_state()
795                    .total_shares
796                    .to_be_bytes_vec(),
797            ),
798        );
799
800        let err = try_decode_snapshot_with_defaults::<LidoV4State>(snapshot)
801            .await
802            .unwrap_err();
803
804        let InvalidSnapshotError::ValueError(message) = err else {
805            panic!("expected a value error, got {err:?}");
806        };
807        assert!(message.contains(TOTAL_SHARES_ATTR), "{message}");
808    }
809
810    /// The width of every attribute is the width of the stETH field it is unpacked from, so each
811    /// one has to be pinned on its own: a width that is too generous accepts a value the field
812    /// cannot hold, and one that is too tight rejects a value the package legitimately emits.
813    #[test]
814    fn every_attribute_is_read_at_the_width_of_its_field() {
815        let widths: HashMap<&str, usize> = HashMap::from([
816            (TOTAL_SHARES_ATTR, 16),
817            (EXTERNAL_SHARES_ATTR, 16),
818            (BUFFERED_ETHER_ATTR, 16),
819            (DEPOSITED_POST_REPORT_ATTR, 16),
820            (CL_VALIDATORS_BALANCE_ATTR, 16),
821            (CL_PENDING_BALANCE_ATTR, 16),
822            (PREV_STAKE_BLOCK_NUMBER_ATTR, 4),
823            (MAX_STAKE_LIMIT_GROWTH_BLOCKS_ATTR, 4),
824            (PREV_STAKE_LIMIT_ATTR, 12),
825            (MAX_STAKE_LIMIT_ATTR, 12),
826            (WSTETH_SHARES_ATTR, 32),
827        ]);
828        assert_eq!(widths.len(), COMPONENT_ATTRS.len());
829
830        for name in COMPONENT_ATTRS {
831            let width = widths[name];
832            decode_attribute(name, &vec![0xffu8; width])
833                .unwrap_or_else(|e| panic!("{name} rejects a full {width}-byte field: {e}"));
834            let err = decode_attribute(name, &vec![0xffu8; width + 1])
835                .expect_err("a value wider than the field is malformed");
836            assert!(err.contains(name), "{err}");
837        }
838    }
839
840    #[tokio::test]
841    async fn decoder_rejects_an_unknown_component_id() {
842        let mut snapshot = snapshot();
843        snapshot.component.id = "0xdeadbeef".to_string();
844
845        assert!(try_decode_snapshot_with_defaults::<LidoV4State>(snapshot)
846            .await
847            .is_err());
848    }
849
850    #[test]
851    fn eth_to_steth_updates_state_and_consumes_stake_limit() {
852        let state = sample_state();
853        let amount_in = BigUint::from(10u64).pow(18);
854        let result = state
855            .get_amount_out(amount_in, &eth_token(), &steth_token())
856            .unwrap();
857
858        assert!(result.amount > BigUint::ZERO);
859        let new_state = result
860            .new_state
861            .as_any()
862            .downcast_ref::<LidoV4State>()
863            .unwrap();
864        assert_eq!(
865            new_state.buffered_ether,
866            state.buffered_ether + U256::from(10).pow(U256::from(18))
867        );
868        assert!(new_state.total_shares > state.total_shares);
869        let old_limit = state
870            .staking_state
871            .current_limit(state.execution_block_number);
872        let new_limit = new_state
873            .staking_state
874            .current_limit(new_state.execution_block_number);
875        assert!(new_limit < old_limit);
876    }
877
878    /// Both legs move the stETH the wrapper holds, and that balance is what bounds unwrapping,
879    /// so a consumer walking the returned state has to see it change.
880    #[test]
881    fn wrapping_and_unwrapping_move_the_wrapper_shares() {
882        let state = sample_state();
883        let amount_in = BigUint::from(10u64).pow(18);
884
885        let wrap = state
886            .get_amount_out(amount_in.clone(), &steth_token(), &wsteth_token())
887            .expect("wrap");
888        let wrapped = wrap
889            .new_state
890            .as_any()
891            .downcast_ref::<LidoV4State>()
892            .unwrap();
893        // `wrap` pulls the stETH in, so the wrapper holds the shares it just minted on top.
894        assert_eq!(wrapped.wsteth_shares, state.wsteth_shares + biguint_to_u256(&wrap.amount));
895
896        let unwrap = state
897            .get_amount_out(amount_in.clone(), &wsteth_token(), &steth_token())
898            .expect("unwrap");
899        let unwrapped = unwrap
900            .new_state
901            .as_any()
902            .downcast_ref::<LidoV4State>()
903            .unwrap();
904        // `unwrap` pays the stETH out and `transfer` re-derives the shares it is worth. Both
905        // conversions round down, so the wrapper keeps one wei-share of what was burnt.
906        assert_eq!(
907            unwrapped.wsteth_shares,
908            state.wsteth_shares - biguint_to_u256(&amount_in) + U256::ONE
909        );
910    }
911
912    /// Draining the wrapper moves the bound down to what is left, which is the dust the two
913    /// roundings strand and stETH cannot pay out.
914    #[test]
915    fn unwrapping_the_whole_wrapper_strands_the_rounding_dust() {
916        let state = sample_state();
917        let (max_in, _) = state
918            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
919            .expect("limits");
920
921        let drained = state
922            .get_amount_out(max_in.clone(), &wsteth_token(), &steth_token())
923            .expect("drain");
924        let drained = drained
925            .new_state
926            .as_any()
927            .downcast_ref::<LidoV4State>()
928            .unwrap();
929
930        assert_eq!(drained.wsteth_shares, U256::ONE);
931        let (drained_max_in, _) = drained
932            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
933            .expect("limits");
934        assert_eq!(drained_max_in, BigUint::ZERO);
935        // And a second unwrap of the original size is refused.
936        assert!(drained
937            .get_amount_out(max_in, &wsteth_token(), &steth_token())
938            .is_err());
939    }
940
941    #[test]
942    fn unwrap_quotes_transferred_shares_and_rejects_zero_receipts() {
943        let mut state = sample_state();
944        state.total_shares = U256::from(10);
945        state.external_shares = U256::ZERO;
946        state.buffered_ether = U256::from(15);
947        state.deposited_post_report = U256::ZERO;
948        state.cl_validators_balance = U256::ZERO;
949        state.cl_pending_balance = U256::ZERO;
950        state.wsteth_shares = U256::from(3);
951        let quote = state
952            .get_amount_out(BigUint::from(3u8), &wsteth_token(), &steth_token())
953            .unwrap();
954        assert_eq!(quote.amount, BigUint::from(3u8));
955        assert_eq!(
956            state
957                .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
958                .unwrap(),
959            (BigUint::from(3u8), BigUint::from(3u8))
960        );
961        assert!(
962            matches!(state.get_amount_out(BigUint::from(1u8), &wsteth_token(), &steth_token()),
963            Err(SimulationError::RecoverableError(message)) if message == "ZERO_OUTPUT")
964        );
965        state.wsteth_shares = U256::ONE;
966        assert_eq!(
967            state
968                .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
969                .unwrap(),
970            (BigUint::ZERO, BigUint::ZERO)
971        );
972    }
973
974    #[test]
975    fn unwrap_limit_respects_the_steth_transfer_amount_bound() {
976        let mut state = sample_state();
977        let cap = U256::from(u128::MAX);
978        state.total_shares = cap / U256::from(2);
979        state.external_shares = U256::ZERO;
980        state.buffered_ether = cap;
981        state.deposited_post_report = U256::ZERO;
982        state.cl_validators_balance = U256::ZERO;
983        state.cl_pending_balance = U256::ZERO;
984        state.wsteth_shares = state.total_shares;
985        let (max_sell, max_buy) = state
986            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
987            .unwrap();
988        assert_eq!(max_sell, u256_to_biguint(state.total_shares - U256::ONE));
989        assert_eq!(max_buy, u256_to_biguint(cap - U256::from(5)));
990        let quote = state
991            .get_amount_out(max_sell.clone(), &wsteth_token(), &steth_token())
992            .unwrap();
993        assert_eq!(quote.amount, max_buy);
994        assert!(state
995            .get_amount_out(max_sell + BigUint::from(1u8), &wsteth_token(), &steth_token())
996            .is_err());
997    }
998
999    #[test]
1000    fn oversized_input_returns_an_error() {
1001        assert!(matches!(
1002            sample_state().get_amount_out(
1003                BigUint::from(1u8) << 256usize,
1004                &eth_token(),
1005                &steth_token()
1006            ),
1007            Err(SimulationError::InvalidInput(_, _))
1008        ));
1009    }
1010
1011    #[test]
1012    fn wrap_refuses_more_than_the_reported_supply() {
1013        let state = sample_state();
1014        let (limit, _) = state
1015            .get_limits(Bytes::from(STETH_ADDRESS), Bytes::from(WSTETH_ADDRESS))
1016            .unwrap();
1017        assert!(state
1018            .get_amount_out(limit + BigUint::from(1u8), &steth_token(), &wsteth_token())
1019            .is_err());
1020    }
1021
1022    #[test]
1023    fn mint_limits_respect_storage_headroom() {
1024        let cap = U256::from(u128::MAX);
1025        for (shares, buffer, validators, expected_limit) in [
1026            (cap - U256::from(10), U256::ONE, cap - U256::from(11), 10u64),
1027            (cap - U256::from(100), cap - U256::from(10), U256::ZERO, 10),
1028            (cap - U256::from(10), U256::from(100), U256::ZERO, 0),
1029            (U256::from(100), cap - U256::from(10), U256::ZERO, 0),
1030        ] {
1031            let mut state = sample_state();
1032            state.total_shares = shares;
1033            state.external_shares = U256::ZERO;
1034            state.buffered_ether = buffer;
1035            state.deposited_post_report = U256::ZERO;
1036            state.cl_validators_balance = validators;
1037            state.cl_pending_balance = U256::ZERO;
1038            state.staking_state.max_stake_limit = U256::ZERO;
1039            for output in [steth_token(), wsteth_token()] {
1040                let (limit, _) = state
1041                    .get_limits(Bytes::from(ETH_ADDRESS), output.address.clone())
1042                    .unwrap();
1043                assert_eq!(limit, BigUint::from(expected_limit));
1044                if limit != BigUint::ZERO {
1045                    let quote = state
1046                        .get_amount_out(limit.clone(), &eth_token(), &output)
1047                        .unwrap();
1048                    let next = quote
1049                        .new_state
1050                        .as_any()
1051                        .downcast_ref::<LidoV4State>()
1052                        .unwrap();
1053                    assert!(next.total_shares <= cap);
1054                    assert!(next.buffered_ether <= cap);
1055                }
1056                assert!(state
1057                    .get_amount_out(limit + BigUint::from(1u8), &eth_token(), &output)
1058                    .is_err());
1059            }
1060        }
1061    }
1062
1063    /// Every direction reverts on chain at a zero amount.
1064    #[test]
1065    fn zero_amount_is_refused_in_every_direction() {
1066        let state = sample_state();
1067        for (token_in, token_out) in [
1068            (eth_token(), steth_token()),
1069            (eth_token(), wsteth_token()),
1070            (steth_token(), wsteth_token()),
1071            (wsteth_token(), steth_token()),
1072        ] {
1073            let err = state
1074                .get_amount_out(BigUint::ZERO, &token_in, &token_out)
1075                .unwrap_err();
1076            assert!(
1077                matches!(err, SimulationError::RecoverableError(ref m) if m == "ZERO_AMOUNT"),
1078                "{} -> {} quoted a zero amount",
1079                token_in.symbol,
1080                token_out.symbol
1081            );
1082        }
1083    }
1084
1085    #[test]
1086    fn spot_price_covers_every_tradable_direction() {
1087        let state = sample_state();
1088
1089        // Submitting is at parity, and wrapping is the share rate, so the two wstETH legs agree.
1090        let steth_per_eth = state
1091            .spot_price(&eth_token(), &steth_token())
1092            .expect("ETH -> stETH price");
1093        let wsteth_per_eth = state
1094            .spot_price(&eth_token(), &wsteth_token())
1095            .expect("ETH -> wstETH price");
1096        let wsteth_per_steth = state
1097            .spot_price(&steth_token(), &wsteth_token())
1098            .expect("stETH -> wstETH price");
1099        let steth_per_wsteth = state
1100            .spot_price(&wsteth_token(), &steth_token())
1101            .expect("wstETH -> stETH price");
1102
1103        assert!((steth_per_eth - 1.0).abs() < 1e-6, "submit off parity: {steth_per_eth}");
1104        assert_eq!(wsteth_per_eth, wsteth_per_steth);
1105        assert!((wsteth_per_steth * steth_per_wsteth - 1.0).abs() < 1e-9);
1106    }
1107
1108    #[test]
1109    fn spot_price_survives_exhausted_staking_capacity() {
1110        let mut state = sample_state();
1111        let mut staking_state = state.staking_state;
1112        // Capacity gone, but the pair still has a rate: the limit bounds size, not price.
1113        staking_state.prev_stake_limit = U256::ZERO;
1114        staking_state.prev_stake_block_number =
1115            u32::try_from(state.execution_block_number).unwrap();
1116        staking_state.max_stake_limit_growth_blocks = 0;
1117        state.staking_state = staking_state;
1118
1119        // A quote is unavailable ...
1120        assert!(state
1121            .get_amount_out(BigUint::from(10u64).pow(18), &eth_token(), &steth_token())
1122            .is_err());
1123        // ... but the price still resolves, for both submit paths.
1124        assert!(state
1125            .spot_price(&eth_token(), &steth_token())
1126            .is_ok());
1127        assert!(state
1128            .spot_price(&eth_token(), &wsteth_token())
1129            .is_ok());
1130    }
1131
1132    #[test]
1133    fn spot_price_rejects_a_token_the_venue_does_not_hold() {
1134        let weth = Token::new(&Bytes::from([0xc0u8; 20]), "WETH", 18, 0, &[], Chain::Ethereum, 100);
1135
1136        assert!(sample_state()
1137            .spot_price(&weth, &steth_token())
1138            .is_err());
1139    }
1140
1141    #[test]
1142    fn get_limits_unwrap_is_bounded_by_wrapper_shares() {
1143        let state = sample_state();
1144
1145        let (max_in, max_out) = state
1146            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
1147            .unwrap();
1148
1149        // Unwrapping pays out of the wrapper's stETH, so the limit is its share balance.
1150        assert_eq!(max_in, u256_to_biguint(sample_wsteth_shares()));
1151        assert_eq!(
1152            max_out,
1153            u256_to_biguint(
1154                state
1155                    .pooled_eth_by_shares(
1156                        state
1157                            .shares_for_pooled_eth(
1158                                state
1159                                    .pooled_eth_by_shares(sample_wsteth_shares())
1160                                    .unwrap()
1161                            )
1162                            .unwrap()
1163                    )
1164                    .unwrap()
1165            )
1166        );
1167        assert!(max_in < u256_to_biguint(U256::from(UINT128_MAX_EXCLUSIVE) - U256::ONE));
1168    }
1169
1170    #[test]
1171    fn get_limits_wrap_is_bounded_by_steth_supply() {
1172        let state = sample_state();
1173
1174        let (max_in, max_out) = state
1175            .get_limits(Bytes::from(STETH_ADDRESS), Bytes::from(WSTETH_ADDRESS))
1176            .unwrap();
1177
1178        // No more stETH can be wrapped than exists, and what exists is `totalSupply()`: the
1179        // internal ether plus the ether backing the externally minted shares.
1180        let supply = U256::from_str_radix("21803278404946205780741210", 10).expect("supply");
1181        assert_eq!(max_in, u256_to_biguint(supply));
1182        assert!(max_in > u256_to_biguint(state.internal_ether()), "external ether is missing");
1183        // Wrapping the whole supply mints every share but the one the round trip rounds away.
1184        assert_eq!(max_out, u256_to_biguint(state.total_shares - U256::ONE));
1185        assert!(max_in < u256_to_biguint(U256::from(UINT128_MAX_EXCLUSIVE) - U256::ONE));
1186    }
1187
1188    #[test]
1189    fn get_limits_unwrap_with_empty_wrapper_returns_zero() {
1190        let mut state = sample_state();
1191        state.wsteth_shares = U256::ZERO;
1192
1193        let (max_in, max_out) = state
1194            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
1195            .unwrap();
1196
1197        assert_eq!(max_in, BigUint::ZERO);
1198        assert_eq!(max_out, BigUint::ZERO);
1199    }
1200
1201    #[test]
1202    fn decoder_reads_wsteth_shares() {
1203        let state = sample_state();
1204        assert_eq!(state.wsteth_shares, sample_wsteth_shares());
1205    }
1206
1207    #[test]
1208    fn get_limits_unsupported_direction_returns_zero() {
1209        let state = sample_state();
1210
1211        let (max_in, max_out) = state
1212            .get_limits(Bytes::from(STETH_ADDRESS), Bytes::from(ETH_ADDRESS))
1213            .expect("limits");
1214
1215        assert_eq!(max_in, BigUint::ZERO);
1216        assert_eq!(max_out, BigUint::ZERO);
1217    }
1218
1219    #[test]
1220    fn get_limits_respects_current_stake_limit() {
1221        let state = sample_state();
1222        let (max_in, max_out) = state
1223            .get_limits(Bytes::from(ETH_ADDRESS), Bytes::from(STETH_ADDRESS))
1224            .unwrap();
1225
1226        assert_eq!(
1227            max_in,
1228            u256_to_biguint(
1229                state
1230                    .staking_state
1231                    .current_limit(state.execution_block_number)
1232            )
1233        );
1234        assert!(max_out > BigUint::ZERO);
1235    }
1236
1237    #[test]
1238    fn paused_staking_blocks_eth_to_steth() {
1239        let mut state = sample_state();
1240        let mut staking_state = state.staking_state;
1241        staking_state.prev_stake_block_number = 0;
1242        state.staking_state = staking_state;
1243
1244        let err = state
1245            .get_amount_out(BigUint::from(10u64).pow(18), &eth_token(), &steth_token())
1246            .unwrap_err();
1247
1248        assert!(
1249            matches!(err, SimulationError::RecoverableError(ref msg) if msg == "STAKING_PAUSED")
1250        );
1251    }
1252
1253    #[test]
1254    fn delta_transition_updates_state() {
1255        let mut state = sample_state();
1256        let new_total = U256::from(999u64);
1257        let new_external = U256::from(111u64);
1258        let new_buffered = U256::from(222u64);
1259        let new_deposited_post_report = U256::from(333u64);
1260        let new_cl_validators_balance = U256::from(444u64);
1261        let new_cl_pending_balance = U256::from(555u64);
1262        let new_staking_state = StakingState {
1263            prev_stake_block_number: 77,
1264            prev_stake_limit: U256::from(888u64),
1265            max_stake_limit_growth_blocks: 9,
1266            max_stake_limit: U256::from(999u64),
1267        };
1268
1269        state
1270            .delta_transition(
1271                ProtocolStateDelta {
1272                    component_id: STETH_COMPONENT_ID.to_string(),
1273                    updated_attributes: HashMap::from([
1274                        (TOTAL_SHARES_ATTR.to_string(), attribute(new_total)),
1275                        (EXTERNAL_SHARES_ATTR.to_string(), attribute(new_external)),
1276                        (BUFFERED_ETHER_ATTR.to_string(), attribute(new_buffered)),
1277                        (
1278                            DEPOSITED_POST_REPORT_ATTR.to_string(),
1279                            attribute(new_deposited_post_report),
1280                        ),
1281                        (
1282                            CL_VALIDATORS_BALANCE_ATTR.to_string(),
1283                            attribute(new_cl_validators_balance),
1284                        ),
1285                        (CL_PENDING_BALANCE_ATTR.to_string(), attribute(new_cl_pending_balance)),
1286                        (
1287                            PREV_STAKE_BLOCK_NUMBER_ATTR.to_string(),
1288                            attribute(U256::from(new_staking_state.prev_stake_block_number)),
1289                        ),
1290                        (
1291                            PREV_STAKE_LIMIT_ATTR.to_string(),
1292                            attribute(new_staking_state.prev_stake_limit),
1293                        ),
1294                        (
1295                            MAX_STAKE_LIMIT_GROWTH_BLOCKS_ATTR.to_string(),
1296                            attribute(U256::from(new_staking_state.max_stake_limit_growth_blocks)),
1297                        ),
1298                        (
1299                            MAX_STAKE_LIMIT_ATTR.to_string(),
1300                            attribute(new_staking_state.max_stake_limit),
1301                        ),
1302                    ]),
1303                    deleted_attributes: Default::default(),
1304                },
1305                &HashMap::new(),
1306                &Balances::default(),
1307            )
1308            .unwrap();
1309
1310        assert_eq!(state.total_shares, new_total);
1311        assert_eq!(state.external_shares, new_external);
1312        assert_eq!(state.buffered_ether, new_buffered);
1313        assert_eq!(state.deposited_post_report, new_deposited_post_report);
1314        assert_eq!(state.cl_validators_balance, new_cl_validators_balance);
1315        assert_eq!(state.cl_pending_balance, new_cl_pending_balance);
1316        assert_eq!(state.staking_state, new_staking_state);
1317    }
1318
1319    /// `prev_stake_block_number` is a 32-bit field. A five-byte value cannot come from the
1320    /// package, and narrowing it would wrap the block the stake limit accrues from.
1321    #[test]
1322    fn delta_transition_rejects_a_block_number_wider_than_its_field() {
1323        let mut state = sample_state();
1324        let before = state.clone();
1325
1326        let err = state
1327            .delta_transition(
1328                ProtocolStateDelta {
1329                    component_id: STETH_COMPONENT_ID.to_string(),
1330                    updated_attributes: HashMap::from([
1331                        (TOTAL_SHARES_ATTR.to_string(), attribute(U256::from(1u64))),
1332                        (
1333                            PREV_STAKE_BLOCK_NUMBER_ATTR.to_string(),
1334                            attribute(U256::from(1u64) << 32),
1335                        ),
1336                    ]),
1337                    deleted_attributes: Default::default(),
1338                },
1339                &HashMap::new(),
1340                &Balances::default(),
1341            )
1342            .unwrap_err();
1343
1344        let TransitionError::DecodeError(message) = err else {
1345            panic!("expected a decode error, got {err:?}");
1346        };
1347        assert!(message.contains(PREV_STAKE_BLOCK_NUMBER_ATTR), "{message}");
1348        assert_eq!(state, before, "a rejected delta must leave the state untouched");
1349    }
1350
1351    #[test]
1352    fn unwrap_quote_is_bounded_by_wrapper_shares() {
1353        let state = sample_state();
1354        let (max_in, _) = state
1355            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
1356            .expect("limits");
1357
1358        // At the limit it quotes ...
1359        assert!(state
1360            .get_amount_out(max_in.clone(), &wsteth_token(), &steth_token())
1361            .is_ok());
1362        // ... and one wei past it, it refuses. `get_limits` and `get_amount_out` have to agree
1363        // on the same bound.
1364        let err = state
1365            .get_amount_out(max_in + BigUint::from(1u64), &wsteth_token(), &steth_token())
1366            .unwrap_err();
1367        assert!(matches!(err, SimulationError::RecoverableError(ref m) if m == "UNWRAP_LIMIT"));
1368    }
1369
1370    #[test]
1371    fn eth_to_wsteth_mints_the_submitted_shares() {
1372        let state = sample_state();
1373        let amount_in = BigUint::from(10u64).pow(18);
1374
1375        let result = state
1376            .get_amount_out(amount_in.clone(), &eth_token(), &wsteth_token())
1377            .expect("quote");
1378
1379        // `receive()` mints exactly the shares `submit` returned.
1380        let expected = state
1381            .shares_for_pooled_eth(biguint_to_u256(&amount_in))
1382            .unwrap();
1383        assert_eq!(result.amount, u256_to_biguint(expected));
1384
1385        let new_state = result
1386            .new_state
1387            .as_any()
1388            .downcast_ref::<LidoV4State>()
1389            .unwrap();
1390        // The submitted ETH is buffered, the shares are minted, and they land on the wrapper.
1391        assert_eq!(new_state.buffered_ether, state.buffered_ether + biguint_to_u256(&amount_in));
1392        assert_eq!(new_state.total_shares, state.total_shares + expected);
1393        assert_eq!(new_state.wsteth_shares, state.wsteth_shares + expected);
1394    }
1395
1396    #[test]
1397    fn eth_to_wsteth_is_bounded_by_the_stake_limit() {
1398        let state = sample_state();
1399
1400        let (max_in, max_out) = state
1401            .get_limits(Bytes::from(ETH_ADDRESS), Bytes::from(WSTETH_ADDRESS))
1402            .expect("limits");
1403
1404        assert_eq!(
1405            max_in,
1406            u256_to_biguint(
1407                state
1408                    .staking_state
1409                    .current_limit(state.execution_block_number)
1410            )
1411        );
1412        assert!(max_out > BigUint::ZERO);
1413    }
1414
1415    #[test]
1416    fn eth_to_wsteth_beats_routing_through_steth() {
1417        let state = sample_state();
1418        let amount_in = BigUint::from(10u64).pow(18);
1419
1420        let direct = state
1421            .get_amount_out(amount_in.clone(), &eth_token(), &wsteth_token())
1422            .expect("direct");
1423        // The two-hop route: submit on the stETH component, then wrap on this one.
1424        let submitted = sample_state()
1425            .get_amount_out(amount_in, &eth_token(), &steth_token())
1426            .expect("submit");
1427        let wrapped = state
1428            .get_amount_out(submitted.amount, &steth_token(), &wsteth_token())
1429            .expect("wrap");
1430
1431        assert!(direct.amount >= wrapped.amount, "shortcut must not quote worse");
1432        assert!(direct.gas < submitted.gas + wrapped.gas, "shortcut must be cheaper");
1433    }
1434
1435    /// One component carries three tokens, so a caller can ask for any of six orderings. Only
1436    /// the four the venue performs may quote; the two that would unstake have to report a zero
1437    /// limit and refuse to price or swap, in every method, or a router builds a leg that cannot
1438    /// settle.
1439    #[test]
1440    fn component_serves_only_the_four_directions_the_venue_performs() {
1441        let state = sample_state();
1442        let amount = BigUint::from(10u64).pow(18);
1443
1444        let tradable = [
1445            (eth_token(), steth_token()),
1446            (steth_token(), wsteth_token()),
1447            (wsteth_token(), steth_token()),
1448            (eth_token(), wsteth_token()),
1449        ];
1450        // Unstaking runs through the asynchronous withdrawal queue.
1451        let untradable = [(steth_token(), eth_token()), (wsteth_token(), eth_token())];
1452
1453        for (token_in, token_out) in &tradable {
1454            let pair = format!("{} -> {}", token_in.symbol, token_out.symbol);
1455            let (max_in, max_out) = state
1456                .get_limits(token_in.address.clone(), token_out.address.clone())
1457                .unwrap_or_else(|e| panic!("{pair} limits: {e:?}"));
1458            assert!(max_in > BigUint::ZERO, "{pair} has no input capacity");
1459            assert!(max_out > BigUint::ZERO, "{pair} has no output capacity");
1460            assert!(
1461                state
1462                    .spot_price(token_in, token_out)
1463                    .is_ok(),
1464                "{pair} has no price"
1465            );
1466            assert!(
1467                state
1468                    .get_amount_out(amount.clone(), token_in, token_out)
1469                    .is_ok(),
1470                "{pair} does not quote"
1471            );
1472        }
1473
1474        // A token the component does not hold is a different answer from "no capacity".
1475        let weth = Token::new(&Bytes::from([0xc0u8; 20]), "WETH", 18, 0, &[], Chain::Ethereum, 100);
1476        assert!(
1477            state
1478                .get_limits(weth.address.clone(), steth_token().address)
1479                .is_err(),
1480            "an unknown token reported a limit instead of an error"
1481        );
1482        assert!(state
1483            .spot_price(&weth, &steth_token())
1484            .is_err());
1485        assert!(state
1486            .get_amount_out(amount.clone(), &weth, &steth_token())
1487            .is_err());
1488
1489        for (token_in, token_out) in &untradable {
1490            let pair = format!("{} -> {}", token_in.symbol, token_out.symbol);
1491            assert_eq!(
1492                state
1493                    .get_limits(token_in.address.clone(), token_out.address.clone())
1494                    .unwrap_or_else(|e| panic!("{pair} limits: {e:?}")),
1495                (BigUint::ZERO, BigUint::ZERO),
1496                "{pair} reports capacity it cannot settle"
1497            );
1498            assert!(
1499                state
1500                    .spot_price(token_in, token_out)
1501                    .is_err(),
1502                "{pair} has a price"
1503            );
1504            assert!(
1505                state
1506                    .get_amount_out(amount.clone(), token_in, token_out)
1507                    .is_err(),
1508                "{pair} quotes a swap the venue cannot perform"
1509            );
1510        }
1511    }
1512
1513    /// State read from stETH storage at the Lido v4 migration block 25603297. Pricing
1514    /// `sharesOf(wstETH)` at the share rate has to land on `stETH.balanceOf(wstETH)` from the
1515    /// same block, which pins the v4 pooled-ether formula to the chain.
1516    #[test]
1517    fn share_rate_matches_chain_on_the_v4_storage_layout() {
1518        let state = LidoV4State::new(
1519            25_603_297,
1520            U256::from_str_radix("7526667021904051320418763", 10).unwrap(),
1521            U256::from_str_radix("3721126242498807385407", 10).unwrap(),
1522            U256::from_str_radix("539569870340371095571", 10).unwrap(),
1523            U256::from_str_radix("761440000000000000000000", 10).unwrap(),
1524            U256::from_str_radix("8567227049119653000000000", 10).unwrap(),
1525            U256::ZERO,
1526            sample_staking_state(),
1527            U256::from_str_radix("3628434125893615122886002", 10).unwrap(),
1528        );
1529
1530        let wsteth_backing = state
1531            .pooled_eth_by_shares(state.wsteth_shares)
1532            .unwrap();
1533
1534        assert_eq!(wsteth_backing, U256::from_str_radix("4499621841408863271318368", 10).unwrap());
1535    }
1536
1537    #[test]
1538    fn unsupported_direction_errors() {
1539        let err = sample_state()
1540            .get_amount_out(BigUint::from(10u64).pow(18), &steth_token(), &eth_token())
1541            .unwrap_err();
1542        assert!(matches!(err, SimulationError::FatalError(_)));
1543    }
1544
1545    #[tokio::test]
1546    async fn decoder_seeds_the_execution_block_from_the_header() {
1547        let snapshot = snapshot();
1548        let state = LidoV4State::try_from_with_header(
1549            snapshot,
1550            BlockHeader {
1551                number: 123,
1552                timestamp: 456,
1553                hash: Bytes::new(),
1554                parent_hash: Bytes::new(),
1555                revert: false,
1556                partial_block_index: None,
1557            },
1558            &HashMap::new(),
1559            &HashMap::new(),
1560            &Default::default(),
1561        )
1562        .await
1563        .unwrap();
1564
1565        assert_eq!(state.execution_block_number, 123);
1566    }
1567
1568    /// The stake limit accrues per block, so an idle block still has to move it - that is the
1569    /// whole reason the block cannot come in on a delta.
1570    #[test]
1571    fn apply_block_accrues_the_stake_limit_without_a_delta() {
1572        let mut state = sample_state();
1573        // The fixture starts at `max_stake_limit`, where nothing can accrue. A partly consumed
1574        // limit is the case this guards.
1575        state.staking_state.prev_stake_limit = state.staking_state.max_stake_limit / U256::from(2);
1576        let limit_before = state
1577            .staking_state
1578            .current_limit(state.execution_block_number);
1579
1580        let changed = state.apply_block(&BlockContext::new(state.execution_block_number + 1, 0));
1581
1582        assert!(changed, "an accruing limit must re-emit");
1583        assert!(
1584            state
1585                .staking_state
1586                .current_limit(state.execution_block_number) >
1587                limit_before
1588        );
1589    }
1590
1591    #[test]
1592    fn apply_block_is_idempotent_for_a_repeated_block() {
1593        let mut state = sample_state();
1594        let block = BlockContext::new(state.execution_block_number, 0);
1595
1596        assert!(!state.apply_block(&block));
1597        assert!(!state.apply_block(&block));
1598    }
1599
1600    /// Once the limit sits at `max_stake_limit` it cannot grow further, so later blocks must not
1601    /// keep re-emitting the state to consumers.
1602    #[test]
1603    fn apply_block_does_not_re_emit_once_the_limit_is_saturated() {
1604        let mut state = sample_state();
1605        state.staking_state.prev_stake_limit = state.staking_state.max_stake_limit / U256::from(2);
1606        state.apply_block(&BlockContext::new(state.execution_block_number + 10_000_000, 0));
1607        let saturated = state
1608            .staking_state
1609            .current_limit(state.execution_block_number);
1610        assert_eq!(saturated, state.staking_state.max_stake_limit);
1611
1612        let changed = state.apply_block(&BlockContext::new(state.execution_block_number + 1, 0));
1613
1614        assert!(!changed);
1615    }
1616
1617    fn every_token_pair() -> Vec<(Bytes, Bytes)> {
1618        let tokens = [ETH_ADDRESS, STETH_ADDRESS, WSTETH_ADDRESS];
1619        let mut pairs = Vec::new();
1620        for sell in tokens {
1621            for buy in tokens {
1622                if sell != buy {
1623                    pairs.push((Bytes::from(sell), Bytes::from(buy)));
1624                }
1625            }
1626        }
1627        pairs
1628    }
1629
1630    /// A reported limit has to be a trade the venue performs: quoting at it must succeed and
1631    /// return exactly the reported output.
1632    #[test]
1633    fn every_reported_limit_quotes_at_its_own_size() {
1634        let state = sample_state();
1635        for (sell, buy) in every_token_pair() {
1636            let (max_in, max_out) = state
1637                .get_limits(sell.clone(), buy.clone())
1638                .expect("a pair the component holds");
1639            if max_in == BigUint::ZERO {
1640                assert_eq!(max_out, BigUint::ZERO, "{sell:x} -> {buy:x} pays out of a zero limit");
1641                continue;
1642            }
1643            let token_in = Token::new(&sell, "in", 18, 0, &[], Chain::Ethereum, 100);
1644            let token_out = Token::new(&buy, "out", 18, 0, &[], Chain::Ethereum, 100);
1645            let quoted = state
1646                .get_amount_out(max_in, &token_in, &token_out)
1647                .unwrap_or_else(|e| panic!("{sell:x} -> {buy:x} limit does not quote: {e:?}"));
1648            assert_eq!(quoted.amount, max_out, "{sell:x} -> {buy:x} limit disagrees with quote");
1649        }
1650    }
1651
1652    /// The share rate is applied in one direction or the other, and the two are inverse up to
1653    /// their rounding, so neither can be applied to a figure already in the other unit.
1654    #[test]
1655    fn shares_and_pooled_ether_round_trip() {
1656        let state = sample_state();
1657        // Each division truncates by under one unit, and the first loss is then scaled
1658        // by the share rate, so a round trip can lose the rate plus one.
1659        let tolerance = state
1660            .pooled_eth_by_shares(U256::ONE)
1661            .expect("rate") +
1662            U256::from(2u8);
1663        for exponent in [15u32, 18, 21, 24] {
1664            let amount = U256::from(10u64).pow(U256::from(exponent));
1665            let back = state
1666                .pooled_eth_by_shares(
1667                    state
1668                        .shares_for_pooled_eth(amount)
1669                        .expect("shares"),
1670                )
1671                .expect("amount");
1672            assert!(back <= amount && amount - back <= tolerance, "amount drifted at 1e{exponent}");
1673
1674            let shares = U256::from(10u64).pow(U256::from(exponent));
1675            let back = state
1676                .shares_for_pooled_eth(
1677                    state
1678                        .pooled_eth_by_shares(shares)
1679                        .expect("amount"),
1680                )
1681                .expect("shares");
1682            assert!(back <= shares && shares - back <= tolerance, "shares drifted at 1e{exponent}");
1683        }
1684    }
1685
1686    /// The decoder requires every name the component carries, so a value the package emits
1687    /// cannot be left unread.
1688    #[tokio::test]
1689    async fn decoder_requires_every_attribute_the_component_carries() {
1690        assert_eq!(snapshot().state.attributes.len(), COMPONENT_ATTRS.len());
1691        for name in COMPONENT_ATTRS {
1692            let mut snapshot = snapshot();
1693            snapshot.state.attributes.remove(name);
1694            let err = try_decode_snapshot_with_defaults::<LidoV4State>(snapshot)
1695                .await
1696                .unwrap_err();
1697            let InvalidSnapshotError::MissingAttribute(missing) = err else {
1698                panic!("{name} removed but the decoder did not report it: {err:?}");
1699            };
1700            assert_eq!(missing, name);
1701        }
1702    }
1703
1704    /// A delta and a fresh snapshot of the same attributes produce identical state.
1705    #[tokio::test]
1706    async fn delta_transition_applies_every_attribute_the_component_carries() {
1707        let base = try_decode_snapshot_with_defaults::<LidoV4State>(snapshot())
1708            .await
1709            .unwrap();
1710        for name in COMPONENT_ATTRS {
1711            let mut state = base.clone();
1712            state
1713                .delta_transition(
1714                    ProtocolStateDelta {
1715                        component_id: STETH_COMPONENT_ID.to_string(),
1716                        updated_attributes: HashMap::from([(
1717                            name.to_string(),
1718                            attribute(U256::from(7u64)),
1719                        )]),
1720                        deleted_attributes: Default::default(),
1721                    },
1722                    &HashMap::new(),
1723                    &Balances::default(),
1724                )
1725                .unwrap_or_else(|e| panic!("{name} was rejected: {e:?}"));
1726            let mut updated = snapshot();
1727            updated
1728                .state
1729                .attributes
1730                .insert(name.to_string(), attribute(U256::from(7u64)));
1731            let expected = try_decode_snapshot_with_defaults::<LidoV4State>(updated)
1732                .await
1733                .unwrap();
1734            assert_eq!(state, expected, "{name} updated the wrong state");
1735        }
1736    }
1737
1738    #[test]
1739    fn delta_transition_ignores_unknown_attributes() {
1740        let mut state = sample_state();
1741        let expected = state.clone();
1742        state
1743            .delta_transition(
1744                ProtocolStateDelta {
1745                    component_id: STETH_COMPONENT_ID.to_string(),
1746                    updated_attributes: HashMap::from([(
1747                        "future_parameter".to_string(),
1748                        Bytes::from(vec![0xff; 64]),
1749                    )]),
1750                    deleted_attributes: Default::default(),
1751                },
1752                &HashMap::new(),
1753                &Balances::default(),
1754            )
1755            .unwrap();
1756        assert_eq!(state, expected);
1757    }
1758
1759    /// The stream decoder puts the chain head in every delta. Those names are not Lido
1760    /// attributes and leave the state alone.
1761    #[test]
1762    fn delta_transition_accepts_the_injected_block_attributes() {
1763        let mut state = sample_state();
1764        state
1765            .delta_transition(
1766                ProtocolStateDelta {
1767                    component_id: STETH_COMPONENT_ID.to_string(),
1768                    updated_attributes: HashMap::from([
1769                        (
1770                            "block_number".to_string(),
1771                            Bytes::from(24_083_114u64.to_be_bytes().to_vec()),
1772                        ),
1773                        (
1774                            "block_timestamp".to_string(),
1775                            Bytes::from(1_700_000_000u64.to_be_bytes().to_vec()),
1776                        ),
1777                    ]),
1778                    deleted_attributes: Default::default(),
1779                },
1780                &HashMap::new(),
1781                &Balances::default(),
1782            )
1783            .expect("the injected names are tolerated");
1784        assert_eq!(state, sample_state());
1785    }
1786}