|
| 1 | +use std::{ |
| 2 | + fs::{File, OpenOptions}, |
| 3 | + io::{Read, Write}, |
| 4 | + time::Duration, |
| 5 | +}; |
| 6 | + |
| 7 | +use ethers::prelude::*; |
| 8 | +use serde::{Deserialize, Serialize}; |
| 9 | +use tokio::time::sleep; |
| 10 | + |
| 11 | +pub(crate) const DEFAULT_BLOCK_RANGE: u64 = 50_000; |
| 12 | + |
| 13 | +/// A single log entry we want to store. |
| 14 | +#[derive(Debug, Serialize, Deserialize)] |
| 15 | +pub(crate) struct QueriedLog { |
| 16 | + /// The block number where this log was found (optional because logs can have None for pending blocks) |
| 17 | + pub(crate) block_number: Option<u64>, |
| 18 | + /// The transaction hash for the log |
| 19 | + pub(crate) transaction_hash: Option<H256>, |
| 20 | + /// The address this log was emitted from |
| 21 | + pub(crate) address: Address, |
| 22 | + /// All topics for the log |
| 23 | + pub(crate) topics: Vec<H256>, |
| 24 | + /// The data field of the log |
| 25 | + pub(crate) data: Vec<u8>, |
| 26 | +} |
| 27 | + |
| 28 | +/// A cache structure that keeps track of how far we’ve fetched and |
| 29 | +/// also retains all queried logs in a vector. |
| 30 | +#[derive(Debug, Serialize, Deserialize)] |
| 31 | +struct Cache { |
| 32 | + first_seen_block: u64, |
| 33 | + last_seen_block: u64, |
| 34 | + all_logs: Vec<QueriedLog>, |
| 35 | +} |
| 36 | + |
| 37 | +/// Read a cache file from disk. |
| 38 | +fn read_cache_from_file(cache_path: &str) -> Option<Cache> { |
| 39 | + let mut file = File::open(cache_path).ok()?; |
| 40 | + let mut data = vec![]; |
| 41 | + file.read_to_end(&mut data).ok()?; |
| 42 | + serde_json::from_slice(&data).ok() |
| 43 | +} |
| 44 | + |
| 45 | +/// Write a cache file to disk. |
| 46 | +fn write_cache_to_file(cache_path: &str, cache: &Cache) -> Result<(), Box<dyn std::error::Error>> { |
| 47 | + let serialized = serde_json::to_vec_pretty(cache)?; |
| 48 | + let mut file = OpenOptions::new() |
| 49 | + .write(true) |
| 50 | + .create(true) |
| 51 | + .truncate(true) |
| 52 | + .open(cache_path)?; |
| 53 | + file.write_all(&serialized)?; |
| 54 | + Ok(()) |
| 55 | +} |
| 56 | + |
| 57 | +/// This function will: |
| 58 | +/// 1. Read from (or initialize) a cache |
| 59 | +/// 2. For each `(address, event_signature)` in `events_to_query`, build a filter |
| 60 | +/// 3. Fetch logs in chunks of `block_range` |
| 61 | +/// 4. Store each log's topics and data in the cache |
| 62 | +/// 5. Write updates back to the cache |
| 63 | +/// |
| 64 | +/// Returns the final vector of logs once all blocks have been processed. |
| 65 | +pub(crate) async fn get_logs_for_events( |
| 66 | + block_to_start_with: u64, |
| 67 | + existing_cache_path: &str, |
| 68 | + rpc_url: &str, |
| 69 | + block_range: u64, |
| 70 | + events_to_query: &[(Address, &str, Option<H256>)], // (contract address, event signature, topic1) |
| 71 | +) -> Vec<QueriedLog> { |
| 72 | + // --------------------------------------------------------- |
| 73 | + // 1. Read or initialize the cache |
| 74 | + // --------------------------------------------------------- |
| 75 | + let mut cache = read_cache_from_file(existing_cache_path).unwrap_or_else(|| Cache { |
| 76 | + first_seen_block: block_to_start_with, |
| 77 | + last_seen_block: block_to_start_with, |
| 78 | + all_logs: vec![], |
| 79 | + }); |
| 80 | + |
| 81 | + // If the cache file was found, check the condition about `first_seen_block` |
| 82 | + if cache.first_seen_block > block_to_start_with { |
| 83 | + // If the cache's first_seen_block is larger than our new start, |
| 84 | + // clear the entire cache and reset. |
| 85 | + cache.first_seen_block = block_to_start_with; |
| 86 | + cache.last_seen_block = block_to_start_with; |
| 87 | + cache.all_logs.clear(); |
| 88 | + } |
| 89 | + |
| 90 | + // --------------------------------------------------------- |
| 91 | + // 2. Connect to a provider |
| 92 | + // --------------------------------------------------------- |
| 93 | + let provider = |
| 94 | + Provider::<Http>::try_from(rpc_url).expect("Could not instantiate HTTP Provider"); |
| 95 | + |
| 96 | + // Get the latest block so we know how far we can go |
| 97 | + let latest_block = provider |
| 98 | + .get_block_number() |
| 99 | + .await |
| 100 | + .expect("Failed to fetch latest block") |
| 101 | + .as_u64(); |
| 102 | + |
| 103 | + // Our actual starting point is whichever is further along |
| 104 | + let mut current_block = cache.last_seen_block; |
| 105 | + |
| 106 | + // --------------------------------------------------------- |
| 107 | + // 3. Process logs in chunks of block_range |
| 108 | + // --------------------------------------------------------- |
| 109 | + while current_block <= latest_block { |
| 110 | + let start_of_range = current_block; |
| 111 | + let end_of_range = std::cmp::min(start_of_range + block_range, latest_block); |
| 112 | + |
| 113 | + println!("Processing range {start_of_range} - {end_of_range}\n"); |
| 114 | + |
| 115 | + // If the entire range is below what we have already processed, skip |
| 116 | + if end_of_range < cache.last_seen_block { |
| 117 | + // skip range |
| 118 | + current_block = end_of_range + 1; |
| 119 | + println!("Range is cached, skipping..."); |
| 120 | + continue; |
| 121 | + } |
| 122 | + |
| 123 | + // We'll collect all logs from all event filters in this chunk |
| 124 | + let mut new_logs_for_range = Vec::new(); |
| 125 | + |
| 126 | + // --------------------------------------------------------- |
| 127 | + // 4. Build filters for each event signature and fetch logs |
| 128 | + // --------------------------------------------------------- |
| 129 | + for (contract_address, event_sig, topic_1) in events_to_query.iter() { |
| 130 | + // Example usage with ethers-rs: Filter::new().event(event_sig) |
| 131 | + // If your event signature is an "event Foo(address,uint256)" string, |
| 132 | + // ethers-rs will do the topic0 hashing automatically. |
| 133 | + // Alternatively, you can manually set .topics(Some(vec![event_sig_hash]), None, None, None). |
| 134 | + let mut filter = Filter::new() |
| 135 | + .address(*contract_address) |
| 136 | + .event(event_sig) |
| 137 | + .from_block(start_of_range) |
| 138 | + .to_block(end_of_range); |
| 139 | + |
| 140 | + if let Some(x) = topic_1 { |
| 141 | + filter = filter.topic1(*x); |
| 142 | + } |
| 143 | + |
| 144 | + // Sleep for 1 second before each JSON-RPC request to avoid hitting rate limits |
| 145 | + sleep(Duration::from_secs(1)).await; |
| 146 | + |
| 147 | + let logs = match provider.get_logs(&filter).await { |
| 148 | + Ok(ls) => ls, |
| 149 | + Err(e) => { |
| 150 | + eprintln!( |
| 151 | + "Failed to fetch logs for event signature {event_sig} at {contract_address:?}: {e}" |
| 152 | + ); |
| 153 | + continue; |
| 154 | + } |
| 155 | + }; |
| 156 | + |
| 157 | + // Store each log's topics + data |
| 158 | + for log in logs { |
| 159 | + new_logs_for_range.push(QueriedLog { |
| 160 | + block_number: log.block_number.map(|bn| bn.as_u64()), |
| 161 | + transaction_hash: log.transaction_hash, |
| 162 | + address: log.address, |
| 163 | + topics: log.topics, |
| 164 | + data: log.data.to_vec(), |
| 165 | + }); |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + // --------------------------------------------------------- |
| 170 | + // 5. Update the cache, flush it to disk |
| 171 | + // --------------------------------------------------------- |
| 172 | + cache.last_seen_block = end_of_range; |
| 173 | + cache.all_logs.extend(new_logs_for_range); |
| 174 | + |
| 175 | + write_cache_to_file(existing_cache_path, &cache).expect("Failed to write cache to file"); |
| 176 | + |
| 177 | + println!("Processed and saved the range!"); |
| 178 | + |
| 179 | + // Move our current_block pointer forward |
| 180 | + if end_of_range == latest_block { |
| 181 | + break; |
| 182 | + } else { |
| 183 | + current_block = end_of_range + 1; |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + // Return the logs we have in the cache. If you only want the new logs |
| 188 | + // from this run, you could track them differently. But for simplicity, |
| 189 | + // we return everything in the cache. |
| 190 | + cache.all_logs |
| 191 | +} |
0 commit comments