Skip to main content

nautilus_blockchain/hypersync/
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
16use alloy::primitives::{Address, B256};
17use nautilus_core::hex;
18
19use super::HypersyncLog;
20use crate::exchanges::parsing::core;
21
22/// Extracts an address from a specific topic in a log entry
23///
24/// # Errors
25///
26/// Returns an error if the topic at the specified index is not present in the log.
27pub fn extract_address_from_topic(
28    log: &HypersyncLog,
29    topic_index: usize,
30    description: &str,
31) -> anyhow::Result<Address> {
32    match log.topics.get(topic_index).and_then(|t| t.as_ref()) {
33        Some(topic) => core::extract_address_from_bytes(topic.as_ref()),
34        None => {
35            anyhow::bail!("Missing {description} address in topic{topic_index} when parsing event")
36        }
37    }
38}
39
40/// Extracts the transaction hash from a log entry
41///
42/// # Errors
43///
44/// Returns an error if the transaction hash is not present in the log.
45pub fn extract_transaction_hash(log: &HypersyncLog) -> anyhow::Result<String> {
46    log.transaction_hash
47        .as_ref()
48        .map(ToString::to_string)
49        .ok_or_else(|| anyhow::anyhow!("Missing transaction hash in log"))
50}
51
52/// Extracts the transaction index from a log entry
53///
54/// # Errors
55///
56/// Returns an error if the transaction index is not present in the log.
57pub fn extract_transaction_index(log: &HypersyncLog) -> anyhow::Result<u32> {
58    log.transaction_index
59        .as_ref()
60        .map(|index| **index as u32)
61        .ok_or_else(|| anyhow::anyhow!("Missing transaction index in the log"))
62}
63
64/// Extracts the log index from a log entry
65///
66/// # Errors
67///
68/// Returns an error if the log index is not present in the log.
69pub fn extract_log_index(log: &HypersyncLog) -> anyhow::Result<u32> {
70    log.log_index
71        .as_ref()
72        .map(|index| **index as u32)
73        .ok_or_else(|| anyhow::anyhow!("Missing log index in the log"))
74}
75
76/// Extracts the block number from a log entry
77///
78/// # Errors
79///
80/// Returns an error if the block number is not present in the log.
81pub fn extract_block_number(log: &HypersyncLog) -> anyhow::Result<u64> {
82    log.block_number
83        .as_ref()
84        .map(|number| **number)
85        .ok_or_else(|| anyhow::anyhow!("Missing block number in the log"))
86}
87
88/// Extracts the block hash from a log entry.
89///
90/// Returns `None` when the query did not select the block hash field.
91pub fn extract_block_hash(log: &HypersyncLog) -> Option<B256> {
92    log.block_hash.as_ref().map(B256::from)
93}
94
95/// Extracts the event signature from a log entry and returns it as a hex string
96///
97/// # Errors
98///
99/// Returns an error if the event signature (topic0) is not present in the log.
100pub fn extract_event_signature(log: &HypersyncLog) -> anyhow::Result<String> {
101    extract_event_signature_bytes(log).map(hex::encode)
102}
103
104/// Extracts the event signature from a log entry and returns it as raw bytes
105///
106/// # Errors
107///
108/// Returns an error if the event signature (topic0) is not present in the log.
109pub fn extract_event_signature_bytes(log: &HypersyncLog) -> anyhow::Result<&[u8]> {
110    if let Some(topic) = log.topics.first().and_then(|t| t.as_ref()) {
111        Ok(topic.as_ref())
112    } else {
113        anyhow::bail!("Missing event signature in topic0");
114    }
115}
116
117/// Validates that a log entry corresponds to the expected event by comparing its topic0 with the provided event signature hash.
118///
119/// # Errors
120///
121/// Returns an error if the event signature doesn't match or if topic0 is missing.
122pub fn validate_event_signature_hash(
123    event_name: &str,
124    target_event_signature_hash: &str,
125    log: &HypersyncLog,
126) -> anyhow::Result<()> {
127    let sig_bytes = extract_event_signature_bytes(log)?;
128    core::validate_signature_bytes(sig_bytes, target_event_signature_hash, event_name)
129}
130
131#[cfg(test)]
132mod tests {
133    use std::str::FromStr;
134
135    use rstest::*;
136    use serde_json::json;
137
138    use super::*;
139
140    #[fixture]
141    fn swap_log_1() -> HypersyncLog {
142        let log_json = json!({
143            "removed": null,
144            "log_index": null,
145            "transaction_index": null,
146            "transaction_hash": null,
147            "block_hash": null,
148            "block_number": "0x1581b7e",
149            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
150            "data": "0x",
151            "topics": [
152                "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67",
153                "0x0000000000000000000000003fc91a3afd70395cd496c647d5a6cc9d4b2b7fad",
154                "0x0000000000000000000000003fc91a3afd70395cd496c647d5a6cc9d4b2b7fad",
155                null
156            ]
157        });
158        serde_json::from_value(log_json).expect("Failed to deserialize log")
159    }
160
161    #[fixture]
162    fn swap_log_2() -> HypersyncLog {
163        let log_json = json!({
164            "removed": null,
165            "log_index": null,
166            "transaction_index": null,
167            "transaction_hash": null,
168            "block_hash": null,
169            "block_number": "0x1581b82",
170            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
171            "data": "0x",
172            "topics": [
173                "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67",
174                "0x00000000000000000000000066a9893cc07d91d95644aedd05d03f95e1dba8af",
175                "0x000000000000000000000000f90321d0ecad58ab2b0c8c79db8aaeeefa023578",
176                null
177            ]
178        });
179        serde_json::from_value(log_json).expect("Failed to deserialize log")
180    }
181
182    #[fixture]
183    fn log_without_topics() -> HypersyncLog {
184        let log_json = json!({
185            "removed": null,
186            "log_index": null,
187            "transaction_index": null,
188            "transaction_hash": null,
189            "block_hash": null,
190            "block_number": "0x1581b82",
191            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
192            "data": "0x",
193            "topics": []
194        });
195        serde_json::from_value(log_json).expect("Failed to deserialize log")
196    }
197
198    #[fixture]
199    fn log_with_none_topic0() -> HypersyncLog {
200        let log_json = json!({
201            "removed": null,
202            "log_index": null,
203            "transaction_index": null,
204            "transaction_hash": null,
205            "block_hash": null,
206            "block_number": "0x1581b82",
207            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
208            "data": "0x",
209            "topics": [null]
210        });
211        serde_json::from_value(log_json).expect("Failed to deserialize log")
212    }
213
214    #[fixture]
215    fn log_with_block_hash() -> HypersyncLog {
216        let log_json = json!({
217            "removed": null,
218            "log_index": null,
219            "transaction_index": null,
220            "transaction_hash": null,
221            "block_hash": "0xd371b6c7b04ec33d6470f067a82e87d7b294b952bea7a46d7b939b4c7addc275",
222            "block_number": "0x1581b7e",
223            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
224            "data": "0x",
225            "topics": []
226        });
227        serde_json::from_value(log_json).expect("Failed to deserialize log")
228    }
229
230    #[rstest]
231    fn test_extract_block_hash_selected(log_with_block_hash: HypersyncLog) {
232        let expected =
233            B256::from_str("0xd371b6c7b04ec33d6470f067a82e87d7b294b952bea7a46d7b939b4c7addc275")
234                .unwrap();
235        assert_eq!(extract_block_hash(&log_with_block_hash), Some(expected));
236    }
237
238    #[rstest]
239    fn test_extract_block_hash_unselected_returns_none(swap_log_1: HypersyncLog) {
240        assert_eq!(extract_block_hash(&swap_log_1), None);
241    }
242
243    #[rstest]
244    fn test_validate_event_signature_hash_success(swap_log_1: HypersyncLog) {
245        // The topic0 from swap_log_1 is the swap event signature
246        let expected_hash = "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67";
247
248        let result = validate_event_signature_hash("Swap", expected_hash, &swap_log_1);
249        assert!(result.is_ok());
250    }
251
252    #[rstest]
253    fn test_validate_event_signature_hash_success_log2(swap_log_2: HypersyncLog) {
254        // The topic0 from swap_log_2 is also the swap event signature
255        let expected_hash = "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67";
256
257        let result = validate_event_signature_hash("Swap", expected_hash, &swap_log_2);
258        assert!(result.is_ok());
259    }
260
261    #[rstest]
262    fn test_validate_event_signature_hash_mismatch(swap_log_1: HypersyncLog) {
263        // Using a different event signature (e.g., Transfer event)
264        let wrong_hash = "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
265
266        let result = validate_event_signature_hash("Transfer", wrong_hash, &swap_log_1);
267        assert!(result.is_err());
268        assert!(
269            result
270                .unwrap_err()
271                .to_string()
272                .contains("Invalid event signature for 'Transfer'")
273        );
274    }
275
276    #[rstest]
277    fn test_validate_event_signature_hash_missing_topic0(log_without_topics: HypersyncLog) {
278        let expected_hash = "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67";
279
280        let result = validate_event_signature_hash("Swap", expected_hash, &log_without_topics);
281        assert!(result.is_err());
282        assert_eq!(
283            result.unwrap_err().to_string(),
284            "Missing event signature in topic0"
285        );
286    }
287
288    #[rstest]
289    fn test_validate_event_signature_hash_none_topic0(log_with_none_topic0: HypersyncLog) {
290        let expected_hash = "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67";
291
292        let result = validate_event_signature_hash("Swap", expected_hash, &log_with_none_topic0);
293        assert!(result.is_err());
294        assert_eq!(
295            result.unwrap_err().to_string(),
296            "Missing event signature in topic0"
297        );
298    }
299
300    #[rstest]
301    fn test_extract_transaction_hash_success() {
302        let log_json = json!({
303            "removed": null,
304            "log_index": null,
305            "transaction_index": null,
306            "transaction_hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
307            "block_hash": null,
308            "block_number": "0x1581b82",
309            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
310            "data": "0x",
311            "topics": []
312        });
313        let log: HypersyncLog =
314            serde_json::from_value(log_json).expect("Failed to deserialize log");
315
316        let result = extract_transaction_hash(&log);
317        assert!(result.is_ok());
318        assert_eq!(
319            result.unwrap(),
320            "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
321        );
322    }
323
324    #[rstest]
325    fn test_extract_transaction_hash_missing() {
326        let log_json = json!({
327            "removed": null,
328            "log_index": null,
329            "transaction_index": null,
330            "transaction_hash": null,
331            "block_hash": null,
332            "block_number": "0x1581b82",
333            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
334            "data": "0x",
335            "topics": []
336        });
337        let log: HypersyncLog =
338            serde_json::from_value(log_json).expect("Failed to deserialize log");
339
340        let result = extract_transaction_hash(&log);
341        assert!(result.is_err());
342        assert_eq!(
343            result.unwrap_err().to_string(),
344            "Missing transaction hash in log"
345        );
346    }
347
348    #[rstest]
349    fn test_extract_transaction_index_success() {
350        let log_json = json!({
351            "removed": null,
352            "log_index": null,
353            "transaction_index": "0x5",
354            "transaction_hash": null,
355            "block_hash": null,
356            "block_number": "0x1581b82",
357            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
358            "data": "0x",
359            "topics": []
360        });
361        let log: HypersyncLog =
362            serde_json::from_value(log_json).expect("Failed to deserialize log");
363
364        let result = extract_transaction_index(&log);
365        assert!(result.is_ok());
366        assert_eq!(result.unwrap(), 5u32);
367    }
368
369    #[rstest]
370    fn test_extract_transaction_index_missing() {
371        let log_json = json!({
372            "removed": null,
373            "log_index": null,
374            "transaction_index": null,
375            "transaction_hash": null,
376            "block_hash": null,
377            "block_number": "0x1581b82",
378            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
379            "data": "0x",
380            "topics": []
381        });
382        let log: HypersyncLog =
383            serde_json::from_value(log_json).expect("Failed to deserialize log");
384
385        let result = extract_transaction_index(&log);
386        assert!(result.is_err());
387        assert_eq!(
388            result.unwrap_err().to_string(),
389            "Missing transaction index in the log"
390        );
391    }
392
393    #[rstest]
394    fn test_extract_log_index_success() {
395        let log_json = json!({
396            "removed": null,
397            "log_index": "0xa",
398            "transaction_index": null,
399            "transaction_hash": null,
400            "block_hash": null,
401            "block_number": "0x1581b82",
402            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
403            "data": "0x",
404            "topics": []
405        });
406        let log: HypersyncLog =
407            serde_json::from_value(log_json).expect("Failed to deserialize log");
408
409        let result = extract_log_index(&log);
410        assert!(result.is_ok());
411        assert_eq!(result.unwrap(), 10u32);
412    }
413
414    #[rstest]
415    fn test_extract_log_index_missing() {
416        let log_json = json!({
417            "removed": null,
418            "log_index": null,
419            "transaction_index": null,
420            "transaction_hash": null,
421            "block_hash": null,
422            "block_number": "0x1581b82",
423            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
424            "data": "0x",
425            "topics": []
426        });
427        let log: HypersyncLog =
428            serde_json::from_value(log_json).expect("Failed to deserialize log");
429
430        let result = extract_log_index(&log);
431        assert!(result.is_err());
432        assert_eq!(
433            result.unwrap_err().to_string(),
434            "Missing log index in the log"
435        );
436    }
437
438    #[rstest]
439    fn test_extract_block_number_success() {
440        let log_json = json!({
441            "removed": null,
442            "log_index": null,
443            "transaction_index": null,
444            "transaction_hash": null,
445            "block_hash": null,
446            "block_number": "0x1581b82",
447            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
448            "data": "0x",
449            "topics": []
450        });
451        let log: HypersyncLog =
452            serde_json::from_value(log_json).expect("Failed to deserialize log");
453
454        let result = extract_block_number(&log);
455        assert!(result.is_ok());
456        assert_eq!(result.unwrap(), 22551426u64); // 0x1581b82 in decimal
457    }
458
459    #[rstest]
460    fn test_extract_block_number_missing() {
461        let log_json = json!({
462            "removed": null,
463            "log_index": null,
464            "transaction_index": null,
465            "transaction_hash": null,
466            "block_hash": null,
467            "block_number": null,
468            "address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
469            "data": "0x",
470            "topics": []
471        });
472        let log: HypersyncLog =
473            serde_json::from_value(log_json).expect("Failed to deserialize log");
474
475        let result = extract_block_number(&log);
476        assert!(result.is_err());
477        assert_eq!(
478            result.unwrap_err().to_string(),
479            "Missing block number in the log"
480        );
481    }
482
483    #[rstest]
484    fn test_extract_address_from_topic_success(swap_log_1: HypersyncLog) {
485        // Extract sender address from topic1
486        let result = extract_address_from_topic(&swap_log_1, 1, "sender");
487        assert!(result.is_ok());
488        let address = result.unwrap();
489        assert_eq!(
490            address.to_string().to_lowercase(),
491            "0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad"
492        );
493    }
494
495    #[rstest]
496    fn test_extract_address_from_topic_success_log2(swap_log_2: HypersyncLog) {
497        // Extract sender address from topic1
498        let result = extract_address_from_topic(&swap_log_2, 1, "sender");
499        assert!(result.is_ok());
500        let address = result.unwrap();
501        assert_eq!(
502            address.to_string().to_lowercase(),
503            "0x66a9893cc07d91d95644aedd05d03f95e1dba8af"
504        );
505
506        // Extract recipient address from topic2
507        let result = extract_address_from_topic(&swap_log_2, 2, "recipient");
508        assert!(result.is_ok());
509        let address = result.unwrap();
510        assert_eq!(
511            address.to_string().to_lowercase(),
512            "0xf90321d0ecad58ab2b0c8c79db8aaeeefa023578"
513        );
514    }
515
516    #[rstest]
517    fn test_extract_address_from_topic_missing_topic(swap_log_1: HypersyncLog) {
518        // Try to extract from topic index 5 (doesn't exist)
519        let result = extract_address_from_topic(&swap_log_1, 5, "nonexistent");
520        assert!(result.is_err());
521        assert_eq!(
522            result.unwrap_err().to_string(),
523            "Missing nonexistent address in topic5 when parsing event"
524        );
525    }
526
527    #[rstest]
528    fn test_extract_address_from_topic_none_topic(swap_log_1: HypersyncLog) {
529        // Try to extract from topic index 3 (which is null in swap_log_1)
530        let result = extract_address_from_topic(&swap_log_1, 3, "null_topic");
531        assert!(result.is_err());
532        assert_eq!(
533            result.unwrap_err().to_string(),
534            "Missing null_topic address in topic3 when parsing event"
535        );
536    }
537
538    #[rstest]
539    fn test_extract_address_from_topic_no_topics(log_without_topics: HypersyncLog) {
540        let result = extract_address_from_topic(&log_without_topics, 1, "sender");
541        assert!(result.is_err());
542        assert_eq!(
543            result.unwrap_err().to_string(),
544            "Missing sender address in topic1 when parsing event"
545        );
546    }
547}