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