tycho-simulation 0.504.0

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::{
    collections::HashMap,
    str::FromStr,
    sync::{LazyLock, RwLock},
};

use alloy::primitives::{Address, U256};
use revm::{primitives::KECCAK_EMPTY, state::AccountInfo};
use tycho_common::{
    models::{token::Token, Chain},
    simulation::errors::SimulationError,
    Bytes,
};

use crate::{
    evm::{
        engine_db::{create_engine, engine_db_interface::EngineDatabaseInterface, SHARED_TYCHO_DB},
        protocol::{
            uniswap_v4::{
                hooks::{
                    angstrom::hook_handler_creator::AngstromHookCreator,
                    generic_vm_hook_handler::GenericVMHookHandler,
                    hook_handler::HookHandler,
                    pancakeswap_clalpha::{
                        hook_handler::CLALPHA_HOOKS_BSC,
                        hook_handler_creator::PancakeswapClAlphaHookCreator,
                    },
                    pons_v2::{
                        hook_handler::PONS_V2_HOOK_ROBINHOOD,
                        hook_handler_creator::PonsV2HookCreator,
                    },
                },
                state::UniswapV4State,
            },
            vm::constants::EXTERNAL_ACCOUNT,
        },
    },
    protocol::errors::InvalidSnapshotError,
};

/// Parameters for creating a HookHandler.
pub struct HookCreationParams<'a> {
    hook_address: Address,
    account_balances: &'a HashMap<Bytes, HashMap<Bytes, Bytes>>,
    all_tokens: &'a HashMap<Bytes, Token>,
    #[expect(
        dead_code,
        reason = "no hook handler reads it; removing it changes the public HookCreationParams::new, a breaking change"
    )]
    state: UniswapV4State,
    /// Attributes of the component. If an attribute's value is a `bigint`,
    /// it will be encoded as a big endian signed hex string. See ResponseProtocolState for more
    /// details.
    pub(crate) attributes: &'a HashMap<String, Bytes>,
    #[expect(
        dead_code,
        reason = "no hook handler reads it; removing it changes the public HookCreationParams::new, a breaking change"
    )]
    /// Mapping from token address to big-endian encoded balance for this component.
    balances: &'a HashMap<Bytes, Bytes>,
    /// Show vm traces in simulations or not
    vm_traces: Option<bool>,
    /// Timestamp of the block the snapshot was decoded at, for hooks whose behavior depends on
    /// time. `None` when the caller has no block header.
    block_timestamp: Option<u64>,
}

impl<'a> HookCreationParams<'a> {
    pub fn new(
        hook_address: Address,
        account_balances: &'a HashMap<Bytes, HashMap<Bytes, Bytes>>,
        all_tokens: &'a HashMap<Bytes, Token>,
        state: UniswapV4State,
        attributes: &'a HashMap<String, Bytes>,
        balances: &'a HashMap<Bytes, Bytes>,
        vm_traces: Option<bool>,
    ) -> Self {
        Self {
            hook_address,
            account_balances,
            all_tokens,
            state,
            attributes,
            balances,
            vm_traces,
            block_timestamp: None,
        }
    }

    /// Records the timestamp of the block the snapshot was decoded at.
    pub fn with_block_timestamp(mut self, timestamp: u64) -> Self {
        self.block_timestamp = Some(timestamp);
        self
    }

    /// Timestamp of the block the snapshot was decoded at, if the caller provided one.
    pub fn block_timestamp(&self) -> Option<u64> {
        self.block_timestamp
    }

    /// The address of the hook the pool was created with.
    pub fn hook_address(&self) -> Address {
        self.hook_address
    }
}

pub trait HookHandlerCreator: Send + Sync {
    fn instantiate_hook_handler(
        &self,
        params: HookCreationParams,
    ) -> Result<Box<dyn HookHandler>, InvalidSnapshotError>;
}

pub struct GenericVMHookHandlerCreator;

