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