Skip to main content

tycho_simulation/evm/protocol/uniswap_v4/
decoder.rs

1use std::collections::HashMap;
2
3use alloy::primitives::{Address, U256};
4use itertools::Itertools;
5use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
6use tycho_common::{models::token::Token, simulation::protocol_sim::ProtocolSim, Bytes};
7
8use super::state::UniswapV4State;
9use crate::{
10    evm::protocol::{
11        uniswap_v4::{
12            hooks::{
13                hook_handler_creator::{
14                    has_native_hook_handler, instantiate_hook_handler, HookCreationParams,
15                },
16                utils::{has_permission, HookOptions},
17            },
18            state::UniswapV4Fees,
19        },
20        utils::{
21            bytes_to_address,
22            uniswap::{i24_be_bytes_to_i32, tick_list::TickInfo},
23        },
24    },
25    protocol::{
26        errors::InvalidSnapshotError,
27        models::{DecoderContext, TryFromWithBlock},
28    },
29};
30
31/// The protocol system whose pool manager reads hook permissions from the pool key rather than
32/// the hook address, and which only emits pools whose hook takes part in swaps.
33const POOL_KEY_PERMISSION_SYSTEM: &str = "pancakeswap_infinity_cl_hooks";
34
35/// Whether a hook can take part in a swap at all, which it can exactly when its address carries
36/// the `beforeSwap` or the `afterSwap` permission bit. Uniswap V4 encodes a hook's permissions in
37/// the low bits of its address and the pool manager calls only the callbacks those bits allow, so
38/// a hook without either bit cannot change what a swap does. The zero address carries no bits and
39/// so falls out of this check as well.
40fn hook_participates_in_swaps(address: Address) -> bool {
41    has_permission(address, HookOptions::BeforeSwap) ||
42        has_permission(address, HookOptions::AfterSwap)
43}
44
45impl TryFromWithBlock<ComponentWithState, BlockHeader> for UniswapV4State {
46    type Error = InvalidSnapshotError;
47
48    /// Decodes a `ComponentWithState` into a `UniswapV4State`. Errors with a `InvalidSnapshotError`
49    /// if the snapshot is missing any required attributes.
50    async fn try_from_with_header(
51        snapshot: ComponentWithState,
52        block: BlockHeader,
53        account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
54        all_tokens: &HashMap<Bytes, Token>,
55        decoder_context: &DecoderContext,
56    ) -> Result<Self, Self::Error> {
57        let liq = snapshot
58            .state
59            .attributes
60            .get("liquidity")
61            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("liquidity".to_string()))?
62            .clone();
63
64        let liquidity = u128::from(liq);
65
66        let sqrt_price = U256::from_be_slice(
67            snapshot
68                .state
69                .attributes
70                .get("sqrt_price_x96")
71                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("sqrt_price".to_string()))?,
72        );
73
74        let lp_fee = u32::from(
75            snapshot
76                .component
77                .static_attributes
78                .get("key_lp_fee")
79                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("key_lp_fee".to_string()))?
80                .clone(),
81        );
82
83        let zero2one_protocol_fee = u32::from(
84            snapshot
85                .state
86                .attributes
87                .get("protocol_fees/zero2one")
88                .ok_or_else(|| {
89                    InvalidSnapshotError::MissingAttribute("protocol_fees/zero2one".to_string())
90                })?
91                .clone(),
92        );
93        let one2zero_protocol_fee = u32::from(
94            snapshot
95                .state
96                .attributes
97                .get("protocol_fees/one2zero")
98                .ok_or_else(|| {
99                    InvalidSnapshotError::MissingAttribute("protocol_fees/one2zero".to_string())
100                })?
101                .clone(),
102        );
103
104        let fees: UniswapV4Fees =
105            UniswapV4Fees::new(zero2one_protocol_fee, one2zero_protocol_fee, lp_fee);
106
107        let tick_spacing: i32 = i32::from(
108            snapshot
109                .component
110                .static_attributes
111                .get("tick_spacing")
112                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("tick_spacing".to_string()))?
113                .clone(),
114        );
115
116        let tick = i24_be_bytes_to_i32(
117            snapshot
118                .state
119                .attributes
120                .get("tick")
121                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("tick".to_string()))?,
122        );
123
124        let ticks: Result<Vec<_>, _> = snapshot
125            .state
126            .attributes
127            .iter()
128            .filter_map(|(key, value)| {
129                if key.starts_with("ticks/") {
130                    Some(
131                        key.split('/')
132                            .nth(1)?
133                            .parse::<i32>()
134                            .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
135                            .and_then(|tick_index| {
136                                TickInfo::new(tick_index, i128::from(value.clone())).map_err(
137                                    |err| InvalidSnapshotError::ValueError(err.to_string()),
138                                )
139                            }),
140                    )
141                } else {
142                    None
143                }
144            })
145            .collect();
146
147        let hook_attribute = snapshot
148            .component
149            .static_attributes
150            .get("hooks");
151
152        let mut ticks = match ticks {
153            Ok(ticks) if !ticks.is_empty() => ticks
154                .into_iter()
155                .filter(|t| t.net_liquidity != 0)
156                .collect::<Vec<_>>(),
157            _ => {
158                // there might be pools where the liquidity is managed by the hook
159                //
160                // Keyed on the attribute being present rather than on the address being non-zero:
161                // a freshly initialised hookless pool has no ticks yet and must still decode.
162                if hook_attribute.is_some() {
163                    Vec::new()
164                } else {
165                    return Err(InvalidSnapshotError::MissingAttribute(
166                        "tick_liquidities".to_string(),
167                    ));
168                }
169            }
170        };
171
172        ticks.sort_by_key(|tick| tick.index);
173
174        let mut state = UniswapV4State::new(liquidity, sqrt_price, fees, tick, tick_spacing, ticks)
175            .map_err(|err| {
176                tracing::error!(
177                    pool_id = %snapshot.component.id,
178                    error = %err,
179                    "Failed to create UniswapV4State"
180                );
181                InvalidSnapshotError::ValueError(err.to_string())
182            })?;
183
184        // Every Uniswap V4 component carries a `hooks` attribute, so its presence says nothing
185        // about whether the pool has a hook: the zero address is what "no hook" looks like on the
186        // wire, and the length check rejects a malformed value. A pool whose hook cannot take part
187        // in a swap is a plain V4 pool too, on every chain: no handler, no chain needed. A hook
188        // with a native handler registered on this chain is always simulated by it, because some
189        // pool managers (PancakeSwap Infinity) do not encode permissions in the hook address. For
190        // the system that only emits such hooks the address bits are never consulted, so a missing
191        // chain or handler fails the decode instead of hinging on whatever bits the address has.
192        let permissions_in_pool_key =
193            snapshot.component.protocol_system == POOL_KEY_PERMISSION_SYSTEM;
194        let hook_address = hook_attribute
195            .map(bytes_to_address)
196            .transpose()
197            .map_err(|err| {
198                InvalidSnapshotError::ValueError(format!(
199                    "hooks attribute is not a 20-byte address: {err}"
200                ))
201            })?
202            .filter(|address| {
203                hook_participates_in_swaps(*address) ||
204                    (permissions_in_pool_key && !address.is_zero()) ||
205                    decoder_context
206                        .chain
207                        .is_some_and(|chain| has_native_hook_handler(chain, address))
208            });
209
210        if let Some(hook_address) = hook_address {
211            // Merge state attributes into static_attributes for hook creation
212            let mut merged_attributes = snapshot
213                .component
214                .static_attributes
215                .clone();
216            merged_attributes.extend(snapshot.state.attributes.clone());
217
218            let chain = decoder_context.chain.ok_or_else(|| {
219                InvalidSnapshotError::ValueError(
220                    "uniswap v4 hook pools require DecoderContext.chain; register the decoder \
221                     through TychoStreamDecoder or set DecoderContext::chain"
222                        .to_string(),
223                )
224            })?;
225
226            let hook_params = HookCreationParams::new(
227                hook_address,
228                account_balances,
229                all_tokens,
230                state.clone(),
231                &merged_attributes,
232                &snapshot.state.balances,
233                decoder_context.vm_traces,
234            )
235            .with_block_timestamp(block.timestamp);
236
237            let hook_handler = instantiate_hook_handler(chain, &hook_address, hook_params)?;
238            state.set_hook_handler(hook_handler);
239        };
240
241        for tokens in snapshot
242            .component
243            .tokens
244            .iter()
245            .permutations(2)
246        {
247            let (t0, t1) = (tokens[0], tokens[1]);
248            let token_in = all_tokens.get(t0).ok_or_else(|| {
249                InvalidSnapshotError::ValueError("Failed to get token".to_string())
250            })?;
251            let token_out = all_tokens.get(t1).ok_or_else(|| {
252                InvalidSnapshotError::ValueError("Failed to get token".to_string())
253            })?;
254            state.spot_price(token_in, token_out)?;
255        }
256
257        Ok(state)
258    }
259}
260
261/// The recorded Robinhood Pons V2 pool `0xc96847cc…` (XLG/NVDA), shared with the stream-decoder
262/// tests in [`crate::evm::decoder`].
263///
264/// Every value comes from the chain: `tests/assets/decoder/uniswap_v4_pons_snapshot_robinhood.json`
265/// is the pool at the end of the block that created it, and the sibling `_sources.json` names the
266/// log or storage read each of its fields was taken from.
267#[cfg(test)]
268pub(crate) mod pons_fixture {
269    use std::{collections::HashMap, fs, path::Path, str::FromStr};
270
271    use num_bigint::BigUint;
272    use tycho_client::feed::{dto, synchronizer::ComponentWithState, BlockHeader};
273    use tycho_common::{
274        models::{token::Token, Chain},
275        Bytes,
276    };
277
278    use super::UniswapV4State;
279    use crate::protocol::{
280        errors::InvalidSnapshotError,
281        models::{DecoderContext, TryFromWithBlock},
282    };
283
284    pub(crate) const POOL_ID: &str =
285        "0xc96847cc43f7595aafcbc1c99d335cb91be7ce1107524c87030f48a716a5f289";
286    const XLG_ADDRESS: &str = "0xab5983fe30f186055095305c862b0e097dab3b52";
287    const NVDA_ADDRESS: &str = "0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec";
288
289    /// The terms `registerPool` froze for this pool, read out of `launches[poolId]`.
290    pub(crate) const HOOK_FEE_BPS: u32 = 100;
291    pub(crate) const CREATOR_TAX_BPS: u32 = 100;
292
293    /// The block the pool was created in, and its timestamp.
294    const BLOCK_NUMBER: u64 = 58_759_099;
295    const BLOCK_TIMESTAMP: u64 = 1_788_978_331;
296
297    pub(crate) fn snapshot() -> ComponentWithState {
298        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
299            .join("tests/assets/decoder/uniswap_v4_pons_snapshot_robinhood.json");
300        let raw =
301            fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
302        serde_json::from_str::<dto::ComponentWithState>(&raw)
303            .expect("the Pons snapshot fixture should match ComponentWithState")
304            .into()
305    }
306
307    /// The same pool with everything the hook contributes stripped off the wire, which is what a
308    /// pool of this shape looks like with no hook at all. Its quotes are the core swap math the
309    /// hook's cut is measured against.
310    pub(crate) fn hookless_snapshot() -> ComponentWithState {
311        let mut snapshot = snapshot();
312        snapshot.component.protocol_system = "uniswap_v4".to_string();
313        for attribute in ["hooks", "hook_identifier", "pons_hook_fee_bps", "pons_creator_tax_bps"] {
314            snapshot
315                .component
316                .static_attributes
317                .remove(attribute);
318        }
319        snapshot
320    }
321
322    /// The same pool behind an address no native handler is registered for on any chain.
323    pub(crate) fn unknown_hook_snapshot() -> ComponentWithState {
324        let mut snapshot = snapshot();
325        snapshot
326            .component
327            .static_attributes
328            .insert(
329                "hooks".to_string(),
330                Bytes::from_str("0x14bcc18fdb0e7a427122b9c2f1a40ff7d63eaacc")
331                    .expect("the literal address parses"),
332            );
333        snapshot
334    }
335
336    fn token(address: &str, symbol: &str) -> Token {
337        Token::new(
338            &Bytes::from_str(address).expect("the fixture token addresses parse"),
339            symbol,
340            18,
341            0,
342            &[Some(10_000)],
343            Chain::Robinhood,
344            100,
345        )
346    }
347
348    /// `currency0` of the pool: the lower of the two addresses, so a swap out of it is
349    /// zero-for-one.
350    pub(crate) fn xlg() -> Token {
351        token(XLG_ADDRESS, "XLG")
352    }
353
354    pub(crate) fn nvda() -> Token {
355        token(NVDA_ADDRESS, "NVDA")
356    }
357
358    pub(crate) fn tokens() -> HashMap<Bytes, Token> {
359        [xlg(), nvda()]
360            .into_iter()
361            .map(|token| (token.address.clone(), token))
362            .collect()
363    }
364
365    pub(crate) fn header() -> BlockHeader {
366        BlockHeader {
367            number: BLOCK_NUMBER,
368            hash: Bytes::from([1u8; 32]),
369            parent_hash: Bytes::from([0u8; 32]),
370            revert: false,
371            timestamp: BLOCK_TIMESTAMP,
372            partial_block_index: None,
373        }
374    }
375
376    /// Decodes `snapshot` as a component of `chain`, the way a decoder registered for that chain
377    /// would.
378    pub(crate) async fn decode_on(
379        snapshot: ComponentWithState,
380        chain: Chain,
381    ) -> Result<UniswapV4State, InvalidSnapshotError> {
382        UniswapV4State::try_from_with_header(
383            snapshot,
384            header(),
385            &HashMap::default(),
386            &tokens(),
387            &DecoderContext::new().chain(chain),
388        )
389        .await
390    }
391
392    /// What the PoolManager holds of `token` for this pool, straight from the snapshot.
393    ///
394    /// Trade sizes are taken as fractions of this rather than of `get_limits`. A full-range
395    /// position can absorb an unbounded amount of one side while giving up a bounded amount of
396    /// the other, so even a millionth of the limit on the `currency0` side drains the pool.
397    pub(crate) fn reserve(token: &Token) -> BigUint {
398        let snapshot = snapshot();
399        let balance = snapshot
400            .state
401            .balances
402            .get(&token.address)
403            .unwrap_or_else(|| panic!("the fixture carries a balance for {}", token.symbol));
404        BigUint::from_bytes_be(balance)
405    }
406
407    /// What is left of a `core` output once the hook has taken its fee and its tax, each floored
408    /// on its own exactly as `_afterSwap` computes them.
409    pub(crate) fn net_of_hook_take(core: &BigUint) -> BigUint {
410        let denominator = BigUint::from(10_000u32);
411        let fee = core * BigUint::from(HOOK_FEE_BPS) / &denominator;
412        let tax = core * BigUint::from(CREATOR_TAX_BPS) / &denominator;
413        core - fee - tax
414    }
415}
416
417#[cfg(test)]
418mod tests {
419    use std::{collections::HashSet, str::FromStr};
420
421    use chrono::DateTime;
422    use num_bigint::BigUint;
423    use num_traits::Zero;
424    use rstest::rstest;
425    use tycho_common::{
426        dto::ProtocolStateDelta,
427        models::{
428            protocol::{ProtocolComponent, ProtocolComponentState},
429            Chain, ChangeType,
430        },
431        simulation::{
432            errors::SimulationError,
433            protocol_sim::{
434                Balances, BlockContext, PoolSwap, Price, QueryPoolSwapParams, SwapConstraint,
435            },
436        },
437    };
438
439    use super::*;
440    use crate::evm::protocol::{
441        test_utils::try_decode_snapshot_with_defaults,
442        uniswap_v4::hooks::pancakeswap_clalpha::hook_handler::CLALPHA_BEFORE_SWAP_GAS,
443    };
444
445    fn usv4_component() -> ProtocolComponent {
446        let creation_time = DateTime::from_timestamp(1622526000, 0)
447            .unwrap()
448            .naive_utc();
449
450        let static_attributes: HashMap<String, Bytes> = HashMap::from([
451            ("key_lp_fee".to_string(), Bytes::from(500_i32.to_be_bytes().to_vec())),
452            ("tick_spacing".to_string(), Bytes::from(60_i32.to_be_bytes().to_vec())),
453        ]);
454
455        ProtocolComponent {
456            id: "State1".to_string(),
457            protocol_system: "system1".to_string(),
458            protocol_type_name: "typename1".to_string(),
459            chain: Chain::Ethereum,
460            tokens: Vec::new(),
461            contract_addresses: Vec::new(),
462            static_attributes,
463            change: ChangeType::Creation,
464            creation_tx: Bytes::from_str("0x0000").unwrap(),
465            created_at: creation_time,
466        }
467    }
468
469    fn usv4_attributes() -> HashMap<String, Bytes> {
470        HashMap::from([
471            ("liquidity".to_string(), Bytes::from(100_u64.to_be_bytes().to_vec())),
472            ("tick".to_string(), Bytes::from(300_i32.to_be_bytes().to_vec())),
473            (
474                "sqrt_price_x96".to_string(),
475                Bytes::from(
476                    79228162514264337593543950336_u128
477                        .to_be_bytes()
478                        .to_vec(),
479                ),
480            ),
481            ("protocol_fees/zero2one".to_string(), Bytes::from(0_u32.to_be_bytes().to_vec())),
482            ("protocol_fees/one2zero".to_string(), Bytes::from(0_u32.to_be_bytes().to_vec())),
483            ("ticks/60/net_liquidity".to_string(), Bytes::from(400_i128.to_be_bytes().to_vec())),
484        ])
485    }
486
487    #[tokio::test]
488    async fn test_usv4_try_from() {
489        let snapshot = ComponentWithState {
490            state: ProtocolComponentState {
491                component_id: "State1".to_owned(),
492                attributes: usv4_attributes(),
493                balances: HashMap::new(),
494            },
495            component: usv4_component(),
496            component_tvl: None,
497            entrypoints: Vec::new(),
498        };
499
500        let result = try_decode_snapshot_with_defaults::<UniswapV4State>(snapshot)
501            .await
502            .unwrap();
503
504        let fees = UniswapV4Fees::new(0, 0, 500);
505        let expected = UniswapV4State::new(
506            100,
507            U256::from(79228162514264337593543950336_u128),
508            fees,
509            300,
510            60,
511            vec![TickInfo::new(60, 400).unwrap()],
512        )
513        .unwrap();
514        assert_eq!(result, expected);
515    }
516
517    /// What a pool with no hook looks like on the wire: every Uniswap V4 component carries the
518    /// `hooks` attribute, zero-valued when there is no hook.
519    const ZERO_HOOK: &str = "0x0000000000000000000000000000000000000000";
520    /// A hook address with no native handler registered for it on any chain. Its low bits carry
521    /// `beforeSwap` (bit 7) and `afterSwap` (bit 6), so it does take part in swaps.
522    const UNKNOWN_HOOK: &str = "0x00000000000000000000000000000000000000c4";
523    /// A hook that only carries the add- and remove-liquidity permissions (bits 11 and 10) and
524    /// neither swap bit, so the pool manager never calls it during a swap.
525    const LIQUIDITY_ONLY_HOOK: &str = "0x0000000000000000000000000000000000000c00";
526
527    fn hookless_token(address: &str, symbol: &str, decimals: u32) -> Token {
528        Token::new(
529            &Bytes::from_str(address).unwrap(),
530            symbol,
531            decimals,
532            0,
533            &[Some(10_000)],
534            Chain::Ethereum,
535            100,
536        )
537    }
538
539    fn token0() -> Token {
540        hookless_token("0x0000000000000000000000000000000000000001", "T0", 18)
541    }
542
543    /// Deliberately a different decimal count from [`token0`], so the two quote orderings differ
544    /// and an ordering bug cannot hide behind a symmetric result.
545    fn token1() -> Token {
546        hookless_token("0x0000000000000000000000000000000000000002", "T1", 6)
547    }
548
549    /// A symmetric, liquid pool, so quoting succeeds in both directions.
550    fn hookless_pool_attributes() -> HashMap<String, Bytes> {
551        let liquidity = 1_000_000_000_000_000_000_i128;
552        HashMap::from([
553            (
554                "liquidity".to_string(),
555                Bytes::from(
556                    (liquidity as u128)
557                        .to_be_bytes()
558                        .to_vec(),
559                ),
560            ),
561            ("tick".to_string(), Bytes::from(0_i32.to_be_bytes().to_vec())),
562            (
563                "sqrt_price_x96".to_string(),
564                Bytes::from(
565                    79228162514264337593543950336_u128
566                        .to_be_bytes()
567                        .to_vec(),
568                ),
569            ),
570            ("protocol_fees/zero2one".to_string(), Bytes::from(0_u32.to_be_bytes().to_vec())),
571            ("protocol_fees/one2zero".to_string(), Bytes::from(0_u32.to_be_bytes().to_vec())),
572            ("ticks/-60/net_liquidity".to_string(), Bytes::from(liquidity.to_be_bytes().to_vec())),
573            (
574                "ticks/60/net_liquidity".to_string(),
575                Bytes::from((-liquidity).to_be_bytes().to_vec()),
576            ),
577        ])
578    }
579
580    /// The very same pool, built directly with no hook — the reference every hookless-decoding
581    /// assertion compares against.
582    fn reference_hookless_state() -> UniswapV4State {
583        let liquidity = 1_000_000_000_000_000_000_i128;
584        UniswapV4State::new(
585            liquidity as u128,
586            U256::from(79228162514264337593543950336_u128),
587            UniswapV4Fees::new(0, 0, 500),
588            0,
589            60,
590            vec![TickInfo::new(-60, liquidity).unwrap(), TickInfo::new(60, -liquidity).unwrap()],
591        )
592        .unwrap()
593    }
594
595    fn hookless_snapshot_with_hook(hook: &str) -> ComponentWithState {
596        let mut component = usv4_component();
597        component
598            .static_attributes
599            .insert("hooks".to_string(), Bytes::from_str(hook).unwrap());
600        component.tokens = vec![token0().address, token1().address];
601
602        ComponentWithState {
603            state: ProtocolComponentState {
604                component_id: "State1".to_owned(),
605                attributes: hookless_pool_attributes(),
606                balances: HashMap::new(),
607            },
608            component,
609            component_tvl: None,
610            entrypoints: Vec::new(),
611        }
612    }
613
614    /// The snapshot the original hook tests used: minimal attributes, no tokens.
615    fn usv4_snapshot_with_hook(hook: &str) -> ComponentWithState {
616        let mut component = usv4_component();
617        component
618            .static_attributes
619            .insert("hooks".to_string(), Bytes::from_str(hook).unwrap());
620
621        ComponentWithState {
622            state: ProtocolComponentState {
623                component_id: "State1".to_owned(),
624                attributes: usv4_attributes(),
625                balances: HashMap::new(),
626            },
627            component,
628            component_tvl: None,
629            entrypoints: Vec::new(),
630        }
631    }
632
633    async fn decode_with_chain(
634        snapshot: ComponentWithState,
635        chain: Option<Chain>,
636    ) -> Result<UniswapV4State, InvalidSnapshotError> {
637        let all_tokens =
638            HashMap::from([(token0().address, token0()), (token1().address, token1())]);
639        let context = match chain {
640            Some(chain) => DecoderContext::new().chain(chain),
641            None => DecoderContext::new(),
642        };
643        UniswapV4State::try_from_with_header(
644            snapshot,
645            Default::default(),
646            &HashMap::default(),
647            &all_tokens,
648            &context,
649        )
650        .await
651    }
652
653    /// A zero `hooks` address is not a hook. The pool decodes on every chain, with or without a
654    /// chain in the context, and behaves exactly like a `UniswapV4State` built with no hook:
655    /// analytic `spot_price`, tick-walk `get_limits`, unchanged `get_amount_out`. It must never
656    /// route through `GenericVMHookHandler`.
657    #[tokio::test]
658    #[rstest]
659    #[case::no_chain(None)]
660    #[case::robinhood(Some(Chain::Robinhood))]
661    #[case::base(Some(Chain::Base))]
662    #[case::ethereum(Some(Chain::Ethereum))]
663    async fn zero_hook_address_decodes_as_hookless(#[case] chain: Option<Chain>) {
664        let decoded = decode_with_chain(hookless_snapshot_with_hook(ZERO_HOOK), chain)
665            .await
666            .expect("a pool with a zero hook address must decode on every chain");
667
668        assert!(decoded.hook.is_none(), "a zero hook address must not install a hook handler");
669        assert_quotes_like_the_hookless_reference(&decoded);
670    }
671
672    /// Every quote a decoded pool answers matches the same pool built directly with no hook.
673    fn assert_quotes_like_the_hookless_reference(decoded: &UniswapV4State) {
674        let reference = reference_hookless_state();
675        let (t0, t1) = (token0(), token1());
676
677        // spot_price, both orderings
678        assert_eq!(decoded.spot_price(&t0, &t1).unwrap(), reference.spot_price(&t0, &t1).unwrap());
679        assert_eq!(decoded.spot_price(&t1, &t0).unwrap(), reference.spot_price(&t1, &t0).unwrap());
680
681        // get_limits, both directions
682        assert_eq!(
683            decoded
684                .get_limits(t0.address.clone(), t1.address.clone())
685                .unwrap(),
686            reference
687                .get_limits(t0.address.clone(), t1.address.clone())
688                .unwrap()
689        );
690        assert_eq!(
691            decoded
692                .get_limits(t1.address.clone(), t0.address.clone())
693                .unwrap(),
694            reference
695                .get_limits(t1.address.clone(), t0.address.clone())
696                .unwrap()
697        );
698
699        // get_amount_out, one amount, both directions
700        let amount_in = BigUint::from(1_000_000_000_000_000_u64);
701        for (token_in, token_out) in [(&t0, &t1), (&t1, &t0)] {
702            let from_decoded = decoded
703                .get_amount_out(amount_in.clone(), token_in, token_out)
704                .unwrap();
705            let from_reference = reference
706                .get_amount_out(amount_in.clone(), token_in, token_out)
707                .unwrap();
708            assert_eq!(from_decoded.amount, from_reference.amount);
709            assert_eq!(from_decoded.gas, from_reference.gas);
710        }
711    }
712
713    /// A hook that carries neither swap permission cannot be called during a swap, so it is
714    /// treated exactly like the zero address: no handler, no chain needed, plain V4 pricing on
715    /// every chain, including the chains where the generic VM handler is enabled.
716    #[tokio::test]
717    #[rstest]
718    #[case::no_chain(None)]
719    #[case::robinhood(Some(Chain::Robinhood))]
720    #[case::ethereum(Some(Chain::Ethereum))]
721    async fn hook_without_swap_permissions_decodes_as_hookless(#[case] chain: Option<Chain>) {
722        let decoded = decode_with_chain(hookless_snapshot_with_hook(LIQUIDITY_ONLY_HOOK), chain)
723            .await
724            .expect("a hook that cannot take part in a swap must decode on every chain");
725
726        assert!(
727            decoded.hook.is_none(),
728            "a hook without beforeSwap or afterSwap must not install a hook handler"
729        );
730        assert_quotes_like_the_hookless_reference(&decoded);
731    }
732
733    /// PancakeSwap Infinity `CLAlphaHook` `0xb0ba…4d0f`. Its address has the v4 `beforeSwap` bit
734    /// clear, so it reaches its handler only through the BSC registration.
735    const CLALPHA_HOOK: &str = "0xb0baa371b899950b4ef6a27c21baf5ef7c434d0f";
736
737    fn clalpha_snapshot(start_timestamp: u64) -> ComponentWithState {
738        let mut snapshot = hookless_snapshot_with_hook(CLALPHA_HOOK);
739        snapshot.component.protocol_system = "pancakeswap_infinity_cl_hooks".to_string();
740        snapshot.state.attributes.insert(
741            "alpha_start_timestamp".to_string(),
742            Bytes::from(start_timestamp.to_be_bytes().to_vec()),
743        );
744        snapshot
745    }
746
747    async fn decode_at(
748        snapshot: ComponentWithState,
749        chain: Chain,
750        timestamp: u64,
751    ) -> Result<UniswapV4State, InvalidSnapshotError> {
752        initialize_hook_handlers().expect("hook handler registration should succeed");
753        let all_tokens =
754            HashMap::from([(token0().address, token0()), (token1().address, token1())]);
755        UniswapV4State::try_from_with_header(
756            snapshot,
757            BlockHeader { timestamp, ..Default::default() },
758            &HashMap::default(),
759            &all_tokens,
760            &DecoderContext::new().chain(chain),
761        )
762        .await
763    }
764
765    /// Moves the pool to 1% below its starting price of 1.
766    fn query_one_percent_move(
767        state: &UniswapV4State,
768        token_in: &Token,
769        token_out: &Token,
770    ) -> Result<PoolSwap, SimulationError> {
771        state.query_pool_swap(&QueryPoolSwapParams::new(
772            token_in.clone(),
773            token_out.clone(),
774            SwapConstraint::PoolTargetPrice {
775                target: Price::new(BigUint::from(990_u64), BigUint::from(1_000_u64)),
776                tolerance: 0f64,
777                min_amount_in: None,
778                max_amount_in: None,
779            },
780        ))
781    }
782
783    /// Once open, a CLAlphaHook pool quotes exactly like the same pool without a hook, plus the
784    /// gas of the `beforeSwap` call and of the pool manager dispatching it.
785    #[tokio::test]
786    async fn open_clalpha_pool_quotes_like_a_hookless_pool() {
787        let decoded = decode_at(clalpha_snapshot(1_000), Chain::Bsc, 1_001)
788            .await
789            .expect("an open CLAlphaHook pool decodes on BSC");
790        assert!(decoded.hook.is_some(), "the registered handler is installed despite the bits");
791
792        let reference = reference_hookless_state();
793        let (t0, t1) = (token0(), token1());
794        assert_eq!(decoded.spot_price(&t0, &t1).unwrap(), reference.spot_price(&t0, &t1).unwrap());
795        assert_eq!(
796            decoded
797                .get_limits(t0.address.clone(), t1.address.clone())
798                .unwrap(),
799            reference
800                .get_limits(t0.address.clone(), t1.address.clone())
801                .unwrap()
802        );
803        let amount_in = BigUint::from(1_000_000_000_000_000_u64);
804        for (token_in, token_out) in [(&t0, &t1), (&t1, &t0)] {
805            let from_decoded = decoded
806                .get_amount_out(amount_in.clone(), token_in, token_out)
807                .unwrap();
808            let from_reference = reference
809                .get_amount_out(amount_in.clone(), token_in, token_out)
810                .unwrap();
811            assert_eq!(from_decoded.amount, from_reference.amount);
812            assert_eq!(
813                from_decoded.gas,
814                from_reference.gas + BigUint::from(CLALPHA_BEFORE_SWAP_GAS)
815            );
816
817            let queried = query_one_percent_move(&decoded, token_in, token_out).unwrap();
818            let reference_query = query_one_percent_move(&reference, token_in, token_out).unwrap();
819            assert_eq!(queried.amount_in(), reference_query.amount_in());
820            assert_eq!(queried.amount_out(), reference_query.amount_out());
821        }
822    }
823
824    /// Before the start time, and when the start time is zero, the pool keeps a spot price but
825    /// cannot trade: no capacity and a refused quote.
826    #[tokio::test]
827    #[rstest]
828    #[case::not_started(2_000)]
829    #[case::disabled(0)]
830    async fn closed_clalpha_pool_keeps_a_price_but_cannot_trade(#[case] start: u64) {
831        let decoded = decode_at(clalpha_snapshot(start), Chain::Bsc, 1_000)
832            .await
833            .expect("a closed CLAlphaHook pool still decodes");
834        let (t0, t1) = (token0(), token1());
835
836        assert_eq!(
837            decoded.spot_price(&t0, &t1).unwrap(),
838            reference_hookless_state()
839                .spot_price(&t0, &t1)
840                .unwrap()
841        );
842        for (token_in, token_out) in [(&t0, &t1), (&t1, &t0)] {
843            assert_eq!(
844                decoded
845                    .get_limits(token_in.address.clone(), token_out.address.clone())
846                    .unwrap(),
847                (BigUint::zero(), BigUint::zero())
848            );
849            let err = decoded
850                .get_amount_out(BigUint::from(1_000_u64), token_in, token_out)
851                .unwrap_err();
852            assert!(
853                matches!(&err, SimulationError::InvalidInput(message, _) if message.contains("PoolNotStarted")),
854                "{err:?}"
855            );
856            let err = query_one_percent_move(&decoded, token_in, token_out).unwrap_err();
857            assert!(matches!(err, SimulationError::InvalidInput(..)), "{err:?}");
858        }
859    }
860
861    /// The execution block opens the pool, and a start time moved past it, as the first
862    /// CLAlphaHook version allows after launch, pauses it again.
863    #[tokio::test]
864    async fn clalpha_pool_follows_the_execution_block_and_start_time_updates() {
865        let mut state = decode_at(clalpha_snapshot(2_000), Chain::Bsc, 1_000)
866            .await
867            .unwrap();
868        let (t0, t1) = (token0(), token1());
869        let quote =
870            |state: &UniswapV4State| state.get_amount_out(BigUint::from(1_000_000_u64), &t0, &t1);
871        assert!(quote(&state).is_err());
872
873        assert!(state.apply_block(&BlockContext::new(2, 2_001)), "opening re-emits the pool");
874        assert!(quote(&state).is_ok());
875
876        state
877            .delta_transition(
878                ProtocolStateDelta {
879                    component_id: "State1".to_string(),
880                    updated_attributes: HashMap::from([(
881                        "alpha_start_timestamp".to_string(),
882                        Bytes::from(7_200_u64.to_be_bytes().to_vec()),
883                    )]),
884                    deleted_attributes: HashSet::new(),
885                },
886                &HashMap::new(),
887                &Balances::default(),
888            )
889            .unwrap();
890        assert!(quote(&state).is_err(), "a rescheduled start pauses the pool");
891
892        assert!(state.apply_block(&BlockContext::new(3, 7_201)));
893        assert!(quote(&state).is_ok());
894    }
895
896    /// The registration is per chain: the same address in an ordinary Uniswap V4 pool elsewhere
897    /// is judged by its address bits, which for this one say it cannot take part in a swap.
898    #[tokio::test]
899    async fn clalpha_address_on_another_chain_is_not_a_clalpha_hook() {
900        let decoded = decode_at(hookless_snapshot_with_hook(CLALPHA_HOOK), Chain::Robinhood, 1_000)
901            .await
902            .unwrap();
903        assert!(decoded.hook.is_none());
904    }
905
906    /// An Infinity hooks pool never falls back to the address bits, which for `0xb0ba…4d0f` say
907    /// it cannot take part in a swap: without a chain it is rejected like any other hooked pool
908    /// rather than decoded as a hookless pool that quotes while the hook refuses swaps.
909    #[tokio::test]
910    async fn clalpha_pool_without_a_chain_is_rejected() {
911        let result = decode_with_chain(clalpha_snapshot(2_000), None).await;
912
913        let Err(InvalidSnapshotError::ValueError(message)) = result else {
914            panic!("an Infinity hooks pool must not decode without a chain: {result:?}");
915        };
916        assert!(message.contains("DecoderContext.chain"), "{message}");
917    }
918
919    #[tokio::test]
920    async fn clalpha_pool_without_a_start_time_fails_to_decode() {
921        let snapshot = hookless_snapshot_with_hook(CLALPHA_HOOK);
922        let err = decode_at(snapshot, Chain::Bsc, 1_000)
923            .await
924            .unwrap_err();
925        assert!(
926            matches!(&err, InvalidSnapshotError::MissingAttribute(name) if name == "alpha_start_timestamp"),
927            "{err:?}"
928        );
929    }
930
931    /// A non-zero hook that does take part in swaps but has no registered handler is rejected
932    /// rather than quoted as if the hook were absent, and it still needs a chain to decide that.
933    #[tokio::test]
934    #[rstest]
935    #[case::robinhood_fails_closed(Some(Chain::Robinhood), "unsupported uniswap v4 hook")]
936    #[case::no_chain_is_rejected(None, "DecoderContext.chain")]
937    async fn nonzero_unsupported_hook_is_rejected(
938        #[case] chain: Option<Chain>,
939        #[case] expected_message: &str,
940    ) {
941        let result = decode_with_chain(hookless_snapshot_with_hook(UNKNOWN_HOOK), chain).await;
942
943        let Err(InvalidSnapshotError::ValueError(message)) = result else {
944            panic!("an unregistered non-zero hook must not decode");
945        };
946        assert!(message.contains(expected_message), "{message}");
947    }
948
949    /// The `hooks` attribute arrives from the stream, so a value that is not a 20-byte address
950    /// must be reported as a bad snapshot rather than panic the decoding task.
951    #[tokio::test]
952    async fn malformed_hooks_attribute_is_rejected_without_panicking() {
953        let mut snapshot = hookless_snapshot_with_hook(ZERO_HOOK);
954        snapshot
955            .component
956            .static_attributes
957            .insert("hooks".to_string(), Bytes::from(vec![0x11_u8; 19]));
958
959        let result = decode_with_chain(snapshot, Some(Chain::Ethereum)).await;
960
961        let Err(InvalidSnapshotError::ValueError(message)) = result else {
962            panic!("a 19-byte hooks attribute must not decode");
963        };
964        assert!(message.contains("hooks"), "{message}");
965    }
966
967    #[tokio::test]
968    async fn test_usv4_zero_hook_pool_with_no_ticks_still_decodes() {
969        // Tick leniency is keyed on the `hooks` attribute being present, not on the address being
970        // non-zero: a freshly initialised hookless pool has no ticks yet and must still decode.
971        let mut snapshot = usv4_snapshot_with_hook(ZERO_HOOK);
972        snapshot
973            .state
974            .attributes
975            .remove("ticks/60/net_liquidity");
976
977        let decoded = decode_with_chain(snapshot, None)
978            .await
979            .expect("a hookless pool with no ticks must decode");
980
981        assert!(decoded.hook.is_none());
982    }
983
984    #[tokio::test]
985    #[rstest]
986    #[case::missing_liquidity("liquidity")]
987    #[case::missing_sqrt_price("sqrt_price")]
988    #[case::missing_tick("tick")]
989    #[case::missing_tick_liquidity("tick_liquidities")]
990    #[case::missing_fee("key_lp_fee")]
991    #[case::missing_fee("protocol_fees/one2zero")]
992    #[case::missing_fee("protocol_fees/zero2one")]
993    async fn test_usv4_try_from_invalid(#[case] missing_attribute: String) {
994        // remove missing attribute
995        let mut component = usv4_component();
996        let mut attributes = usv4_attributes();
997        attributes.remove(&missing_attribute);
998
999        if missing_attribute == "tick_liquidities" {
1000            attributes.remove("ticks/60/net_liquidity");
1001        }
1002
1003        if missing_attribute == "sqrt_price" {
1004            attributes.remove("sqrt_price_x96");
1005        }
1006
1007        if missing_attribute == "key_lp_fee" {
1008            component
1009                .static_attributes
1010                .remove("key_lp_fee");
1011        }
1012
1013        let snapshot = ComponentWithState {
1014            state: ProtocolComponentState {
1015                component_id: "State1".to_owned(),
1016                attributes,
1017                balances: HashMap::new(),
1018            },
1019            component,
1020            component_tvl: None,
1021            entrypoints: Vec::new(),
1022        };
1023
1024        let result = try_decode_snapshot_with_defaults::<UniswapV4State>(snapshot).await;
1025
1026        assert!(result.is_err());
1027        assert!(matches!(
1028            result.err().unwrap(),
1029            InvalidSnapshotError::MissingAttribute(attr) if attr == missing_attribute
1030        ));
1031    }
1032
1033    // Pons V2 on Robinhood, decoded through this very `TryFromWithBlock`.
1034
1035    use std::{fs, path::Path};
1036
1037    use serde::Deserialize;
1038
1039    use super::pons_fixture;
1040    use crate::evm::protocol::uniswap_v4::hooks::{
1041        hook_handler::HookHandler,
1042        hook_handler_creator::initialize_hook_handlers,
1043        pons_v2::hook_handler::{PonsV2HookHandler, PONS_V2_HOOK_ROBINHOOD},
1044    };
1045
1046    /// The native Pons handler a decoded state installed, or a panic naming what it installed
1047    /// instead.
1048    fn pons_handler(state: &UniswapV4State) -> &PonsV2HookHandler {
1049        let hook = state
1050            .hook
1051            .as_ref()
1052            .expect("a Pons pool must decode with a hook handler");
1053        hook.as_any()
1054            .downcast_ref::<PonsV2HookHandler>()
1055            .unwrap_or_else(|| panic!("expected the native Pons handler at {}", hook.address()))
1056    }
1057
1058    /// Whether `state` quotes through the native Pons handler.
1059    fn is_pons(state: &UniswapV4State) -> bool {
1060        state.hook.as_ref().is_some_and(|hook| {
1061            hook.as_any()
1062                .downcast_ref::<PonsV2HookHandler>()
1063                .is_some()
1064        })
1065    }
1066
1067    /// A millionth, a ten-thousandth and a hundredth of what the pool holds of the input token,
1068    /// so one test covers three trade sizes two orders of magnitude apart without hard-coding an
1069    /// amount per direction.
1070    fn probe_amounts(reserve_in: &BigUint) -> [BigUint; 3] {
1071        [
1072            reserve_in / BigUint::from(1_000_000u32),
1073            reserve_in / BigUint::from(10_000u32),
1074            reserve_in / BigUint::from(100u32),
1075        ]
1076    }
1077
1078    /// A Pons pool decoded on Robinhood charges the fee and the tax `registerPool` froze for it,
1079    /// and nothing else: what it quotes is the hookless output less two independently floored
1080    /// cuts, and what it prices is the hookless price marked up by the same take.
1081    #[tokio::test]
1082    async fn pons_pool_decodes_on_robinhood_and_charges_hook_fee() {
1083        initialize_hook_handlers().expect("hook handler registration should succeed");
1084
1085        let hooked = pons_fixture::decode_on(pons_fixture::snapshot(), Chain::Robinhood)
1086            .await
1087            .expect("the recorded Pons pool must decode on Robinhood");
1088        let core = pons_fixture::decode_on(pons_fixture::hookless_snapshot(), Chain::Robinhood)
1089            .await
1090            .expect("the same pool with no hook must decode too");
1091
1092        let handler = pons_handler(&hooked);
1093        assert_eq!(u32::from(handler.hook_fee_bps()), pons_fixture::HOOK_FEE_BPS);
1094        assert_eq!(u32::from(handler.creator_tax_bps()), pons_fixture::CREATOR_TAX_BPS);
1095        assert_eq!(handler.address(), PONS_V2_HOOK_ROBINHOOD);
1096        assert!(core.hook.is_none(), "the reference pool must carry no hook");
1097
1098        let (xlg, nvda) = (pons_fixture::xlg(), pons_fixture::nvda());
1099        for (token_in, token_out) in [(&xlg, &nvda), (&nvda, &xlg)] {
1100            let (limit_in, core_limit_out) = core
1101                .get_limits(token_in.address.clone(), token_out.address.clone())
1102                .expect("a pool holding a full range position has limits");
1103
1104            for amount_in in probe_amounts(&pons_fixture::reserve(token_in)) {
1105                let core_out = core
1106                    .get_amount_out(amount_in.clone(), token_in, token_out)
1107                    .expect("the reference pool quotes every probe")
1108                    .amount;
1109                let hooked_out = hooked
1110                    .get_amount_out(amount_in.clone(), token_in, token_out)
1111                    .expect("the hooked pool quotes every probe")
1112                    .amount;
1113
1114                let expected = pons_fixture::net_of_hook_take(&core_out);
1115                assert!(expected < core_out, "the hook must take something out of {core_out}");
1116                assert_eq!(
1117                    hooked_out, expected,
1118                    "{} -> {}: {amount_in} in",
1119                    token_in.symbol, token_out.symbol
1120                );
1121            }
1122
1123            // `get_limits` reports what a swapper receives, so the hook's cut comes off the
1124            // output while the input the pool can absorb is unchanged.
1125            let (hooked_limit_in, hooked_limit_out) = hooked
1126                .get_limits(token_in.address.clone(), token_out.address.clone())
1127                .expect("the hooked pool has limits too");
1128            assert_eq!(hooked_limit_in, limit_in);
1129            assert_eq!(hooked_limit_out, pons_fixture::net_of_hook_take(&core_limit_out));
1130        }
1131
1132        // Pons takes its cut out of the output, so buying one `base` costs `core / (1 - rate)`.
1133        // At 100 + 100 bps that is `1 / 0.98` of the hookless price, in both orderings.
1134        for (base, quote) in [(&xlg, &nvda), (&nvda, &xlg)] {
1135            let hooked_price = hooked
1136                .spot_price(base, quote)
1137                .expect("the hook prices its own fee");
1138            let core_price = core
1139                .spot_price(base, quote)
1140                .expect("a hookless pool always prices");
1141            let ratio = hooked_price / core_price;
1142            assert!((ratio * 0.98 - 1.0).abs() < 1e-9, "hooked/core is {ratio}, not 1/0.98");
1143        }
1144    }
1145
1146    /// What a tampered Pons snapshot has to do.
1147    #[derive(Debug, Clone, Copy)]
1148    enum Outcome {
1149        /// Decodes, carrying these terms.
1150        Decodes(u16, u16),
1151        /// Rejected as a missing attribute of this name.
1152        Missing(&'static str),
1153        /// Rejected as a value error naming this attribute.
1154        Value(&'static str),
1155    }
1156
1157    /// The substreams module writes each bps with `BigInt::to_signed_bytes_be`, which is
1158    /// minimal-width: one byte below 256, two above.
1159    const BPS_0: &[u8] = &[0x00];
1160    const BPS_1: &[u8] = &[0x01];
1161    const BPS_100: &[u8] = &[0x64];
1162    const BPS_1001: &[u8] = &[0x03, 0xe9];
1163    const BPS_2000: &[u8] = &[0x07, 0xd0];
1164    /// 1,000,001: in range for the three bytes it occupies, far past the `uint16` the contract
1165    /// keeps the rate in.
1166    const BPS_WIDE: &[u8] = &[0x0f, 0x42, 0x41];
1167
1168    /// A Pons snapshot whose terms disagree with what `_registerPool` could have written is
1169    /// rejected rather than quoted at whatever the attributes happen to say. The contract caps
1170    /// `hookFeeBps` at 1,000 and the sum at 2,000, with no separate cap on the creator tax.
1171    #[tokio::test]
1172    #[rstest]
1173    #[case::missing_hook_fee(None, Some(BPS_100), Outcome::Missing("pons_hook_fee_bps"))]
1174    #[case::missing_creator_tax(Some(BPS_100), None, Outcome::Missing("pons_creator_tax_bps"))]
1175    #[case::hook_fee_over_cap(Some(BPS_1001), Some(BPS_0), Outcome::Value("pons_hook_fee_bps"))]
1176    #[case::sum_over_cap(Some(BPS_1), Some(BPS_2000), Outcome::Value("pons_creator_tax_bps"))]
1177    #[case::tax_may_take_the_whole_sum(Some(BPS_0), Some(BPS_2000), Outcome::Decodes(0, 2_000))]
1178    #[case::three_bytes_past_uint16(
1179        Some(BPS_WIDE),
1180        Some(BPS_0),
1181        Outcome::Value("pons_hook_fee_bps")
1182    )]
1183    async fn pons_snapshot_fails_closed_on_bad_attributes(
1184        #[case] hook_fee_bps: Option<&[u8]>,
1185        #[case] creator_tax_bps: Option<&[u8]>,
1186        #[case] expected: Outcome,
1187    ) {
1188        initialize_hook_handlers().expect("hook handler registration should succeed");
1189
1190        let mut snapshot = pons_fixture::snapshot();
1191        for (name, value) in
1192            [("pons_hook_fee_bps", hook_fee_bps), ("pons_creator_tax_bps", creator_tax_bps)]
1193        {
1194            let attributes = &mut snapshot.component.static_attributes;
1195            match value {
1196                Some(value) => attributes.insert(name.to_string(), Bytes::from(value.to_vec())),
1197                None => attributes.remove(name),
1198            };
1199        }
1200
1201        let result = pons_fixture::decode_on(snapshot, Chain::Robinhood).await;
1202
1203        match expected {
1204            Outcome::Decodes(hook_fee, creator_tax) => {
1205                let decoded = result.expect("terms the contract could have written must decode");
1206                let handler = pons_handler(&decoded);
1207                assert_eq!(handler.hook_fee_bps(), hook_fee);
1208                assert_eq!(handler.creator_tax_bps(), creator_tax);
1209            }
1210            Outcome::Missing(name) => {
1211                let Err(InvalidSnapshotError::MissingAttribute(reported)) = result else {
1212                    panic!("expected a missing-attribute error, got {result:?}");
1213                };
1214                assert_eq!(reported, name);
1215            }
1216            Outcome::Value(name) => {
1217                let Err(InvalidSnapshotError::ValueError(message)) = result else {
1218                    panic!("expected a value error, got {result:?}");
1219                };
1220                assert!(message.contains(name), "{message}");
1221            }
1222        }
1223    }
1224
1225    /// The same pool behind a hook this crate does not model fails to decode on Robinhood, so a
1226    /// hook that could move the price is never quoted as if it were absent.
1227    #[tokio::test]
1228    async fn unknown_hook_on_robinhood_fails_decode() {
1229        initialize_hook_handlers().expect("hook handler registration should succeed");
1230
1231        let result =
1232            pons_fixture::decode_on(pons_fixture::unknown_hook_snapshot(), Chain::Robinhood).await;
1233
1234        let Err(InvalidSnapshotError::ValueError(message)) = result else {
1235            panic!("an unregistered hook must not decode, got {result:?}");
1236        };
1237        assert!(message.contains("unsupported uniswap v4 hook"), "{message}");
1238        assert!(message.contains("robinhood"), "{message}");
1239    }
1240
1241    /// Pons is deployed on Robinhood alone, so the same address on Ethereum is a different
1242    /// deployment and the native handler must not serve it there. Whether the generic VM path
1243    /// then manages to build a handler is beside the point; it must not be the Pons one.
1244    #[tokio::test]
1245    async fn pons_same_address_on_ethereum_is_not_native() {
1246        initialize_hook_handlers().expect("hook handler registration should succeed");
1247
1248        match pons_fixture::decode_on(pons_fixture::snapshot(), Chain::Ethereum).await {
1249            Ok(decoded) => assert!(
1250                !is_pons(&decoded),
1251                "the Pons handler must not serve its address off Robinhood"
1252            ),
1253            Err(error) => {
1254                // What actually happens today: the generic VM handler is built and then fails
1255                // for want of VM prerequisites this snapshot does not carry. Either way the
1256                // failure must not come from the Pons creator, and Ethereum being a generic-VM
1257                // chain it must not be the fail-closed rejection Robinhood gives either.
1258                let message = error.to_string();
1259                assert!(
1260                    !message.contains("pons_"),
1261                    "the Pons creator ran off Robinhood: {message}"
1262                );
1263                assert!(
1264                    !message.contains("unsupported uniswap v4 hook"),
1265                    "ethereum runs the generic VM handler rather than failing closed: {message}"
1266                );
1267            }
1268        }
1269    }
1270
1271    /// A second quote taken on the state the first one returned sees the pool the first swap
1272    /// left behind. The hook moves nothing: the pool it hands back is the hookless pool's, swap
1273    /// for swap, and only the amounts differ, by the hook's cut.
1274    #[tokio::test]
1275    #[rstest]
1276    #[case::zero_for_one(true)]
1277    #[case::one_for_zero(false)]
1278    async fn pons_sequential_swaps_use_returned_state(#[case] zero_for_one: bool) {
1279        initialize_hook_handlers().expect("hook handler registration should succeed");
1280
1281        let hooked = pons_fixture::decode_on(pons_fixture::snapshot(), Chain::Robinhood)
1282            .await
1283            .expect("the recorded Pons pool must decode on Robinhood");
1284        let core = pons_fixture::decode_on(pons_fixture::hookless_snapshot(), Chain::Robinhood)
1285            .await
1286            .expect("the same pool with no hook must decode too");
1287
1288        let (xlg, nvda) = (pons_fixture::xlg(), pons_fixture::nvda());
1289        let (token_in, token_out) = if zero_for_one { (&xlg, &nvda) } else { (&nvda, &xlg) };
1290        let amount_in = pons_fixture::reserve(token_in) / BigUint::from(100u32);
1291
1292        let hooked_first = hooked
1293            .get_amount_out(amount_in.clone(), token_in, token_out)
1294            .expect("the first hooked quote fits the pool");
1295        let core_first = core
1296            .get_amount_out(amount_in.clone(), token_in, token_out)
1297            .expect("the first hookless quote fits the pool");
1298
1299        // The hook only accrues accounting balances, so the pool a hooked swap leaves behind is
1300        // the one a hookless swap of the same size leaves: same price, tick and liquidity.
1301        assert_eq!(
1302            format!("{:?}", hooked_first.new_state),
1303            format!("{:?}", core_first.new_state),
1304            "the hook must not move the pool"
1305        );
1306
1307        let hooked_second = hooked_first
1308            .new_state
1309            .get_amount_out(amount_in.clone(), token_in, token_out)
1310            .expect("the second hooked quote fits the pool");
1311        let core_second = core_first
1312            .new_state
1313            .get_amount_out(amount_in, token_in, token_out)
1314            .expect("the second hookless quote fits the pool");
1315
1316        assert!(
1317            core_second.amount < core_first.amount,
1318            "the second swap must execute at a worse price, or the state was not carried over"
1319        );
1320        assert_eq!(hooked_second.amount, pons_fixture::net_of_hook_take(&core_second.amount));
1321        assert_eq!(
1322            format!("{:?}", hooked_second.new_state),
1323            format!("{:?}", core_second.new_state)
1324        );
1325    }
1326
1327    #[derive(Deserialize)]
1328    struct RecordedSwaps {
1329        swaps: Vec<RecordedSwap>,
1330    }
1331
1332    #[derive(Deserialize)]
1333    struct RecordedSwap {
1334        label: String,
1335        currency0: String,
1336        currency1: String,
1337        tick_spacing: i32,
1338        hook_fee_bps: u16,
1339        creator_tax_bps: u16,
1340        pre_state: RecordedPoolState,
1341        position: RecordedPosition,
1342        swap: RecordedSwapLog,
1343        hook_fee: RecordedHookFee,
1344    }
1345
1346    #[derive(Deserialize)]
1347    struct RecordedPoolState {
1348        sqrt_price_x96: String,
1349        liquidity: String,
1350        tick: i32,
1351    }
1352
1353    #[derive(Deserialize)]
1354    struct RecordedPosition {
1355        tick_lower: i32,
1356        tick_upper: i32,
1357        liquidity: String,
1358    }
1359
1360    #[derive(Deserialize)]
1361    struct RecordedSwapLog {
1362        zero_for_one: bool,
1363        amount0: String,
1364        amount1: String,
1365        sqrt_price_x96: String,
1366        liquidity: String,
1367        tick: i32,
1368    }
1369
1370    #[derive(Deserialize)]
1371    struct RecordedHookFee {
1372        fee_amount: String,
1373        tax_amount: String,
1374    }
1375
1376    fn recorded_swaps() -> Vec<RecordedSwap> {
1377        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
1378            .join("tests/assets/hooks/pons_v2/recorded_swaps.json");
1379        let raw =
1380            fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
1381        serde_json::from_str::<RecordedSwaps>(&raw)
1382            .expect("the recorded swap fixture should parse")
1383            .swaps
1384    }
1385
1386    fn recorded_token(address: &str) -> Token {
1387        Token::new(
1388            &Bytes::from_str(address).expect("recorded currency addresses parse"),
1389            "RECORDED",
1390            18,
1391            0,
1392            &[Some(10_000)],
1393            Chain::Robinhood,
1394            100,
1395        )
1396    }
1397
1398    fn u256_from_decimal(value: &str, what: &str) -> U256 {
1399        U256::from_str_radix(value, 10).unwrap_or_else(|e| panic!("{what} = {value}: {e}"))
1400    }
1401
1402    /// Rebuilds the pool a recorded swap ran against: one full-range position and nothing else,
1403    /// no LP fee and no protocol fee, which is what a Pons `PoolKey` carries.
1404    fn recorded_pool(recorded: &RecordedSwap) -> UniswapV4State {
1405        let position = recorded
1406            .position
1407            .liquidity
1408            .parse::<i128>()
1409            .unwrap_or_else(|e| panic!("{}: position liquidity: {e}", recorded.label));
1410
1411        let mut pool = UniswapV4State::new(
1412            recorded
1413                .pre_state
1414                .liquidity
1415                .parse::<u128>()
1416                .unwrap_or_else(|e| panic!("{}: pre-state liquidity: {e}", recorded.label)),
1417            u256_from_decimal(&recorded.pre_state.sqrt_price_x96, "pre-state sqrt price"),
1418            UniswapV4Fees::new(0, 0, 0),
1419            recorded.pre_state.tick,
1420            recorded.tick_spacing,
1421            vec![
1422                TickInfo::new(recorded.position.tick_lower, position).expect("lower tick is valid"),
1423                TickInfo::new(recorded.position.tick_upper, -position)
1424                    .expect("upper tick is valid"),
1425            ],
1426        )
1427        .unwrap_or_else(|e| panic!("{}: rebuilding the pool: {e:?}", recorded.label));
1428
1429        pool.set_hook_handler(Box::new(PonsV2HookHandler::new(
1430            PONS_V2_HOOK_ROBINHOOD,
1431            recorded.hook_fee_bps,
1432            recorded.creator_tax_bps,
1433        )));
1434        pool
1435    }
1436
1437    /// Every recorded swap is a real Robinhood transaction. Quoting its input against the state
1438    /// the previous swap on that pool left behind has to reproduce to the wei what the swapper
1439    /// received once the hook had taken its cut, and leave the pool where the Swap log says it
1440    /// ended up.
1441    #[tokio::test]
1442    async fn pons_quotes_match_recorded_swaps() {
1443        let swaps = recorded_swaps();
1444        assert!(swaps.len() >= 6, "the fixture should cover both directions on several pools");
1445
1446        for recorded in swaps {
1447            let pool = recorded_pool(&recorded);
1448            let (currency0, currency1) =
1449                (recorded_token(&recorded.currency0), recorded_token(&recorded.currency1));
1450            let (token_in, token_out) = if recorded.swap.zero_for_one {
1451                (&currency0, &currency1)
1452            } else {
1453                (&currency1, &currency0)
1454            };
1455
1456            let parse = |value: &str, what: &str| {
1457                value
1458                    .parse::<i128>()
1459                    .unwrap_or_else(|e| panic!("{}: {what} = {value}: {e}", recorded.label))
1460            };
1461            let (amount0, amount1) = (
1462                parse(&recorded.swap.amount0, "amount0"),
1463                parse(&recorded.swap.amount1, "amount1"),
1464            );
1465            // The Swap log is the swapper's balance delta, so the leg they paid is negative.
1466            let (paid, received) =
1467                if recorded.swap.zero_for_one { (amount0, amount1) } else { (amount1, amount0) };
1468            assert!(paid < 0 && received > 0, "{}: not an exact-input swap", recorded.label);
1469
1470            let take = parse(&recorded.hook_fee.fee_amount, "fee_amount") +
1471                parse(&recorded.hook_fee.tax_amount, "tax_amount");
1472            let expected = BigUint::from(
1473                u128::try_from(received - take).expect("what the swapper kept is positive"),
1474            );
1475
1476            let quote = pool
1477                .get_amount_out(BigUint::from(paid.unsigned_abs()), token_in, token_out)
1478                .unwrap_or_else(|e| panic!("{}: {e:?}", recorded.label));
1479
1480            assert_eq!(quote.amount, expected, "{}: amount out", recorded.label);
1481
1482            // The Swap log also carries the state the swap left the pool in. A `UniswapV4State`
1483            // prints its liquidity, price, tick, fees and tick spacing and nothing else, so
1484            // building the logged state and comparing the two covers every one of them.
1485            let logged = UniswapV4State::new(
1486                recorded
1487                    .swap
1488                    .liquidity
1489                    .parse::<u128>()
1490                    .unwrap_or_else(|e| panic!("{}: post-swap liquidity: {e}", recorded.label)),
1491                u256_from_decimal(&recorded.swap.sqrt_price_x96, "post-swap sqrt price"),
1492                UniswapV4Fees::new(0, 0, 0),
1493                recorded.swap.tick,
1494                recorded.tick_spacing,
1495                Vec::new(),
1496            )
1497            .unwrap_or_else(|e| panic!("{}: building the logged state: {e:?}", recorded.label));
1498
1499            assert_eq!(
1500                format!("{:?}", quote.new_state),
1501                format!("{logged:?}"),
1502                "{}: the pool the quote leaves behind",
1503                recorded.label
1504            );
1505        }
1506    }
1507}