impl HookHandlerCreator for GenericVMHookHandlerCreator {
    fn instantiate_hook_handler(
        &self,
        params: HookCreationParams<'_>,
    ) -> Result<Box<dyn HookHandler>, InvalidSnapshotError> {
        let pool_manager_address_bytes = params
            .attributes
            .get("balance_owner")
            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("balance_owner".to_string()))?;

        let pool_manager_address = Address::from_slice(&pool_manager_address_bytes.0);

        let limits_entrypoint = params
            .attributes
            .get("limits_entrypoint")
            .and_then(|bytes| String::from_utf8(bytes.0.to_vec()).ok());

        let is_euler = params
            .attributes
            .get("hook_identifier")
            .and_then(|bytes| String::from_utf8(bytes.0.to_vec()).ok())
            .unwrap_or_default() ==
            "euler_v1";

        let mut trace = false;
        if let Some(vm_traces) = params.vm_traces {
            trace = vm_traces
        }

        let engine = create_engine(SHARED_TYCHO_DB.clone(), trace).map_err(|e| {
            InvalidSnapshotError::VMError(SimulationError::FatalError(format!(
                "Failed to create engine: {e:?}"
            )))
        })?;

        let external_account_info = AccountInfo {
            balance: U256::from(0),
            nonce: 0u64,
            code_hash: KECCAK_EMPTY,
            code: None,
        };

        engine
            .state
            .init_account(*EXTERNAL_ACCOUNT, external_account_info, None, true)
            .map_err(|err| {
                InvalidSnapshotError::VMError(SimulationError::FatalError(format!(
                    "Failed to init external account: {err:?}"
                )))
            })?;

        let hook_handler = GenericVMHookHandler::new(
            params.hook_address,
            engine,
            pool_manager_address,
            params.all_tokens.clone(),
            params.account_balances.clone(),
            limits_entrypoint,
            is_euler,
        )
        .map_err(InvalidSnapshotError::VMError)?;

        Ok(Box::new(hook_handler))
    }
}

/// Chains on which a hook with no registered native handler is simulated with the generic VM
/// handler.
///
/// Anywhere else an unregistered hook is rejected at decode time, so a pool whose hook can move
/// the price is never quoted as if the hook were absent.
pub const GENERIC_VM_HOOK_CHAINS: [Chain; 2] = [Chain::Ethereum, Chain::Unichain];

/// Angstrom's Uniswap V4 hook, deployed on Ethereum mainnet only.
const ANGSTROM_HOOK_ADDRESS: &str = "0x0000000aa232009084Bd71A5797d089AA4Edfad4";

/// Handler creators keyed by chain and hook address. The same hook address on two chains is two
/// different deployments, so the chain is part of the key.
type HookHandlerRegistry = HashMap<(Chain, Address), Box<dyn HookHandlerCreator>>;

// Workaround for stateless decoder trait.
static HANDLER_FACTORY: LazyLock<RwLock<HookHandlerRegistry>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));

static DEFAULT_HANDLER: LazyLock<Box<dyn HookHandlerCreator>> =
    LazyLock::new(|| Box::new(GenericVMHookHandlerCreator {}));

/// Registers the hook handlers this crate ships with.
///
/// Calling it more than once is harmless: each registration replaces the previous one for the
/// same chain and hook.
pub fn initialize_hook_handlers() -> Result<(), SimulationError> {
    let angstrom_hook_address = Address::from_str(ANGSTROM_HOOK_ADDRESS).map_err(|e| {
        SimulationError::FatalError(format!("Failed to parse Angstrom hook address: {e}"))
    })?;
    // Angstrom's attributes are only produced by the Ethereum manifest, so the same address on
    // another chain is not an Angstrom pool.
    register_hook_handler(Chain::Ethereum, angstrom_hook_address, Box::new(AngstromHookCreator))?;

    // Pons V2 is deployed on Robinhood alone, and only the Robinhood manifest emits the
    // `pons_*` attributes its creator reads.
    register_hook_handler(Chain::Robinhood, PONS_V2_HOOK_ROBINHOOD, Box::new(PonsV2HookCreator))?;

    // PancakeSwap Infinity's CLAlphaHook. Infinity takes hook permissions from the pool key, not
    // the address, so these hooks reach their handler only because they are registered.
    for hook in CLALPHA_HOOKS_BSC {
        register_hook_handler(Chain::Bsc, hook, Box::new(PancakeswapClAlphaHookCreator))?;
    }

    Ok(())
}

