Skip to main content

nautilus_blockchain/exchanges/parsing/uniswap_v3/
flash.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::{dyn_abi::SolType, primitives::Address, sol};
17use nautilus_model::defi::{PoolIdentifier, SharedDex, rpc::RpcLog};
18use ustr::Ustr;
19
20use crate::{
21    events::flash::FlashEvent,
22    hypersync::{
23        HypersyncLog,
24        log::{
25            extract_address_from_topic, extract_block_hash, extract_block_number,
26            extract_log_index, extract_transaction_hash, extract_transaction_index,
27            validate_event_signature_hash,
28        },
29    },
30    rpc::log as rpc_log,
31};
32
33// Placeholder hash - will be calculated properly later
34const FLASH_EVENT_SIGNATURE_HASH: &str =
35    "bdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca633";
36
37// Define sol macro for easier parsing of Flash event data
38// event Flash(address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1)
39sol! {
40    struct FlashEventData {
41        uint256 amount0;
42        uint256 amount1;
43        uint256 paid0;
44        uint256 paid1;
45    }
46}
47
48/// Parses a flash event from a Uniswap V3 log.
49///
50/// # Errors
51///
52/// Returns an error if the log parsing fails or if the event data is invalid.
53///
54/// # Panics
55///
56/// Panics if the contract address is not set in the log.
57pub fn parse_flash_event_hypersync(
58    dex: SharedDex,
59    log: &HypersyncLog,
60) -> anyhow::Result<FlashEvent> {
61    validate_event_signature_hash("FlashEvent", FLASH_EVENT_SIGNATURE_HASH, log)?;
62
63    let sender = extract_address_from_topic(log, 1, "sender")?;
64    let recipient = extract_address_from_topic(log, 2, "recipient")?;
65
66    if let Some(data) = &log.data {
67        let data_bytes = data.as_ref();
68
69        // Validate if data contains 4 parameters of 32 bytes each
70        if data_bytes.len() < 4 * 32 {
71            anyhow::bail!("Flash event data is too short");
72        }
73
74        // Decode the data using the FlashEventData struct
75        let decoded = match <FlashEventData as SolType>::abi_decode(data_bytes) {
76            Ok(decoded) => decoded,
77            Err(e) => anyhow::bail!("Failed to decode flash event data: {e}"),
78        };
79
80        let pool_address = Address::from_slice(
81            log.address
82                .clone()
83                .expect("Contract address should be set in logs")
84                .as_ref(),
85        );
86        let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
87
88        Ok(FlashEvent::new(
89            dex,
90            pool_identifier,
91            extract_block_number(log)?,
92            extract_block_hash(log),
93            extract_transaction_hash(log)?,
94            extract_transaction_index(log)?,
95            extract_log_index(log)?,
96            sender,
97            recipient,
98            decoded.amount0,
99            decoded.amount1,
100            decoded.paid0,
101            decoded.paid1,
102        ))
103    } else {
104        anyhow::bail!("Missing data in flash event log");
105    }
106}
107
108/// Parses a flash event from an RPC log.
109///
110/// # Errors
111///
112/// Returns an error if the log parsing fails or if the event data is invalid.
113pub fn parse_flash_event_rpc(dex: SharedDex, log: &RpcLog) -> anyhow::Result<FlashEvent> {
114    rpc_log::validate_event_signature(log, FLASH_EVENT_SIGNATURE_HASH, "Flash")?;
115
116    let sender = rpc_log::extract_address_from_topic(log, 1, "sender")?;
117    let recipient = rpc_log::extract_address_from_topic(log, 2, "recipient")?;
118
119    let data_bytes = rpc_log::extract_data_bytes(log)?;
120
121    // Validate if data contains 4 parameters of 32 bytes each
122    if data_bytes.len() < 4 * 32 {
123        anyhow::bail!("Flash event data is too short");
124    }
125
126    // Decode the data using the FlashEventData struct
127    let decoded = match <FlashEventData as SolType>::abi_decode(&data_bytes) {
128        Ok(decoded) => decoded,
129        Err(e) => anyhow::bail!("Failed to decode flash event data: {e}"),
130    };
131
132    let pool_address = rpc_log::extract_address(log)?;
133    let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
134    Ok(FlashEvent::new(
135        dex,
136        pool_identifier,
137        rpc_log::extract_block_number(log)?,
138        rpc_log::extract_block_hash(log)?,
139        rpc_log::extract_transaction_hash(log)?,
140        rpc_log::extract_transaction_index(log)?,
141        rpc_log::extract_log_index(log)?,
142        sender,
143        recipient,
144        decoded.amount0,
145        decoded.amount1,
146        decoded.paid0,
147        decoded.paid1,
148    ))
149}
150
151#[cfg(test)]
152mod tests {
153    use std::{str::FromStr, sync::Arc};
154
155    use alloy::primitives::{B256, U256};
156    use rstest::*;
157    use serde_json::json;
158
159    use super::*;
160    use crate::exchanges::arbitrum;
161
162    /// Real HyperSync log from Arbitrum Flash event at block 0xfe9d5ce (266982862)
163    /// Pool: 0x4cef551255ec96d89fec975446301b5c4e164c59
164    /// sender: 0xf3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b
165    /// recipient: 0xf3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b
166    #[fixture]
167    fn hypersync_log() -> HypersyncLog {
168        let log_json = json!({
169            "removed": null,
170            "log_index": "0x3b",
171            "transaction_index": "0x4",
172            "transaction_hash": "0x4d345a8cae1e39654904bb7ca04e552b0fc8728ed68a28563ea4b151b96262aa",
173            "block_hash": null,
174            "block_number": "0xfe9d5ce",
175            "address": "0x4CEf551255EC96d89feC975446301b5C4e164C59",
176            "data": "0x00000000000000000000000000000000000000000000002c55804c34816b99060000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000220c6ab9806365120000000000000000000000000000000000000000000000000000000000000000",
177            "topics": [
178                "0xbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca633",
179                "0x000000000000000000000000f3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b",
180                "0x000000000000000000000000f3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b"
181            ]
182        });
183        serde_json::from_value(log_json).expect("Failed to deserialize HyperSync log")
184    }
185
186    /// Real RPC log from Arbitrum Flash event at block 0xfe9d5ce (266982862)
187    #[fixture]
188    fn rpc_log() -> RpcLog {
189        let log_json = json!({
190            "removed": false,
191            "logIndex": "0x3b",
192            "transactionIndex": "0x4",
193            "transactionHash": "0x4d345a8cae1e39654904bb7ca04e552b0fc8728ed68a28563ea4b151b96262aa",
194            "blockHash": "0xf10a01cbc75fccad0384a7447f37f06bfb01fbd08d7541a6e5f558ff9bc31ea4",
195            "blockNumber": "0xfe9d5ce",
196            "address": "0x4CEf551255EC96d89feC975446301b5C4e164C59",
197            "data": "0x00000000000000000000000000000000000000000000002c55804c34816b99060000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000220c6ab9806365120000000000000000000000000000000000000000000000000000000000000000",
198            "topics": [
199                "0xbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca633",
200                "0x000000000000000000000000f3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b",
201                "0x000000000000000000000000f3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b"
202            ]
203        });
204        serde_json::from_value(log_json).expect("Failed to deserialize RPC log")
205    }
206
207    #[rstest]
208    fn test_parse_flash_event_hypersync(hypersync_log: HypersyncLog) {
209        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
210        let event = parse_flash_event_hypersync(dex, &hypersync_log).unwrap();
211
212        assert_eq!(event.block_hash, None);
213
214        assert_eq!(
215            event.pool_identifier.to_string(),
216            "0x4CEf551255EC96d89feC975446301b5C4e164C59"
217        );
218        assert_eq!(
219            event.sender.to_string().to_lowercase(),
220            "0xf3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b"
221        );
222        assert_eq!(
223            event.recipient.to_string().to_lowercase(),
224            "0xf3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b"
225        );
226        let expected_amount0 = U256::from_str_radix("2c55804c34816b9906", 16).unwrap();
227        assert_eq!(event.amount0, expected_amount0);
228        assert_eq!(event.amount1, U256::ZERO);
229        let expected_paid0 = U256::from_str_radix("220c6ab980636512", 16).unwrap();
230        assert_eq!(event.paid0, expected_paid0);
231        assert_eq!(event.paid1, U256::ZERO);
232        assert_eq!(event.block_number, 266982862);
233    }
234
235    #[rstest]
236    fn test_parse_flash_event_rpc(rpc_log: RpcLog) {
237        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
238        let event = parse_flash_event_rpc(dex, &rpc_log).unwrap();
239
240        let expected =
241            B256::from_str("0xf10a01cbc75fccad0384a7447f37f06bfb01fbd08d7541a6e5f558ff9bc31ea4")
242                .unwrap();
243        assert_eq!(event.block_hash, Some(expected));
244
245        assert_eq!(
246            event.pool_identifier.to_string(),
247            "0x4CEf551255EC96d89feC975446301b5C4e164C59"
248        );
249        assert_eq!(
250            event.sender.to_string().to_lowercase(),
251            "0xf3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b"
252        );
253        assert_eq!(
254            event.recipient.to_string().to_lowercase(),
255            "0xf3f521ee74debaa28fd0ea1e8ca2fd8d6c110d8b"
256        );
257        let expected_amount0 = U256::from_str_radix("2c55804c34816b9906", 16).unwrap();
258        assert_eq!(event.amount0, expected_amount0);
259        assert_eq!(event.amount1, U256::ZERO);
260        let expected_paid0 = U256::from_str_radix("220c6ab980636512", 16).unwrap();
261        assert_eq!(event.paid0, expected_paid0);
262        assert_eq!(event.paid1, U256::ZERO);
263        assert_eq!(event.block_number, 266982862);
264    }
265
266    #[rstest]
267    fn test_hypersync_rpc_match(hypersync_log: HypersyncLog, rpc_log: RpcLog) {
268        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
269        let event_hypersync =
270            parse_flash_event_hypersync(Arc::clone(&dex), &hypersync_log).unwrap();
271        let event_rpc = parse_flash_event_rpc(dex, &rpc_log).unwrap();
272
273        assert_eq!(event_hypersync.pool_identifier, event_rpc.pool_identifier);
274        assert_eq!(event_hypersync.sender, event_rpc.sender);
275        assert_eq!(event_hypersync.recipient, event_rpc.recipient);
276        assert_eq!(event_hypersync.amount0, event_rpc.amount0);
277        assert_eq!(event_hypersync.amount1, event_rpc.amount1);
278        assert_eq!(event_hypersync.paid0, event_rpc.paid0);
279        assert_eq!(event_hypersync.paid1, event_rpc.paid1);
280        assert_eq!(event_hypersync.block_number, event_rpc.block_number);
281        assert_eq!(event_hypersync.transaction_hash, event_rpc.transaction_hash);
282    }
283}