Skip to main content

tycho_simulation/evm/protocol/lido_v4/
state.rs

1use std::{any::Any, collections::HashMap};
2
3use alloy::primitives::{U256, U512};
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_div_u512, safe_mul_u256, safe_sub_u256},
19    u256_num::{biguint_to_uint, 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 whose
225        // minted shares fit the field; a quotient beyond U256 saturates, and `max_input` caps it.
226        let share_capacity = U256::saturating_from(safe_div_u512(
227            share_headroom.widening_mul(self.internal_ether()),
228            U512::from(shares),
229        )?);
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_uint(&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!(
895            wrapped.wsteth_shares,
896            state.wsteth_shares + biguint_to_uint(&wrap.amount).unwrap()
897        );
898
899        let unwrap = state
900            .get_amount_out(amount_in.clone(), &wsteth_token(), &steth_token())
901            .expect("unwrap");
902        let unwrapped = unwrap
903            .new_state
904            .as_any()
905            .downcast_ref::<LidoV4State>()
906            .unwrap();
907        // `unwrap` pays the stETH out and `transfer` re-derives the shares it is worth. Both
908        // conversions round down, so the wrapper keeps one wei-share of what was burnt.
909        assert_eq!(
910            unwrapped.wsteth_shares,
911            state.wsteth_shares - biguint_to_uint(&amount_in).unwrap() + U256::ONE
912        );
913    }
914
915    /// Draining the wrapper moves the bound down to what is left, which is the dust the two
916    /// roundings strand and stETH cannot pay out.
917    #[test]
918    fn unwrapping_the_whole_wrapper_strands_the_rounding_dust() {
919        let state = sample_state();
920        let (max_in, _) = state
921            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
922            .expect("limits");
923
924        let drained = state
925            .get_amount_out(max_in.clone(), &wsteth_token(), &steth_token())
926            .expect("drain");
927        let drained = drained
928            .new_state
929            .as_any()
930            .downcast_ref::<LidoV4State>()
931            .unwrap();
932
933        assert_eq!(drained.wsteth_shares, U256::ONE);
934        let (drained_max_in, _) = drained
935            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
936            .expect("limits");
937        assert_eq!(drained_max_in, BigUint::ZERO);
938        // And a second unwrap of the original size is refused.
939        assert!(drained
940            .get_amount_out(max_in, &wsteth_token(), &steth_token())
941            .is_err());
942    }
943
944    #[test]
945    fn unwrap_quotes_transferred_shares_and_rejects_zero_receipts() {
946        let mut state = sample_state();
947        state.total_shares = U256::from(10);
948        state.external_shares = U256::ZERO;
949        state.buffered_ether = U256::from(15);
950        state.deposited_post_report = U256::ZERO;
951        state.cl_validators_balance = U256::ZERO;
952        state.cl_pending_balance = U256::ZERO;
953        state.wsteth_shares = U256::from(3);
954        let quote = state
955            .get_amount_out(BigUint::from(3u8), &wsteth_token(), &steth_token())
956            .unwrap();
957        assert_eq!(quote.amount, BigUint::from(3u8));
958        assert_eq!(
959            state
960                .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
961                .unwrap(),
962            (BigUint::from(3u8), BigUint::from(3u8))
963        );
964        assert!(
965            matches!(state.get_amount_out(BigUint::from(1u8), &wsteth_token(), &steth_token()),
966            Err(SimulationError::RecoverableError(message)) if message == "ZERO_OUTPUT")
967        );
968        state.wsteth_shares = U256::ONE;
969        assert_eq!(
970            state
971                .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
972                .unwrap(),
973            (BigUint::ZERO, BigUint::ZERO)
974        );
975    }
976
977    #[test]
978    fn unwrap_limit_respects_the_steth_transfer_amount_bound() {
979        let mut state = sample_state();
980        let cap = U256::from(u128::MAX);
981        state.total_shares = cap / U256::from(2);
982        state.external_shares = U256::ZERO;
983        state.buffered_ether = cap;
984        state.deposited_post_report = U256::ZERO;
985        state.cl_validators_balance = U256::ZERO;
986        state.cl_pending_balance = U256::ZERO;
987        state.wsteth_shares = state.total_shares;
988        let (max_sell, max_buy) = state
989            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
990            .unwrap();
991        assert_eq!(max_sell, u256_to_biguint(state.total_shares - U256::ONE));
992        assert_eq!(max_buy, u256_to_biguint(cap - U256::from(5)));
993        let quote = state
994            .get_amount_out(max_sell.clone(), &wsteth_token(), &steth_token())
995            .unwrap();
996        assert_eq!(quote.amount, max_buy);
997        assert!(state
998            .get_amount_out(max_sell + BigUint::from(1u8), &wsteth_token(), &steth_token())
999            .is_err());
1000    }
1001
1002    #[test]
1003    fn oversized_input_returns_an_error() {
1004        assert!(matches!(
1005            sample_state().get_amount_out(
1006                BigUint::from(1u8) << 256usize,
1007                &eth_token(),
1008                &steth_token()
1009            ),
1010            Err(SimulationError::InvalidInput(_, _))
1011        ));
1012    }
1013
1014    #[test]
1015    fn wrap_refuses_more_than_the_reported_supply() {
1016        let state = sample_state();
1017        let (limit, _) = state
1018            .get_limits(Bytes::from(STETH_ADDRESS), Bytes::from(WSTETH_ADDRESS))
1019            .unwrap();
1020        assert!(state
1021            .get_amount_out(limit + BigUint::from(1u8), &steth_token(), &wsteth_token())
1022            .is_err());
1023    }
1024
1025    #[test]
1026    fn mint_limits_respect_storage_headroom() {
1027        let cap = U256::from(u128::MAX);
1028        for (shares, buffer, validators, expected_limit) in [
1029            (cap - U256::from(10), U256::ONE, cap - U256::from(11), 10u64),
1030            (cap - U256::from(100), cap - U256::from(10), U256::ZERO, 10),
1031            (cap - U256::from(10), U256::from(100), U256::ZERO, 0),
1032            (U256::from(100), cap - U256::from(10), U256::ZERO, 0),
1033        ] {
1034            let mut state = sample_state();
1035            state.total_shares = shares;
1036            state.external_shares = U256::ZERO;
1037            state.buffered_ether = buffer;
1038            state.deposited_post_report = U256::ZERO;
1039            state.cl_validators_balance = validators;
1040            state.cl_pending_balance = U256::ZERO;
1041            state.staking_state.max_stake_limit = U256::ZERO;
1042            for output in [steth_token(), wsteth_token()] {
1043                let (limit, _) = state
1044                    .get_limits(Bytes::from(ETH_ADDRESS), output.address.clone())
1045                    .unwrap();
1046                assert_eq!(limit, BigUint::from(expected_limit));
1047                if limit != BigUint::ZERO {
1048                    let quote = state
1049                        .get_amount_out(limit.clone(), &eth_token(), &output)
1050                        .unwrap();
1051                    let next = quote
1052                        .new_state
1053                        .as_any()
1054                        .downcast_ref::<LidoV4State>()
1055                        .unwrap();
1056                    assert!(next.total_shares <= cap);
1057                    assert!(next.buffered_ether <= cap);
1058                }
1059                assert!(state
1060                    .get_amount_out(limit + BigUint::from(1u8), &eth_token(), &output)
1061                    .is_err());
1062            }
1063        }
1064    }
1065
1066    /// Every direction reverts on chain at a zero amount.
1067    #[test]
1068    fn zero_amount_is_refused_in_every_direction() {
1069        let state = sample_state();
1070        for (token_in, token_out) in [
1071            (eth_token(), steth_token()),
1072            (eth_token(), wsteth_token()),
1073            (steth_token(), wsteth_token()),
1074            (wsteth_token(), steth_token()),
1075        ] {
1076            let err = state
1077                .get_amount_out(BigUint::ZERO, &token_in, &token_out)
1078                .unwrap_err();
1079            assert!(
1080                matches!(err, SimulationError::RecoverableError(ref m) if m == "ZERO_AMOUNT"),
1081                "{} -> {} quoted a zero amount",
1082                token_in.symbol,
1083                token_out.symbol
1084            );
1085        }
1086    }
1087
1088    #[test]
1089    fn spot_price_covers_every_tradable_direction() {
1090        let state = sample_state();
1091
1092        // Submitting is at parity, and wrapping is the share rate, so the two wstETH legs agree.
1093        let steth_per_eth = state
1094            .spot_price(&eth_token(), &steth_token())
1095            .expect("ETH -> stETH price");
1096        let wsteth_per_eth = state
1097            .spot_price(&eth_token(), &wsteth_token())
1098            .expect("ETH -> wstETH price");
1099        let wsteth_per_steth = state
1100            .spot_price(&steth_token(), &wsteth_token())
1101            .expect("stETH -> wstETH price");
1102        let steth_per_wsteth = state
1103            .spot_price(&wsteth_token(), &steth_token())
1104            .expect("wstETH -> stETH price");
1105
1106        assert!((steth_per_eth - 1.0).abs() < 1e-6, "submit off parity: {steth_per_eth}");
1107        assert_eq!(wsteth_per_eth, wsteth_per_steth);
1108        assert!((wsteth_per_steth * steth_per_wsteth - 1.0).abs() < 1e-9);
1109    }
1110
1111    #[test]
1112    fn spot_price_survives_exhausted_staking_capacity() {
1113        let mut state = sample_state();
1114        let mut staking_state = state.staking_state;
1115        // Capacity gone, but the pair still has a rate: the limit bounds size, not price.
1116        staking_state.prev_stake_limit = U256::ZERO;
1117        staking_state.prev_stake_block_number =
1118            u32::try_from(state.execution_block_number).unwrap();
1119        staking_state.max_stake_limit_growth_blocks = 0;
1120        state.staking_state = staking_state;
1121
1122        // A quote is unavailable ...
1123        assert!(state
1124            .get_amount_out(BigUint::from(10u64).pow(18), &eth_token(), &steth_token())
1125            .is_err());
1126        // ... but the price still resolves, for both submit paths.
1127        assert!(state
1128            .spot_price(&eth_token(), &steth_token())
1129            .is_ok());
1130        assert!(state
1131            .spot_price(&eth_token(), &wsteth_token())
1132            .is_ok());
1133    }
1134
1135    #[test]
1136    fn spot_price_rejects_a_token_the_venue_does_not_hold() {
1137        let weth = Token::new(&Bytes::from([0xc0u8; 20]), "WETH", 18, 0, &[], Chain::Ethereum, 100);
1138
1139        assert!(sample_state()
1140            .spot_price(&weth, &steth_token())
1141            .is_err());
1142    }
1143
1144    #[test]
1145    fn get_limits_unwrap_is_bounded_by_wrapper_shares() {
1146        let state = sample_state();
1147
1148        let (max_in, max_out) = state
1149            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
1150            .unwrap();
1151
1152        // Unwrapping pays out of the wrapper's stETH, so the limit is its share balance.
1153        assert_eq!(max_in, u256_to_biguint(sample_wsteth_shares()));
1154        assert_eq!(
1155            max_out,
1156            u256_to_biguint(
1157                state
1158                    .pooled_eth_by_shares(
1159                        state
1160                            .shares_for_pooled_eth(
1161                                state
1162                                    .pooled_eth_by_shares(sample_wsteth_shares())
1163                                    .unwrap()
1164                            )
1165                            .unwrap()
1166                    )
1167                    .unwrap()
1168            )
1169        );
1170        assert!(max_in < u256_to_biguint(U256::from(UINT128_MAX_EXCLUSIVE) - U256::ONE));
1171    }
1172
1173    #[test]
1174    fn get_limits_wrap_is_bounded_by_steth_supply() {
1175        let state = sample_state();
1176
1177        let (max_in, max_out) = state
1178            .get_limits(Bytes::from(STETH_ADDRESS), Bytes::from(WSTETH_ADDRESS))
1179            .unwrap();
1180
1181        // No more stETH can be wrapped than exists, and what exists is `totalSupply()`: the
1182        // internal ether plus the ether backing the externally minted shares.
1183        let supply = U256::from_str_radix("21803278404946205780741210", 10).expect("supply");
1184        assert_eq!(max_in, u256_to_biguint(supply));
1185        assert!(max_in > u256_to_biguint(state.internal_ether()), "external ether is missing");
1186        // Wrapping the whole supply mints every share but the one the round trip rounds away.
1187        assert_eq!(max_out, u256_to_biguint(state.total_shares - U256::ONE));
1188        assert!(max_in < u256_to_biguint(U256::from(UINT128_MAX_EXCLUSIVE) - U256::ONE));
1189    }
1190
1191    #[test]
1192    fn get_limits_unwrap_with_empty_wrapper_returns_zero() {
1193        let mut state = sample_state();
1194        state.wsteth_shares = U256::ZERO;
1195
1196        let (max_in, max_out) = state
1197            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
1198            .unwrap();
1199
1200        assert_eq!(max_in, BigUint::ZERO);
1201        assert_eq!(max_out, BigUint::ZERO);
1202    }
1203
1204    #[test]
1205    fn decoder_reads_wsteth_shares() {
1206        let state = sample_state();
1207        assert_eq!(state.wsteth_shares, sample_wsteth_shares());
1208    }
1209
1210    #[test]
1211    fn get_limits_unsupported_direction_returns_zero() {
1212        let state = sample_state();
1213
1214        let (max_in, max_out) = state
1215            .get_limits(Bytes::from(STETH_ADDRESS), Bytes::from(ETH_ADDRESS))
1216            .expect("limits");
1217
1218        assert_eq!(max_in, BigUint::ZERO);
1219        assert_eq!(max_out, BigUint::ZERO);
1220    }
1221
1222    #[test]
1223    fn get_limits_respects_current_stake_limit() {
1224        let state = sample_state();
1225        let (max_in, max_out) = state
1226            .get_limits(Bytes::from(ETH_ADDRESS), Bytes::from(STETH_ADDRESS))
1227            .unwrap();
1228
1229        assert_eq!(
1230            max_in,
1231            u256_to_biguint(
1232                state
1233                    .staking_state
1234                    .current_limit(state.execution_block_number)
1235            )
1236        );
1237        assert!(max_out > BigUint::ZERO);
1238    }
1239
1240    #[test]
1241    fn paused_staking_blocks_eth_to_steth() {
1242        let mut state = sample_state();
1243        let mut staking_state = state.staking_state;
1244        staking_state.prev_stake_block_number = 0;
1245        state.staking_state = staking_state;
1246
1247        let err = state
1248            .get_amount_out(BigUint::from(10u64).pow(18), &eth_token(), &steth_token())
1249            .unwrap_err();
1250
1251        assert!(
1252            matches!(err, SimulationError::RecoverableError(ref msg) if msg == "STAKING_PAUSED")
1253        );
1254    }
1255
1256    #[test]
1257    fn delta_transition_updates_state() {
1258        let mut state = sample_state();
1259        let new_total = U256::from(999u64);
1260        let new_external = U256::from(111u64);
1261        let new_buffered = U256::from(222u64);
1262        let new_deposited_post_report = U256::from(333u64);
1263        let new_cl_validators_balance = U256::from(444u64);
1264        let new_cl_pending_balance = U256::from(555u64);
1265        let new_staking_state = StakingState {
1266            prev_stake_block_number: 77,
1267            prev_stake_limit: U256::from(888u64),
1268            max_stake_limit_growth_blocks: 9,
1269            max_stake_limit: U256::from(999u64),
1270        };
1271
1272        state
1273            .delta_transition(
1274                ProtocolStateDelta {
1275                    component_id: STETH_COMPONENT_ID.to_string(),
1276                    updated_attributes: HashMap::from([
1277                        (TOTAL_SHARES_ATTR.to_string(), attribute(new_total)),
1278                        (EXTERNAL_SHARES_ATTR.to_string(), attribute(new_external)),
1279                        (BUFFERED_ETHER_ATTR.to_string(), attribute(new_buffered)),
1280                        (
1281                            DEPOSITED_POST_REPORT_ATTR.to_string(),
1282                            attribute(new_deposited_post_report),
1283                        ),
1284                        (
1285                            CL_VALIDATORS_BALANCE_ATTR.to_string(),
1286                            attribute(new_cl_validators_balance),
1287                        ),
1288                        (CL_PENDING_BALANCE_ATTR.to_string(), attribute(new_cl_pending_balance)),
1289                        (
1290                            PREV_STAKE_BLOCK_NUMBER_ATTR.to_string(),
1291                            attribute(U256::from(new_staking_state.prev_stake_block_number)),
1292                        ),
1293                        (
1294                            PREV_STAKE_LIMIT_ATTR.to_string(),
1295                            attribute(new_staking_state.prev_stake_limit),
1296                        ),
1297                        (
1298                            MAX_STAKE_LIMIT_GROWTH_BLOCKS_ATTR.to_string(),
1299                            attribute(U256::from(new_staking_state.max_stake_limit_growth_blocks)),
1300                        ),
1301                        (
1302                            MAX_STAKE_LIMIT_ATTR.to_string(),
1303                            attribute(new_staking_state.max_stake_limit),
1304                        ),
1305                    ]),
1306                    deleted_attributes: Default::default(),
1307                },
1308                &HashMap::new(),
1309                &Balances::default(),
1310            )
1311            .unwrap();
1312
1313        assert_eq!(state.total_shares, new_total);
1314        assert_eq!(state.external_shares, new_external);
1315        assert_eq!(state.buffered_ether, new_buffered);
1316        assert_eq!(state.deposited_post_report, new_deposited_post_report);
1317        assert_eq!(state.cl_validators_balance, new_cl_validators_balance);
1318        assert_eq!(state.cl_pending_balance, new_cl_pending_balance);
1319        assert_eq!(state.staking_state, new_staking_state);
1320    }
1321
1322    /// `prev_stake_block_number` is a 32-bit field. A five-byte value cannot come from the
1323    /// package, and narrowing it would wrap the block the stake limit accrues from.
1324    #[test]
1325    fn delta_transition_rejects_a_block_number_wider_than_its_field() {
1326        let mut state = sample_state();
1327        let before = state.clone();
1328
1329        let err = state
1330            .delta_transition(
1331                ProtocolStateDelta {
1332                    component_id: STETH_COMPONENT_ID.to_string(),
1333                    updated_attributes: HashMap::from([
1334                        (TOTAL_SHARES_ATTR.to_string(), attribute(U256::from(1u64))),
1335                        (
1336                            PREV_STAKE_BLOCK_NUMBER_ATTR.to_string(),
1337                            attribute(U256::from(1u64) << 32),
1338                        ),
1339                    ]),
1340                    deleted_attributes: Default::default(),
1341                },
1342                &HashMap::new(),
1343                &Balances::default(),
1344            )
1345            .unwrap_err();
1346
1347        let TransitionError::DecodeError(message) = err else {
1348            panic!("expected a decode error, got {err:?}");
1349        };
1350        assert!(message.contains(PREV_STAKE_BLOCK_NUMBER_ATTR), "{message}");
1351        assert_eq!(state, before, "a rejected delta must leave the state untouched");
1352    }
1353
1354    #[test]
1355    fn unwrap_quote_is_bounded_by_wrapper_shares() {
1356        let state = sample_state();
1357        let (max_in, _) = state
1358            .get_limits(Bytes::from(WSTETH_ADDRESS), Bytes::from(STETH_ADDRESS))
1359            .expect("limits");
1360
1361        // At the limit it quotes ...
1362        assert!(state
1363            .get_amount_out(max_in.clone(), &wsteth_token(), &steth_token())
1364            .is_ok());
1365        // ... and one wei past it, it refuses. `get_limits` and `get_amount_out` have to agree
1366        // on the same bound.
1367        let err = state
1368            .get_amount_out(max_in + BigUint::from(1u64), &wsteth_token(), &steth_token())
1369            .unwrap_err();
1370        assert!(matches!(err, SimulationError::RecoverableError(ref m) if m == "UNWRAP_LIMIT"));
1371    }
1372
1373    #[test]
1374    fn eth_to_wsteth_mints_the_submitted_shares() {
1375        let state = sample_state();
1376        let amount_in = BigUint::from(10u64).pow(18);
1377
1378        let result = state
1379            .get_amount_out(amount_in.clone(), &eth_token(), &wsteth_token())
1380            .expect("quote");
1381
1382        // `receive()` mints exactly the shares `submit` returned.
1383        let expected = state
1384            .shares_for_pooled_eth(biguint_to_uint(&amount_in).unwrap())
1385            .unwrap();
1386        assert_eq!(result.amount, u256_to_biguint(expected));
1387
1388        let new_state = result
1389            .new_state
1390            .as_any()
1391            .downcast_ref::<LidoV4State>()
1392            .unwrap();
1393        // The submitted ETH is buffered, the shares are minted, and they land on the wrapper.
1394        assert_eq!(
1395            new_state.buffered_ether,
1396            state.buffered_ether + biguint_to_uint(&amount_in).unwrap()
1397        );
1398        assert_eq!(new_state.total_shares, state.total_shares + expected);
1399        assert_eq!(new_state.wsteth_shares, state.wsteth_shares + expected);
1400    }
1401
1402    #[test]
1403    fn eth_to_wsteth_is_bounded_by_the_stake_limit() {
1404        let state = sample_state();
1405
1406        let (max_in, max_out) = state
1407            .get_limits(Bytes::from(ETH_ADDRESS), Bytes::from(WSTETH_ADDRESS))
1408            .expect("limits");
1409
1410        assert_eq!(
1411            max_in,
1412            u256_to_biguint(
1413                state
1414                    .staking_state
1415                    .current_limit(state.execution_block_number)
1416            )
1417        );
1418        assert!(max_out > BigUint::ZERO);
1419    }
1420
1421    #[test]
1422    fn eth_to_wsteth_beats_routing_through_steth() {
1423        let state = sample_state();
1424        let amount_in = BigUint::from(10u64).pow(18);
1425
1426        let direct = state
1427            .get_amount_out(amount_in.clone(), &eth_token(), &wsteth_token())
1428            .expect("direct");
1429        // The two-hop route: submit on the stETH component, then wrap on this one.
1430        let submitted = sample_state()
1431            .get_amount_out(amount_in, &eth_token(), &steth_token())
1432            .expect("submit");
1433        let wrapped = state
1434            .get_amount_out(submitted.amount, &steth_token(), &wsteth_token())
1435            .expect("wrap");
1436
1437        assert!(direct.amount >= wrapped.amount, "shortcut must not quote worse");
1438        assert!(direct.gas < submitted.gas + wrapped.gas, "shortcut must be cheaper");
1439    }
1440
1441    /// One component carries three tokens, so a caller can ask for any of six orderings. Only
1442    /// the four the venue performs may quote; the two that would unstake have to report a zero
1443    /// limit and refuse to price or swap, in every method, or a router builds a leg that cannot
1444    /// settle.
1445    #[test]
1446    fn component_serves_only_the_four_directions_the_venue_performs() {
1447        let state = sample_state();
1448        let amount = BigUint::from(10u64).pow(18);
1449
1450        let tradable = [
1451            (eth_token(), steth_token()),
1452            (steth_token(), wsteth_token()),
1453            (wsteth_token(), steth_token()),
1454            (eth_token(), wsteth_token()),
1455        ];
1456        // Unstaking runs through the asynchronous withdrawal queue.
1457        let untradable = [(steth_token(), eth_token()), (wsteth_token(), eth_token())];
1458
1459        for (token_in, token_out) in &tradable {
1460            let pair = format!("{} -> {}", token_in.symbol, token_out.symbol);
1461            let (max_in, max_out) = state
1462                .get_limits(token_in.address.clone(), token_out.address.clone())
1463                .unwrap_or_else(|e| panic!("{pair} limits: {e:?}"));
1464            assert!(max_in > BigUint::ZERO, "{pair} has no input capacity");
1465            assert!(max_out > BigUint::ZERO, "{pair} has no output capacity");
1466            assert!(
1467                state
1468                    .spot_price(token_in, token_out)
1469                    .is_ok(),
1470                "{pair} has no price"
1471            );
1472            assert!(
1473                state
1474                    .get_amount_out(amount.clone(), token_in, token_out)
1475                    .is_ok(),
1476                "{pair} does not quote"
1477            );
1478        }
1479
1480        // A token the component does not hold is a different answer from "no capacity".
1481        let weth = Token::new(&Bytes::from([0xc0u8; 20]), "WETH", 18, 0, &[], Chain::Ethereum, 100);
1482        assert!(
1483            state
1484                .get_limits(weth.address.clone(), steth_token().address)
1485                .is_err(),
1486            "an unknown token reported a limit instead of an error"
1487        );
1488        assert!(state
1489            .spot_price(&weth, &steth_token())
1490            .is_err());
1491        assert!(state
1492            .get_amount_out(amount.clone(), &weth, &steth_token())
1493            .is_err());
1494
1495        for (token_in, token_out) in &untradable {
1496            let pair = format!("{} -> {}", token_in.symbol, token_out.symbol);
1497            assert_eq!(
1498                state
1499                    .get_limits(token_in.address.clone(), token_out.address.clone())
1500                    .unwrap_or_else(|e| panic!("{pair} limits: {e:?}")),
1501                (BigUint::ZERO, BigUint::ZERO),
1502                "{pair} reports capacity it cannot settle"
1503            );
1504            assert!(
1505                state
1506                    .spot_price(token_in, token_out)
1507                    .is_err(),
1508                "{pair} has a price"
1509            );
1510            assert!(
1511                state
1512                    .get_amount_out(amount.clone(), token_in, token_out)
1513                    .is_err(),
1514                "{pair} quotes a swap the venue cannot perform"
1515            );
1516        }
1517    }
1518
1519    /// State read from stETH storage at the Lido v4 migration block 25603297. Pricing
1520    /// `sharesOf(wstETH)` at the share rate has to land on `stETH.balanceOf(wstETH)` from the
1521    /// same block, which pins the v4 pooled-ether formula to the chain.
1522    #[test]
1523    fn share_rate_matches_chain_on_the_v4_storage_layout() {
1524        let state = LidoV4State::new(
1525            25_603_297,
1526            U256::from_str_radix("7526667021904051320418763", 10).unwrap(),
1527            U256::from_str_radix("3721126242498807385407", 10).unwrap(),
1528            U256::from_str_radix("539569870340371095571", 10).unwrap(),
1529            U256::from_str_radix("761440000000000000000000", 10).unwrap(),
1530            U256::from_str_radix("8567227049119653000000000", 10).unwrap(),
1531            U256::ZERO,
1532            sample_staking_state(),
1533            U256::from_str_radix("3628434125893615122886002", 10).unwrap(),
1534        );
1535
1536        let wsteth_backing = state
1537            .pooled_eth_by_shares(state.wsteth_shares)
1538            .unwrap();
1539
1540        assert_eq!(wsteth_backing, U256::from_str_radix("4499621841408863271318368", 10).unwrap());
1541    }
1542
1543    #[test]
1544    fn unsupported_direction_errors() {
1545        let err = sample_state()
1546            .get_amount_out(BigUint::from(10u64).pow(18), &steth_token(), &eth_token())
1547            .unwrap_err();
1548        assert!(matches!(err, SimulationError::FatalError(_)));
1549    }
1550
1551    #[tokio::test]
1552    async fn decoder_seeds_the_execution_block_from_the_header() {
1553        let snapshot = snapshot();
1554        let state = LidoV4State::try_from_with_header(
1555            snapshot,
1556            BlockHeader {
1557                number: 123,
1558                timestamp: 456,
1559                hash: Bytes::new(),
1560                parent_hash: Bytes::new(),
1561                revert: false,
1562                partial_block_index: None,
1563            },
1564            &HashMap::new(),
1565            &HashMap::new(),
1566            &Default::default(),
1567        )
1568        .await
1569        .unwrap();
1570
1571        assert_eq!(state.execution_block_number, 123);
1572    }
1573
1574    /// The stake limit accrues per block, so an idle block still has to move it - that is the
1575    /// whole reason the block cannot come in on a delta.
1576    #[test]
1577    fn apply_block_accrues_the_stake_limit_without_a_delta() {
1578        let mut state = sample_state();
1579        // The fixture starts at `max_stake_limit`, where nothing can accrue. A partly consumed
1580        // limit is the case this guards.
1581        state.staking_state.prev_stake_limit = state.staking_state.max_stake_limit / U256::from(2);
1582        let limit_before = state
1583            .staking_state
1584            .current_limit(state.execution_block_number);
1585
1586        let changed = state.apply_block(&BlockContext::new(state.execution_block_number + 1, 0));
1587
1588        assert!(changed, "an accruing limit must re-emit");
1589        assert!(
1590            state
1591                .staking_state
1592                .current_limit(state.execution_block_number) >
1593                limit_before
1594        );
1595    }
1596
1597    #[test]
1598    fn apply_block_is_idempotent_for_a_repeated_block() {
1599        let mut state = sample_state();
1600        let block = BlockContext::new(state.execution_block_number, 0);
1601
1602        assert!(!state.apply_block(&block));
1603        assert!(!state.apply_block(&block));
1604    }
1605
1606    /// Once the limit sits at `max_stake_limit` it cannot grow further, so later blocks must not
1607    /// keep re-emitting the state to consumers.
1608    #[test]
1609    fn apply_block_does_not_re_emit_once_the_limit_is_saturated() {
1610        let mut state = sample_state();
1611        state.staking_state.prev_stake_limit = state.staking_state.max_stake_limit / U256::from(2);
1612        state.apply_block(&BlockContext::new(state.execution_block_number + 10_000_000, 0));
1613        let saturated = state
1614            .staking_state
1615            .current_limit(state.execution_block_number);
1616        assert_eq!(saturated, state.staking_state.max_stake_limit);
1617
1618        let changed = state.apply_block(&BlockContext::new(state.execution_block_number + 1, 0));
1619
1620        assert!(!changed);
1621    }
1622
1623    fn every_token_pair() -> Vec<(Bytes, Bytes)> {
1624        let tokens = [ETH_ADDRESS, STETH_ADDRESS, WSTETH_ADDRESS];
1625        let mut pairs = Vec::new();
1626        for sell in tokens {
1627            for buy in tokens {
1628                if sell != buy {
1629                    pairs.push((Bytes::from(sell), Bytes::from(buy)));
1630                }
1631            }
1632        }
1633        pairs
1634    }
1635
1636    /// A reported limit has to be a trade the venue performs: quoting at it must succeed and
1637    /// return exactly the reported output.
1638    #[test]
1639    fn every_reported_limit_quotes_at_its_own_size() {
1640        let state = sample_state();
1641        for (sell, buy) in every_token_pair() {
1642            let (max_in, max_out) = state
1643                .get_limits(sell.clone(), buy.clone())
1644                .expect("a pair the component holds");
1645            if max_in == BigUint::ZERO {
1646                assert_eq!(max_out, BigUint::ZERO, "{sell:x} -> {buy:x} pays out of a zero limit");
1647                continue;
1648            }
1649            let token_in = Token::new(&sell, "in", 18, 0, &[], Chain::Ethereum, 100);
1650            let token_out = Token::new(&buy, "out", 18, 0, &[], Chain::Ethereum, 100);
1651            let quoted = state
1652                .get_amount_out(max_in, &token_in, &token_out)
1653                .unwrap_or_else(|e| panic!("{sell:x} -> {buy:x} limit does not quote: {e:?}"));
1654            assert_eq!(quoted.amount, max_out, "{sell:x} -> {buy:x} limit disagrees with quote");
1655        }
1656    }
1657
1658    /// The share rate is applied in one direction or the other, and the two are inverse up to
1659    /// their rounding, so neither can be applied to a figure already in the other unit.
1660    #[test]
1661    fn shares_and_pooled_ether_round_trip() {
1662        let state = sample_state();
1663        // Each division truncates by under one unit, and the first loss is then scaled
1664        // by the share rate, so a round trip can lose the rate plus one.
1665        let tolerance = state
1666            .pooled_eth_by_shares(U256::ONE)
1667            .expect("rate") +
1668            U256::from(2u8);
1669        for exponent in [15u32, 18, 21, 24] {
1670            let amount = U256::from(10u64).pow(U256::from(exponent));
1671            let back = state
1672                .pooled_eth_by_shares(
1673                    state
1674                        .shares_for_pooled_eth(amount)
1675                        .expect("shares"),
1676                )
1677                .expect("amount");
1678            assert!(back <= amount && amount - back <= tolerance, "amount drifted at 1e{exponent}");
1679
1680            let shares = U256::from(10u64).pow(U256::from(exponent));
1681            let back = state
1682                .shares_for_pooled_eth(
1683                    state
1684                        .pooled_eth_by_shares(shares)
1685                        .expect("amount"),
1686                )
1687                .expect("shares");
1688            assert!(back <= shares && shares - back <= tolerance, "shares drifted at 1e{exponent}");
1689        }
1690    }
1691
1692    /// The decoder requires every name the component carries, so a value the package emits
1693    /// cannot be left unread.
1694    #[tokio::test]
1695    async fn decoder_requires_every_attribute_the_component_carries() {
1696        assert_eq!(snapshot().state.attributes.len(), COMPONENT_ATTRS.len());
1697        for name in COMPONENT_ATTRS {
1698            let mut snapshot = snapshot();
1699            snapshot.state.attributes.remove(name);
1700            let err = try_decode_snapshot_with_defaults::<LidoV4State>(snapshot)
1701                .await
1702                .unwrap_err();
1703            let InvalidSnapshotError::MissingAttribute(missing) = err else {
1704                panic!("{name} removed but the decoder did not report it: {err:?}");
1705            };
1706            assert_eq!(missing, name);
1707        }
1708    }
1709
1710    /// A delta and a fresh snapshot of the same attributes produce identical state.
1711    #[tokio::test]
1712    async fn delta_transition_applies_every_attribute_the_component_carries() {
1713        let base = try_decode_snapshot_with_defaults::<LidoV4State>(snapshot())
1714            .await
1715            .unwrap();
1716        for name in COMPONENT_ATTRS {
1717            let mut state = base.clone();
1718            state
1719                .delta_transition(
1720                    ProtocolStateDelta {
1721                        component_id: STETH_COMPONENT_ID.to_string(),
1722                        updated_attributes: HashMap::from([(
1723                            name.to_string(),
1724                            attribute(U256::from(7u64)),
1725                        )]),
1726                        deleted_attributes: Default::default(),
1727                    },
1728                    &HashMap::new(),
1729                    &Balances::default(),
1730                )
1731                .unwrap_or_else(|e| panic!("{name} was rejected: {e:?}"));
1732            let mut updated = snapshot();
1733            updated
1734                .state
1735                .attributes
1736                .insert(name.to_string(), attribute(U256::from(7u64)));
1737            let expected = try_decode_snapshot_with_defaults::<LidoV4State>(updated)
1738                .await
1739                .unwrap();
1740            assert_eq!(state, expected, "{name} updated the wrong state");
1741        }
1742    }
1743
1744    #[test]
1745    fn delta_transition_ignores_unknown_attributes() {
1746        let mut state = sample_state();
1747        let expected = state.clone();
1748        state
1749            .delta_transition(
1750                ProtocolStateDelta {
1751                    component_id: STETH_COMPONENT_ID.to_string(),
1752                    updated_attributes: HashMap::from([(
1753                        "future_parameter".to_string(),
1754                        Bytes::from(vec![0xff; 64]),
1755                    )]),
1756                    deleted_attributes: Default::default(),
1757                },
1758                &HashMap::new(),
1759                &Balances::default(),
1760            )
1761            .unwrap();
1762        assert_eq!(state, expected);
1763    }
1764
1765    /// The stream decoder puts the chain head in every delta. Those names are not Lido
1766    /// attributes and leave the state alone.
1767    #[test]
1768    fn delta_transition_accepts_the_injected_block_attributes() {
1769        let mut state = sample_state();
1770        state
1771            .delta_transition(
1772                ProtocolStateDelta {
1773                    component_id: STETH_COMPONENT_ID.to_string(),
1774                    updated_attributes: HashMap::from([
1775                        (
1776                            "block_number".to_string(),
1777                            Bytes::from(24_083_114u64.to_be_bytes().to_vec()),
1778                        ),
1779                        (
1780                            "block_timestamp".to_string(),
1781                            Bytes::from(1_700_000_000u64.to_be_bytes().to_vec()),
1782                        ),
1783                    ]),
1784                    deleted_attributes: Default::default(),
1785                },
1786                &HashMap::new(),
1787                &Balances::default(),
1788            )
1789            .expect("the injected names are tolerated");
1790        assert_eq!(state, sample_state());
1791    }
1792}