/// Registers `handler` as the native handler for `hook` on `chain`, replacing any previous
/// registration for that pair.
pub fn register_hook_handler(
    chain: Chain,
    hook: Address,
    handler: Box<dyn HookHandlerCreator>,
) -> Result<(), SimulationError> {
    HANDLER_FACTORY
        .write()
        .map_err(|e| SimulationError::FatalError(e.to_string()))?
        .insert((chain, hook), handler);
    Ok(())
}

/// Whether a native handler is registered for `hook` on `chain`.
///
/// A registered hook is simulated by its handler whatever its address bits say, which matters for
/// pool managers that do not encode hook permissions in the address.
pub fn has_native_hook_handler(chain: Chain, hook: &Address) -> bool {
    HANDLER_FACTORY
        .read()
        .is_ok_and(|factory| factory.contains_key(&(chain, *hook)))
}

/// Builds the [`HookHandler`] for `hook_address` on `chain`.
///
/// The native handler registered for the pair wins. With none registered, the generic VM handler
/// serves the chains in [`GENERIC_VM_HOOK_CHAINS`]; on every other chain the hook is unsupported
/// and this returns [`InvalidSnapshotError::ValueError`], so the pool fails to decode rather than
/// being quoted as if it had no hook.
pub fn instantiate_hook_handler(
    chain: Chain,
    hook_address: &Address,
    params: HookCreationParams<'_>,
) -> Result<Box<dyn HookHandler>, InvalidSnapshotError> {
    let factory = HANDLER_FACTORY
        .read()
        .map_err(|e| InvalidSnapshotError::VMError(SimulationError::FatalError(e.to_string())))?;
    if let Some(creator) = factory.get(&(chain, *hook_address)) {
        return creator.instantiate_hook_handler(params);
    }
    if GENERIC_VM_HOOK_CHAINS.contains(&chain) {
        return DEFAULT_HANDLER.instantiate_hook_handler(params);
    }
    Err(InvalidSnapshotError::ValueError(format!(
        "unsupported uniswap v4 hook {hook_address} on {chain}: no native handler registered and \
         the generic VM hook handler is not enabled on this chain"
    )))
}

#[cfg(test)]
mod tests {
    use alloy::primitives::address;
    use rstest::rstest;

    use super::*;
    use crate::evm::protocol::uniswap_v4::state::UniswapV4Fees;

    /// Owns the collections a [`HookCreationParams`] borrows, so a test can build params for an
    /// arbitrary hook address with no attributes set. Every creator then fails on the first
    /// attribute it needs, which identifies the creator that ran.
    #[derive(Default)]
    struct BareSnapshot {
        account_balances: HashMap<Bytes, HashMap<Bytes, Bytes>>,
        all_tokens: HashMap<Bytes, Token>,
        attributes: HashMap<String, Bytes>,
        balances: HashMap<Bytes, Bytes>,
    }

