nautilus_blockchain/rpc/
log.rs1use std::str::FromStr;
21
22use alloy::primitives::{Address, B256};
23use nautilus_core::hex;
24use nautilus_model::defi::rpc::RpcLog;
25
26pub 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
35pub 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
45pub 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
55pub 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
68pub 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
84pub 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
95pub 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
108pub 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
121pub 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
137pub 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
150pub 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
173pub fn extract_data_bytes(log: &RpcLog) -> anyhow::Result<Vec<u8>> {
179 decode_hex(&log.data)
180}
181
182pub 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 #[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 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); }
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 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 assert_eq!(data.len(), 64); 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 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}