Skip to main content

tycho_simulation/evm/protocol/uniswap_v4/
decoder.rs

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