    impl BareSnapshot {
        fn params(&self, hook: Address) -> HookCreationParams<'_> {
            let state = UniswapV4State::new(
                0,
                U256::from(1),
                UniswapV4Fees::new(0, 0, 0),
                0,
                1,
                Vec::new(),
            )
            .expect("bare pool state should build");
            HookCreationParams::new(
                hook,
                &self.account_balances,
                &self.all_tokens,
                state,
                &self.attributes,
                &self.balances,
                None,
            )
        }
    }

    /// A creator whose only job is to be recognisable in the error it returns.
    struct TestHookCreator;

    impl HookHandlerCreator for TestHookCreator {
        fn instantiate_hook_handler(
            &self,
            _params: HookCreationParams<'_>,
        ) -> Result<Box<dyn HookHandler>, InvalidSnapshotError> {
            Err(InvalidSnapshotError::ValueError("test creator".to_string()))
        }
    }

    fn angstrom_hook() -> Address {
        Address::from_str(ANGSTROM_HOOK_ADDRESS).expect("angstrom hook address should parse")
    }

    /// Instantiates `hook` on `chain` from a bare snapshot and returns the error every creator
    /// raises for want of attributes.
    fn instantiation_error(chain: Chain, hook: Address) -> InvalidSnapshotError {
        let snapshot = BareSnapshot::default();
        let Err(error) = instantiate_hook_handler(chain, &hook, snapshot.params(hook)) else {
            panic!("a bare snapshot carries no attributes, so no creator can succeed");
        };
        error
    }

    #[rstest]
    #[case::robinhood(Chain::Robinhood, "robinhood")]
    #[case::base(Chain::Base, "base")]
    fn unregistered_hook_is_rejected_off_the_generic_vm_chains(
        #[case] chain: Chain,
        #[case] chain_name: &str,
    ) {
        initialize_hook_handlers().expect("hook handler registration should succeed");
        let hook = address!("00000000000000000000000000000000000000c4");

        let error = instantiation_error(chain, hook);

        let InvalidSnapshotError::ValueError(message) = error else {
            panic!("expected the unsupported-hook error, got {error:?}");
        };
        assert!(message.contains("unsupported uniswap v4 hook"), "{message}");
        assert!(message.contains(chain_name), "{message}");
    }

    #[rstest]
    #[case::ethereum(Chain::Ethereum)]
    #[case::unichain(Chain::Unichain)]
    fn unregistered_hook_falls_back_to_the_generic_vm_handler(#[case] chain: Chain) {
        initialize_hook_handlers().expect("hook handler registration should succeed");
        let hook = address!("00000000000000000000000000000000000000c5");

        let error = instantiation_error(chain, hook);

        let InvalidSnapshotError::MissingAttribute(attribute) = error else {
            panic!("expected the generic VM creator to run, got {error:?}");
        };
        assert_eq!(attribute, "balance_owner");
    }

    #[test]
    fn angstrom_hook_uses_its_native_creator_on_ethereum() {
        initialize_hook_handlers().expect("hook handler registration should succeed");

        let error = instantiation_error(Chain::Ethereum, angstrom_hook());

        let InvalidSnapshotError::MissingAttribute(attribute) = error else {
            panic!("expected the Angstrom creator to run, got {error:?}");
        };
        assert_eq!(attribute, "hooks");
    }

    #[test]
    fn angstrom_hook_falls_back_to_the_generic_vm_handler_off_ethereum() {
        // Angstrom's attributes are only produced by the Ethereum manifest, so the creator is
        // registered for Ethereum alone and the same address elsewhere is just another hook.
        initialize_hook_handlers().expect("hook handler registration should succeed");

        let error = instantiation_error(Chain::Unichain, angstrom_hook());

        let InvalidSnapshotError::MissingAttribute(attribute) = error else {
            panic!("expected the generic VM creator to run, got {error:?}");
        };
        assert_eq!(attribute, "balance_owner");
    }

    #[test]
    fn a_registered_creator_serves_only_the_chain_it_was_registered_for() {
        initialize_hook_handlers().expect("hook handler registration should succeed");
        let hook = address!("00000000000000000000000000000000000000c6");
        register_hook_handler(Chain::Robinhood, hook, Box::new(TestHookCreator))
            .expect("registering a hook handler should succeed");

        let registered = instantiation_error(Chain::Robinhood, hook);
        let InvalidSnapshotError::ValueError(message) = registered else {
            panic!("expected the registered creator to run, got {registered:?}");
        };
        assert_eq!(message, "test creator");

        let elsewhere = instantiation_error(Chain::Ethereum, hook);
        let InvalidSnapshotError::MissingAttribute(attribute) = elsewhere else {
            panic!("expected the generic VM creator to run, got {elsewhere:?}");
        };
        assert_eq!(attribute, "balance_owner");
    }
}