Skip to main content

nautilus_blockchain/rpc/
log.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//! Parses Ethereum JSON-RPC log entries.
17//!
18//! Converts `RpcLog` fields and hex strings to their domain types.
19
20use std::str::FromStr;
21
22use alloy::primitives::{Address, B256};
23use nautilus_core::hex;
24use nautilus_model::defi::rpc::RpcLog;
25
26/// Decode hex string (with or without 0x prefix) to bytes.
27///
28/// # Errors
29///
30/// Returns an error if the hex string is invalid.
31pub fn decode_hex(hex: &str) -> anyhow::Result<Vec<u8>> {
32    hex::decode(hex.trim_start_matches("0x")).map_err(|e| anyhow::anyhow!("Invalid hex: {e}"))
33}
34
35/// Parse hex string to u64.
36///
37/// # Errors
38///
39/// Returns an error if the hex string cannot be parsed as u64.
40pub fn parse_hex_u64(hex: &str) -> anyhow::Result<u64> {
41    u64::from_str_radix(hex.trim_start_matches("0x"), 16)
42        .map_err(|e| anyhow::anyhow!("Invalid hex u64: {e}"))
43}
44
45/// Parse hex string to u32.
46///
47/// # Errors
48///
49/// Returns an error if the hex string cannot be parsed as u32.
50pub fn parse_hex_u32(hex: &str) -> anyhow::Result<u32> {
51    u32::from_str_radix(hex.trim_start_matches("0x"), 16)
52        .map_err(|e| anyhow::anyhow!("Invalid hex u32: {e}"))
53}
54
55/// Extract block number from RPC log.
56///
57/// # Errors
58///
59/// Returns an error if the block number is missing or cannot be parsed.
60pub fn extract_block_number(log: &RpcLog) -> anyhow::Result<u64> {
61    let hex = log
62        .block_number
63        .as_ref()
64        .ok_or_else(|| anyhow::anyhow!("Missing block number"))?;
65    parse_hex_u64(hex)
66}
67
68/// Extracts the block hash from an RPC log.
69///
70/// Returns `None` for pending logs, which carry no block hash.
71///
72/// # Errors
73///
74/// Returns an error if the reported block hash is not valid 32-byte hex.
75pub fn extract_block_hash(log: &RpcLog) -> anyhow::Result<Option<B256>> {
76    log.block_hash
77        .as_deref()
78        .map(|hash| {
79            B256::from_str(hash).map_err(|e| anyhow::anyhow!("Invalid block hash {hash}: {e}"))
80        })
81        .transpose()
82}
83
84/// Extract transaction hash from RPC log.
85///
86/// # Errors
87///
88/// Returns an error if the transaction hash is missing.
89pub fn extract_transaction_hash(log: &RpcLog) -> anyhow::Result<String> {
90    log.transaction_hash
91        .clone()
92        .ok_or_else(|| anyhow::anyhow!("Missing transaction hash"))
93}
94
95/// Extract transaction index from RPC log.
96///
97/// # Errors
98///
99/// Returns an error if the transaction index is missing or cannot be parsed.
100pub fn extract_transaction_index(log: &RpcLog) -> anyhow::Result<u32> {
101    let hex = log
102        .transaction_index
103        .as_ref()
104        .ok_or_else(|| anyhow::anyhow!("Missing transaction index"))?;
105    parse_hex_u32(hex)
106}
107
108/// Extract log index from RPC log.
109///
110/// # Errors
111///
112/// Returns an error if the log index is missing or cannot be parsed.
113pub fn extract_log_index(log: &RpcLog) -> anyhow::Result<u32> {
114    let hex = log
115        .log_index
116        .as_ref()
117        .ok_or_else(|| anyhow::anyhow!("Missing log index"))?;
118    parse_hex_u32(hex)
119}
120
121/// Extract contract address from RPC log.
122///
123/// # Errors
124///
125/// Returns an error if the address is invalid.
126pub fn extract_address(log: &RpcLog) -> anyhow::Result<Address> {
127    let bytes = decode_hex(&log.address)?;
128    anyhow::ensure!(
129        bytes.len() == Address::len_bytes(),
130        "Invalid contract address length: expected {} bytes, was {}",
131        Address::len_bytes(),
132        bytes.len()
133    );
134    Ok(Address::from_slice(&bytes))
135}
136
137/// Extract topic bytes at index.
138///
139/// # Errors
140///
141/// Returns an error if the topic at the specified index is missing.
142pub fn extract_topic_bytes(log: &RpcLog, index: usize) -> anyhow::Result<Vec<u8>> {
143    let hex = log
144        .topics
145        .get(index)
146        .ok_or_else(|| anyhow::anyhow!("Missing topic at index {index}"))?;
147    decode_hex(hex)
148}
149
150/// Extract address from topic at index.
151///
152/// In Ethereum event logs, indexed address parameters are stored as 32-byte
153/// values with the 20-byte address right-aligned (padded with zeros on the left).
154///
155/// # Errors
156///
157/// Returns an error if the topic is missing or the address extraction fails.
158pub fn extract_address_from_topic(
159    log: &RpcLog,
160    index: usize,
161    description: &str,
162) -> anyhow::Result<Address> {
163    let bytes = extract_topic_bytes(log, index)
164        .map_err(|_| anyhow::anyhow!("Missing {description} address in topic{index}"))?;
165    anyhow::ensure!(
166        bytes.len() == 32,
167        "Topic must be 32 bytes, was {}",
168        bytes.len()
169    );
170    Ok(Address::from_slice(&bytes[12..32]))
171}
172
173/// Extract data bytes from RPC log.
174///
175/// # Errors
176///
177/// Returns an error if the hex decoding fails.
178pub fn extract_data_bytes(log: &RpcLog) -> anyhow::Result<Vec<u8>> {
179    decode_hex(&log.data)
180}
181
182/// Validate event signature from topic0.
183///
184/// The first topic (topic0) of an Ethereum event log contains the keccak256 hash
185/// of the event signature. This function validates that the actual signature
186/// matches the expected one.
187///
188/// # Errors
189///
190/// Returns an error if the signature doesn't match or topic0 is missing.
191pub fn validate_event_signature(
192    log: &RpcLog,
193    expected_hash: &str,
194    event_name: &str,
195) -> anyhow::Result<()> {
196    let sig_bytes = extract_topic_bytes(log, 0)?;
197    let actual_hex = hex::encode(&sig_bytes);
198    anyhow::ensure!(
199        actual_hex == expected_hash,
200        "Invalid event signature for '{event_name}': expected {expected_hash}, was {actual_hex}",
201    );
202    Ok(())
203}
204
205#[cfg(test)]
206mod tests {
207    use rstest::{fixture, rstest};
208
209    use super::*;
210
211    /// Real RPC log from Arbitrum PoolCreated event at block 185
212    /// Pool: 0xB9Fc136980D98C034a529AadbD5651c087365D5f
213    /// token0: 0x2E5353426C89F4eCD52D1036DA822D47E73376C4
214    /// token1: 0x838930cFE7502dd36B0b1ebbef8001fbF94f3bFb
215    /// fee: 3000, tickSpacing: 60
216    #[fixture]
217    fn log() -> RpcLog {
218        RpcLog {
219            removed: false,
220            log_index: Some("0x0".to_string()),
221            transaction_index: Some("0x0".to_string()),
222            transaction_hash: Some(
223                "0x24058dde7caf5b8b70041de8b27731f20f927365f210247c3e720e947b9098e7".to_string(),
224            ),
225            block_hash: Some(
226                "0xd371b6c7b04ec33d6470f067a82e87d7b294b952bea7a46d7b939b4c7addc275".to_string(),
227            ),
228            block_number: Some("0xb9".to_string()),
229            address: "0x1f98431c8ad98523631ae4a59f267346ea31f984".to_string(),
230            data: "0x000000000000000000000000000000000000000000000000000000000000003c000000000000000000000000b9fc136980d98c034a529aadbd5651c087365d5f".to_string(),
231            topics: vec![
232                "0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118".to_string(),
233                "0x0000000000000000000000002e5353426c89f4ecd52d1036da822d47e73376c4".to_string(),
234                "0x000000000000000000000000838930cfe7502dd36b0b1ebbef8001fbf94f3bfb".to_string(),
235                "0x0000000000000000000000000000000000000000000000000000000000000bb8".to_string(),
236            ],
237        }
238    }
239
240    #[rstest]
241    fn test_decode_hex_with_prefix() {
242        let result = decode_hex("0x1234").unwrap();
243        assert_eq!(result, vec![0x12, 0x34]);
244    }
245
246    #[rstest]
247    fn test_decode_hex_without_prefix() {
248        let result = decode_hex("1234").unwrap();
249        assert_eq!(result, vec![0x12, 0x34]);
250    }
251
252    #[rstest]
253    fn test_parse_hex_u64_block_185() {
254        // Block 185 = 0xb9
255        assert_eq!(parse_hex_u64("0xb9").unwrap(), 185);
256        assert_eq!(parse_hex_u64("b9").unwrap(), 185);
257    }
258
259    #[rstest]
260    fn test_parse_hex_u32() {
261        assert_eq!(parse_hex_u32("0x0").unwrap(), 0);
262        assert_eq!(parse_hex_u32("0xbb8").unwrap(), 3000); // fee from block 185
263    }
264
265    #[rstest]
266    fn test_extract_block_number(log: RpcLog) {
267        assert_eq!(extract_block_number(&log).unwrap(), 185);
268    }
269
270    #[rstest]
271    fn test_extract_block_hash(log: RpcLog) {
272        let expected =
273            B256::from_str("0xd371b6c7b04ec33d6470f067a82e87d7b294b952bea7a46d7b939b4c7addc275")
274                .unwrap();
275        assert_eq!(extract_block_hash(&log).unwrap(), Some(expected));
276    }
277
278    #[rstest]
279    fn test_extract_block_hash_pending_log_returns_none(mut log: RpcLog) {
280        log.block_hash = None;
281
282        assert_eq!(extract_block_hash(&log).unwrap(), None);
283    }
284
285    #[rstest]
286    fn test_extract_block_hash_invalid_returns_error(mut log: RpcLog) {
287        log.block_hash = Some("0xnotahash".to_string());
288
289        assert!(extract_block_hash(&log).is_err());
290    }
291
292    #[rstest]
293    fn test_extract_transaction_hash(log: RpcLog) {
294        assert_eq!(
295            extract_transaction_hash(&log).unwrap(),
296            "0x24058dde7caf5b8b70041de8b27731f20f927365f210247c3e720e947b9098e7"
297        );
298    }
299
300    #[rstest]
301    fn test_extract_transaction_index(log: RpcLog) {
302        assert_eq!(extract_transaction_index(&log).unwrap(), 0);
303    }
304
305    #[rstest]
306    fn test_extract_log_index(log: RpcLog) {
307        assert_eq!(extract_log_index(&log).unwrap(), 0);
308    }
309
310    #[rstest]
311    fn test_extract_address(log: RpcLog) {
312        let address = extract_address(&log).unwrap();
313        // Uniswap V3 Factory address on Arbitrum
314        assert_eq!(
315            address.to_string().to_lowercase(),
316            "0x1f98431c8ad98523631ae4a59f267346ea31f984"
317        );
318    }
319
320    #[rstest]
321    #[case("0x", 0)]
322    #[case("0x00112233445566778899aabbccddeeff001122", 19)]
323    #[case("0x00112233445566778899aabbccddeeff0011223344", 21)]
324    fn test_extract_address_rejects_wrong_length(
325        mut log: RpcLog,
326        #[case] address: &str,
327        #[case] actual: usize,
328    ) {
329        log.address = address.to_string();
330
331        let error = extract_address(&log).unwrap_err();
332
333        assert_eq!(
334            error.to_string(),
335            format!("Invalid contract address length: expected 20 bytes, was {actual}")
336        );
337    }
338
339    #[rstest]
340    fn test_extract_address_from_topic_token0(log: RpcLog) {
341        let address = extract_address_from_topic(&log, 1, "token0").unwrap();
342        assert_eq!(
343            address.to_string().to_lowercase(),
344            "0x2e5353426c89f4ecd52d1036da822d47e73376c4"
345        );
346    }
347
348    #[rstest]
349    fn test_extract_address_from_topic_token1(log: RpcLog) {
350        let address = extract_address_from_topic(&log, 2, "token1").unwrap();
351        assert_eq!(
352            address.to_string().to_lowercase(),
353            "0x838930cfe7502dd36b0b1ebbef8001fbf94f3bfb"
354        );
355    }
356
357    #[rstest]
358    #[case(31)]
359    #[case(33)]
360    fn test_extract_address_from_topic_rejects_noncanonical_width(
361        mut log: RpcLog,
362        #[case] byte_len: usize,
363    ) {
364        let valid_log = log.clone();
365        log.topics[1] = format!("0x{}", "11".repeat(byte_len));
366
367        let error = extract_address_from_topic(&log, 1, "token0").unwrap_err();
368        let address = extract_address_from_topic(&valid_log, 1, "token0").unwrap();
369
370        assert_eq!(
371            error.to_string(),
372            format!("Topic must be 32 bytes, was {byte_len}")
373        );
374        assert_eq!(
375            address.to_string().to_lowercase(),
376            "0x2e5353426c89f4ecd52d1036da822d47e73376c4"
377        );
378    }
379
380    #[rstest]
381    fn test_extract_data_bytes(log: RpcLog) {
382        let data = extract_data_bytes(&log).unwrap();
383        // Data contains tickSpacing (60 = 0x3c) and pool address
384        assert_eq!(data.len(), 64); // 2 x 32 bytes
385        // First 32 bytes: tickSpacing = 60 (0x3c)
386        assert_eq!(data[31], 0x3c);
387    }
388
389    #[rstest]
390    fn test_validate_event_signature_pool_created(log: RpcLog) {
391        let expected = "783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118";
392        assert!(validate_event_signature(&log, expected, "PoolCreated").is_ok());
393    }
394
395    #[rstest]
396    fn test_validate_event_signature_mismatch(log: RpcLog) {
397        // Swap event signature instead of PoolCreated
398        let wrong = "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67";
399        let result = validate_event_signature(&log, wrong, "Swap");
400        assert!(result.is_err());
401        assert!(
402            result
403                .unwrap_err()
404                .to_string()
405                .contains("Invalid event signature")
406        );
407    }
408}