Skip to main content

nautilus_blockchain/exchanges/parsing/uniswap_v4/
initialize.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use alloy::{dyn_abi::SolType, primitives::Address, sol};
17use nautilus_core::hex;
18use nautilus_model::defi::{PoolIdentifier, rpc::RpcLog};
19use ustr::Ustr;
20
21use crate::{
22    events::pool_created::PoolCreatedEvent,
23    hypersync::{
24        HypersyncLog,
25        log::{extract_block_number, validate_event_signature_hash},
26    },
27    rpc::log as rpc_log,
28};
29
30const INITIALIZE_EVENT_SIGNATURE_HASH: &str =
31    "dd466e674ea557f56295e2d0218a125ea4b4f0f6f3307b95f85e6110838d6438";
32
33// Define sol macro for parsing Initialize event data
34// Topics contain: [signature, poolId, currency0, currency1]
35// Data contains 5 parameters: fee, tickSpacing, hooks, sqrtPriceX96, tick
36sol! {
37    struct InitializeEventData {
38        uint24 fee;
39        int24 tick_spacing;
40        address hooks;
41        uint160 sqrtPriceX96;
42        int24 tick;
43    }
44}
45
46/// Parses a UniswapV4 Initialize event from a HyperSync log.
47///
48/// UniswapV4 uses the Initialize event for pool discovery (no separate PoolCreated event).
49/// The PoolManager is a singleton contract that manages all V4 pools.
50///
51/// Initialize event signature:
52/// ```solidity
53/// event Initialize(
54///     PoolId indexed id,          // bytes32 (topic1)
55///     Currency indexed currency0, // address (topic2)
56///     Currency indexed currency1, // address (topic3)
57///     uint24 fee,                // (data)
58///     int24 tickSpacing,         // (data)
59///     IHooks hooks,              // address (data)
60///     uint160 sqrtPriceX96,      // (data)
61///     int24 tick                 // (data)
62/// );
63/// ```
64///
65/// # Errors
66///
67/// Returns an error if the log parsing fails or if the event data is invalid.
68///
69/// # Panics
70///
71/// Panics if the log address is not set.
72pub fn parse_initialize_event_hypersync(log: HypersyncLog) -> anyhow::Result<PoolCreatedEvent> {
73    validate_event_signature_hash("InitializeEvent", INITIALIZE_EVENT_SIGNATURE_HASH, &log)?;
74
75    let block_number = extract_block_number(&log)?;
76
77    // The pool address for V4 is the PoolManager contract address (the event emitter)
78    let pool_manager_address = Address::from_slice(
79        log.address
80            .clone()
81            .expect("PoolManager address should be set in logs")
82            .as_ref(),
83    );
84
85    // Extract currency0 and currency1 from topics
86    // topics[0] = event signature
87    // topics[1] = poolId (bytes32)
88    // topics[2] = currency0 (indexed)
89    // topics[3] = currency1 (indexed)
90    let topics = &log.topics;
91    if topics.len() < 4 {
92        anyhow::bail!(
93            "Initialize event missing topics: expected 4, was {}",
94            topics.len()
95        );
96    }
97
98    // Extract Pool ID from topics[1] - this is the unique identifier for V4 pools
99    let pool_id_bytes = topics[1]
100        .as_ref()
101        .ok_or_else(|| anyhow::anyhow!("Missing poolId topic"))?
102        .as_ref();
103    let pool_identifier = Ustr::from(&hex::encode_prefixed(pool_id_bytes));
104
105    let currency0 = Address::from_slice(
106        topics[2]
107            .as_ref()
108            .ok_or_else(|| anyhow::anyhow!("Missing currency0 topic"))?
109            .as_ref()
110            .get(12..32)
111            .ok_or_else(|| anyhow::anyhow!("Invalid currency0 topic length"))?,
112    );
113
114    let currency1 = Address::from_slice(
115        topics[3]
116            .as_ref()
117            .ok_or_else(|| anyhow::anyhow!("Missing currency1 topic"))?
118            .as_ref()
119            .get(12..32)
120            .ok_or_else(|| anyhow::anyhow!("Invalid currency1 topic length"))?,
121    );
122
123    if let Some(data) = log.data {
124        let data_bytes = data.as_ref();
125
126        // Validate minimum data length (5 fields × 32 bytes = 160 bytes)
127        if data_bytes.len() < 160 {
128            anyhow::bail!(
129                "Initialize event data too short: expected at least 160 bytes, was {}",
130                data_bytes.len()
131            );
132        }
133
134        let decoded = <InitializeEventData as SolType>::abi_decode(data_bytes)
135            .map_err(|e| anyhow::anyhow!("Failed to decode initialize event data: {e}"))?;
136
137        let mut event = PoolCreatedEvent::new(
138            block_number,
139            currency0,
140            currency1,
141            pool_manager_address, // V4 pools are managed by PoolManager
142            PoolIdentifier::PoolId(pool_identifier), // Pool ID (bytes32 as hex string)
143            Some(decoded.fee.to::<u32>()),
144            Some(i32::try_from(decoded.tick_spacing)? as u32),
145        );
146
147        event.set_initialize_params(decoded.sqrtPriceX96, i32::try_from(decoded.tick)?);
148        event.set_hooks(decoded.hooks);
149
150        Ok(event)
151    } else {
152        Err(anyhow::anyhow!("Missing data in initialize event log"))
153    }
154}
155
156/// Parses a UniswapV4 Initialize event from an RPC log.
157///
158/// # Errors
159///
160/// Returns an error if the log parsing fails or if the event data is invalid.
161pub fn parse_initialize_event_rpc(log: &RpcLog) -> anyhow::Result<PoolCreatedEvent> {
162    rpc_log::validate_event_signature(log, INITIALIZE_EVENT_SIGNATURE_HASH, "InitializeEvent")?;
163
164    let block_number = rpc_log::extract_block_number(log)?;
165
166    // Pool address is the PoolManager contract (event emitter)
167    let pool_manager_address = rpc_log::extract_address(log)?;
168
169    // Extract currency0 and currency1 from topics
170    // topics[0] = event signature
171    // topics[1] = poolId (bytes32)
172    // topics[2] = currency0 (indexed)
173    // topics[3] = currency1 (indexed)
174    if log.topics.len() < 4 {
175        anyhow::bail!(
176            "Initialize event missing topics: expected 4, was {}",
177            log.topics.len()
178        );
179    }
180
181    // Extract Pool ID from topics[1] - this is the unique identifier for V4 pools
182    let pool_id_bytes = rpc_log::extract_topic_bytes(log, 1)?;
183    let pool_identifier = Ustr::from(&hex::encode_prefixed(pool_id_bytes));
184
185    let currency0 = rpc_log::extract_address_from_topic(log, 2, "currency0")?;
186    let currency1 = rpc_log::extract_address_from_topic(log, 3, "currency1")?;
187
188    // Extract and decode event data
189    let data_bytes = rpc_log::extract_data_bytes(log)?;
190
191    // Validate minimum data length (5 fields × 32 bytes = 160 bytes)
192    if data_bytes.len() < 160 {
193        anyhow::bail!(
194            "Initialize event data too short: expected at least 160 bytes, was {}",
195            data_bytes.len()
196        );
197    }
198
199    let decoded = <InitializeEventData as SolType>::abi_decode(&data_bytes)
200        .map_err(|e| anyhow::anyhow!("Failed to decode initialize event data: {e}"))?;
201
202    let mut event = PoolCreatedEvent::new(
203        block_number,
204        currency0,
205        currency1,
206        pool_manager_address,
207        PoolIdentifier::PoolId(pool_identifier), // Pool ID (bytes32 as hex string)
208        Some(decoded.fee.to::<u32>()),
209        Some(i32::try_from(decoded.tick_spacing)? as u32),
210    );
211
212    event.set_initialize_params(decoded.sqrtPriceX96, i32::try_from(decoded.tick)?);
213    event.set_hooks(decoded.hooks);
214
215    Ok(event)
216}
217
218#[cfg(test)]
219mod tests {
220    use rstest::{fixture, rstest};
221    use serde_json::json;
222
223    use super::*;
224
225    // Real UniswapV4 Initialize event from Arbitrum
226    // Pool Manager: 0x360E68faCcca8cA495c1B759Fd9EEe466db9FB32
227    // WETH-USDC pool
228    // Block: 0x11c44853 (297879635)
229    // Tx: 0xdb973062b20333d61a57f4dc14b33c044e044a97c7d3db2900acc61e04179738
230
231    #[fixture]
232    fn hypersync_log_weth_usdc() -> HypersyncLog {
233        let log_json = json!({
234            "removed": null,
235            "log_index": "0x1",
236            "transaction_index": "0x3",
237            "transaction_hash": "0xdb973062b20333d61a57f4dc14b33c044e044a97c7d3db2900acc61e04179738",
238            "block_hash": null,
239            "block_number": "0x11c44853",
240            "address": "0x360e68faccca8ca495c1b759fd9eee466db9fb32",
241            "data": "0x0000000000000000000000000000000000000000000000000000000000000bb8000000000000000000000000000000000000000000000000000000000000003c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e08ab0dd488513a6f62efffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd0765",
242            "topics": [
243                "0xdd466e674ea557f56295e2d0218a125ea4b4f0f6f3307b95f85e6110838d6438",
244                "0xc9bc8043294146424a4e4607d8ad837d6a659142822bbaaabc83bb57e7447461",
245                "0x00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1",
246                "0x000000000000000000000000af88d065e77c8cc2239327c5edb3a432268e5831"
247            ]
248        });
249        serde_json::from_value(log_json).expect("Failed to deserialize HyperSync log")
250    }
251
252    #[fixture]
253    fn rpc_log_weth_usdc() -> RpcLog {
254        let log_json = json!({
255            "removed": false,
256            "logIndex": "0x1",
257            "transactionIndex": "0x3",
258            "transactionHash": "0xdb973062b20333d61a57f4dc14b33c044e044a97c7d3db2900acc61e04179738",
259            "blockHash": "0x4f72d534028d2322fa2dcaa3f470467a264eda2e20f73eeb1ece370361bb0ee7",
260            "blockNumber": "0x11c44853",
261            "address": "0x360e68faccca8ca495c1b759fd9eee466db9fb32",
262            "data": "0x0000000000000000000000000000000000000000000000000000000000000bb8000000000000000000000000000000000000000000000000000000000000003c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e08ab0dd488513a6f62efffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd0765",
263            "topics": [
264                "0xdd466e674ea557f56295e2d0218a125ea4b4f0f6f3307b95f85e6110838d6438",
265                "0xc9bc8043294146424a4e4607d8ad837d6a659142822bbaaabc83bb57e7447461",
266                "0x00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1",
267                "0x000000000000000000000000af88d065e77c8cc2239327c5edb3a432268e5831"
268            ]
269        });
270        serde_json::from_value(log_json).expect("Failed to deserialize RPC log")
271    }
272
273    #[rstest]
274    fn test_parse_initialize_hypersync(hypersync_log_weth_usdc: HypersyncLog) {
275        let event =
276            parse_initialize_event_hypersync(hypersync_log_weth_usdc).expect("Failed to parse");
277
278        assert_eq!(event.block_number, 298076243);
279        assert_eq!(
280            event.token0.to_string().to_lowercase(),
281            "0x82af49447d8a07e3bd95bd0d56f35241523fbab1"
282        );
283        assert_eq!(
284            event.token1.to_string().to_lowercase(),
285            "0xaf88d065e77c8cc2239327c5edb3a432268e5831"
286        );
287        assert_eq!(
288            event.pool_identifier.to_string(),
289            "0xc9bc8043294146424a4e4607d8ad837d6a659142822bbaaabc83bb57e7447461"
290        );
291        assert_eq!(event.fee, Some(3000));
292        assert_eq!(event.tick_spacing, Some(60));
293    }
294
295    #[rstest]
296    fn test_parse_initialize_rpc(rpc_log_weth_usdc: RpcLog) {
297        let event = parse_initialize_event_rpc(&rpc_log_weth_usdc).expect("Failed to parse");
298
299        assert_eq!(event.block_number, 298076243);
300        assert_eq!(
301            event.token0.to_string().to_lowercase(),
302            "0x82af49447d8a07e3bd95bd0d56f35241523fbab1"
303        );
304        assert_eq!(
305            event.token1.to_string().to_lowercase(),
306            "0xaf88d065e77c8cc2239327c5edb3a432268e5831"
307        );
308        assert_eq!(
309            event.pool_identifier.to_string(),
310            "0xc9bc8043294146424a4e4607d8ad837d6a659142822bbaaabc83bb57e7447461"
311        );
312        assert_eq!(event.fee, Some(3000));
313        assert_eq!(event.tick_spacing, Some(60));
314    }
315
316    #[rstest]
317    #[case(2, 31)]
318    #[case(3, 31)]
319    #[case(2, 33)]
320    #[case(3, 33)]
321    fn test_parse_initialize_rpc_rejects_noncanonical_currency_topic(
322        mut rpc_log_weth_usdc: RpcLog,
323        #[case] topic_index: usize,
324        #[case] byte_len: usize,
325    ) {
326        let valid_log = rpc_log_weth_usdc.clone();
327        rpc_log_weth_usdc.topics[topic_index] = format!("0x{}", "11".repeat(byte_len));
328
329        let error = parse_initialize_event_rpc(&rpc_log_weth_usdc).unwrap_err();
330        let event = parse_initialize_event_rpc(&valid_log).unwrap();
331
332        assert_eq!(
333            error.to_string(),
334            format!("Topic must be 32 bytes, was {byte_len}")
335        );
336        assert_eq!(event.block_number, 298076243);
337    }
338
339    #[rstest]
340    fn test_parse_initialize_rpc_rejects_short_pool_manager_address(mut rpc_log_weth_usdc: RpcLog) {
341        let valid_log = rpc_log_weth_usdc.clone();
342        rpc_log_weth_usdc.address = "0x360e68faccca8ca495c1b759fd9eee466db9fb".to_string();
343
344        let error = parse_initialize_event_rpc(&rpc_log_weth_usdc).unwrap_err();
345        let event = parse_initialize_event_rpc(&valid_log).unwrap();
346
347        assert_eq!(
348            error.to_string(),
349            "Invalid contract address length: expected 20 bytes, was 19"
350        );
351        assert_eq!(event.block_number, 298076243);
352    }
353
354    #[rstest]
355    fn test_hypersync_rpc_match(hypersync_log_weth_usdc: HypersyncLog, rpc_log_weth_usdc: RpcLog) {
356        let hypersync_event =
357            parse_initialize_event_hypersync(hypersync_log_weth_usdc).expect("HyperSync parse");
358        let rpc_event = parse_initialize_event_rpc(&rpc_log_weth_usdc).expect("RPC parse");
359
360        assert_eq!(hypersync_event.block_number, rpc_event.block_number);
361        assert_eq!(hypersync_event.token0, rpc_event.token0);
362        assert_eq!(hypersync_event.token1, rpc_event.token1);
363        assert_eq!(hypersync_event.pool_identifier, rpc_event.pool_identifier);
364        assert_eq!(hypersync_event.fee, rpc_event.fee);
365        assert_eq!(hypersync_event.tick_spacing, rpc_event.tick_spacing);
366    }
367}