Skip to main content

nautilus_blockchain/exchanges/parsing/
core.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
16//! Shared core extraction functions for parsing event logs.
17//!
18//! These functions operate on raw bytes and are used by both HyperSync and RPC parsers
19//! to ensure consistent extraction logic.
20
21use alloy::primitives::Address;
22use nautilus_core::hex;
23
24/// Extract address from 32-byte topic (address in last 20 bytes).
25///
26/// In Ethereum event logs, indexed address parameters are stored as 32-byte
27/// values with the 20-byte address right-aligned (padded with zeros on the left).
28///
29/// # Errors
30///
31/// Returns an error if the byte slice is not exactly 32 bytes.
32pub fn extract_address_from_bytes(bytes: &[u8]) -> anyhow::Result<Address> {
33    require_topic_width(bytes)?;
34    Ok(Address::from_slice(&bytes[12..32]))
35}
36
37/// Extract u32 from 32-byte topic (value in last 4 bytes, big-endian).
38///
39/// In Ethereum event logs, indexed numeric parameters are stored as 32-byte
40/// values with the number right-aligned in big-endian format.
41///
42/// # Errors
43///
44/// Returns an error if the byte slice is not exactly 32 bytes.
45pub fn extract_u32_from_bytes(bytes: &[u8]) -> anyhow::Result<u32> {
46    require_topic_width(bytes)?;
47    Ok(u32::from_be_bytes(bytes[28..32].try_into()?))
48}
49
50/// Extract i32 from 32-byte topic (value in last 4 bytes, big-endian, signed).
51///
52/// In Ethereum event logs, indexed signed numeric parameters (like tick values)
53/// are stored as 32-byte values with the number right-aligned in big-endian format.
54///
55/// # Errors
56///
57/// Returns an error if the byte slice is not exactly 32 bytes.
58pub fn extract_i32_from_bytes(bytes: &[u8]) -> anyhow::Result<i32> {
59    require_topic_width(bytes)?;
60    Ok(i32::from_be_bytes(bytes[28..32].try_into()?))
61}
62
63fn require_topic_width(bytes: &[u8]) -> anyhow::Result<()> {
64    anyhow::ensure!(
65        bytes.len() == 32,
66        "Topic must be 32 bytes, was {}",
67        bytes.len()
68    );
69    Ok(())
70}
71
72/// Validate event signature matches expected hash.
73///
74/// The first topic (topic0) of an Ethereum event log contains the keccak256 hash
75/// of the event signature. This function validates that the actual signature
76/// matches the expected one.
77///
78/// # Errors
79///
80/// Returns an error if the signatures don't match.
81pub fn validate_signature_bytes(
82    actual: &[u8],
83    expected_hex: &str,
84    event_name: &str,
85) -> anyhow::Result<()> {
86    let actual_hex = hex::encode(actual);
87    anyhow::ensure!(
88        actual_hex == expected_hex,
89        "Invalid event signature for '{event_name}': expected {expected_hex}, was {actual_hex}",
90    );
91    Ok(())
92}
93
94#[cfg(test)]
95mod tests {
96    use rstest::rstest;
97
98    use super::*;
99
100    #[rstest]
101    fn test_extract_address_token0() {
102        // token0 address from PoolCreated event topic1 at block 185
103        let bytes = hex::decode("0000000000000000000000002e5353426c89f4ecd52d1036da822d47e73376c4")
104            .unwrap();
105
106        let address = extract_address_from_bytes(&bytes).unwrap();
107        assert_eq!(
108            address.to_string().to_lowercase(),
109            "0x2e5353426c89f4ecd52d1036da822d47e73376c4"
110        );
111    }
112
113    #[rstest]
114    fn test_extract_address_token1_block() {
115        // token1 address from PoolCreated event topic2 at block 185
116        let bytes = hex::decode("000000000000000000000000838930cfe7502dd36b0b1ebbef8001fbf94f3bfb")
117            .unwrap();
118
119        let address = extract_address_from_bytes(&bytes).unwrap();
120        assert_eq!(
121            address.to_string().to_lowercase(),
122            "0x838930cfe7502dd36b0b1ebbef8001fbf94f3bfb"
123        );
124    }
125
126    #[rstest]
127    #[case(31)]
128    #[case(33)]
129    fn test_extract_topic_rejects_noncanonical_width(#[case] byte_len: usize) {
130        let bytes = vec![0xffu8; byte_len];
131        let expected = format!("Topic must be 32 bytes, was {byte_len}");
132        let address_error = extract_address_from_bytes(&bytes).unwrap_err();
133        let fee_error = extract_u32_from_bytes(&bytes).unwrap_err();
134        let tick_error = extract_i32_from_bytes(&bytes).unwrap_err();
135
136        let address = extract_address_from_bytes(
137            &hex::decode("0000000000000000000000002e5353426c89f4ecd52d1036da822d47e73376c4")
138                .unwrap(),
139        )
140        .unwrap();
141        let fee = extract_u32_from_bytes(
142            &hex::decode("0000000000000000000000000000000000000000000000000000000000000bb8")
143                .unwrap(),
144        )
145        .unwrap();
146        let tick = extract_i32_from_bytes(
147            &hex::decode("000000000000000000000000000000000000000000000000000000000000003c")
148                .unwrap(),
149        )
150        .unwrap();
151
152        assert_eq!(address_error.to_string(), expected);
153        assert_eq!(fee_error.to_string(), expected);
154        assert_eq!(tick_error.to_string(), expected);
155        assert_eq!(
156            address.to_string().to_lowercase(),
157            "0x2e5353426c89f4ecd52d1036da822d47e73376c4"
158        );
159        assert_eq!(fee, 3000);
160        assert_eq!(tick, 60);
161    }
162
163    #[rstest]
164    fn test_extract_u32_fee_3000() {
165        let bytes = hex::decode("0000000000000000000000000000000000000000000000000000000000000bb8")
166            .unwrap();
167
168        let value = extract_u32_from_bytes(&bytes).unwrap();
169        assert_eq!(value, 3000);
170    }
171
172    #[rstest]
173    fn test_extract_u32_fee_500() {
174        let bytes = hex::decode("00000000000000000000000000000000000000000000000000000000000001f4")
175            .unwrap();
176
177        let value = extract_u32_from_bytes(&bytes).unwrap();
178        assert_eq!(value, 500);
179    }
180
181    #[rstest]
182    fn test_extract_i32_tick_spacing_60() {
183        let bytes = hex::decode("000000000000000000000000000000000000000000000000000000000000003c")
184            .unwrap();
185
186        let value = extract_i32_from_bytes(&bytes).unwrap();
187        assert_eq!(value, 60);
188    }
189
190    #[rstest]
191    fn test_extract_i32_tick_spacing_10() {
192        let bytes = hex::decode("000000000000000000000000000000000000000000000000000000000000000a")
193            .unwrap();
194
195        let value = extract_i32_from_bytes(&bytes).unwrap();
196        assert_eq!(value, 10);
197    }
198
199    #[rstest]
200    fn test_extract_i32_from_bytes_negative() {
201        let bytes = hex::decode("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc4")
202            .unwrap();
203
204        let value = extract_i32_from_bytes(&bytes).unwrap();
205        assert_eq!(value, -60);
206    }
207
208    #[rstest]
209    fn test_validate_signature_pool_created() {
210        let pool_created_signature =
211            hex::decode("783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118")
212                .unwrap();
213        let expected = "783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118";
214
215        let result = validate_signature_bytes(&pool_created_signature, expected, "PoolCreated");
216        assert!(result.is_ok());
217    }
218
219    #[rstest]
220    fn test_validate_signature_bytes_mismatch() {
221        let pool_created_signature =
222            hex::decode("783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118")
223                .unwrap();
224        let swap_expected = "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67";
225
226        let result = validate_signature_bytes(&pool_created_signature, swap_expected, "Swap");
227        assert!(result.is_err());
228        assert!(
229            result
230                .unwrap_err()
231                .to_string()
232                .contains("Invalid event signature for 'Swap'")
233        );
234    }
235}