Skip to main content

nautilus_blockchain/exchanges/parsing/uniswap_v3/
swap.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::swap::SwapEvent,
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
33const SWAP_EVENT_SIGNATURE_HASH: &str =
34    "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67";
35
36// Define sol macro for easier parsing of Swap event data
37// It contains 5 parameters of 32 bytes each:
38// amount0 (int256), amount1 (int256), sqrtPriceX96 (uint160), liquidity (uint128), tick (int24)
39sol! {
40    struct SwapEventData {
41        int256 amount0;
42        int256 amount1;
43        uint160 sqrt_price_x96;
44        uint128 liquidity;
45        int24 tick;
46    }
47}
48
49/// Parses a swap event from a HyperSync log.
50///
51/// # Errors
52///
53/// Returns an error if the log parsing fails or if the event data is invalid.
54///
55/// # Panics
56///
57/// Panics if the contract address is not set in the log.
58pub fn parse_swap_event_hypersync(dex: SharedDex, log: &HypersyncLog) -> anyhow::Result<SwapEvent> {
59    validate_event_signature_hash("SwapEvent", SWAP_EVENT_SIGNATURE_HASH, log)?;
60
61    let sender = extract_address_from_topic(log, 1, "sender")?;
62    let recipient = extract_address_from_topic(log, 2, "recipient")?;
63
64    if let Some(data) = &log.data {
65        let data_bytes = data.as_ref();
66
67        // Validate if data contains 5 parameters of 32 bytes each
68        if data_bytes.len() < 5 * 32 {
69            anyhow::bail!("Swap event data is too short");
70        }
71
72        // Decode the data using the SwapEventData struct
73        let decoded = match <SwapEventData as SolType>::abi_decode(data_bytes) {
74            Ok(decoded) => decoded,
75            Err(e) => anyhow::bail!("Failed to decode swap event data: {e}"),
76        };
77        let _ = decoded.amount0;
78        let pool_address = Address::from_slice(
79            log.address
80                .clone()
81                .expect("Contract address should be set in logs")
82                .as_ref(),
83        );
84        let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
85        Ok(SwapEvent::new(
86            dex,
87            pool_identifier,
88            extract_block_number(log)?,
89            extract_block_hash(log),
90            extract_transaction_hash(log)?,
91            extract_transaction_index(log)?,
92            extract_log_index(log)?,
93            sender,
94            recipient,
95            decoded.amount0,
96            decoded.amount1,
97            decoded.sqrt_price_x96,
98            decoded.liquidity,
99            decoded.tick.as_i32(),
100        ))
101    } else {
102        Err(anyhow::anyhow!("Missing data in swap event log"))
103    }
104}
105
106/// Parses a swap event from an RPC log.
107///
108/// # Errors
109///
110/// Returns an error if the log parsing fails or if the event data is invalid.
111pub fn parse_swap_event_rpc(dex: SharedDex, log: &RpcLog) -> anyhow::Result<SwapEvent> {
112    rpc_log::validate_event_signature(log, SWAP_EVENT_SIGNATURE_HASH, "Swap")?;
113
114    let sender = rpc_log::extract_address_from_topic(log, 1, "sender")?;
115    let recipient = rpc_log::extract_address_from_topic(log, 2, "recipient")?;
116
117    let data_bytes = rpc_log::extract_data_bytes(log)?;
118
119    // Validate if data contains 5 parameters of 32 bytes each
120    if data_bytes.len() < 5 * 32 {
121        anyhow::bail!("Swap event data is too short");
122    }
123
124    // Decode the data using the SwapEventData struct
125    let decoded = match <SwapEventData as SolType>::abi_decode(&data_bytes) {
126        Ok(decoded) => decoded,
127        Err(e) => anyhow::bail!("Failed to decode swap event data: {e}"),
128    };
129
130    let pool_address = rpc_log::extract_address(log)?;
131    let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
132    Ok(SwapEvent::new(
133        dex,
134        pool_identifier,
135        rpc_log::extract_block_number(log)?,
136        rpc_log::extract_block_hash(log)?,
137        rpc_log::extract_transaction_hash(log)?,
138        rpc_log::extract_transaction_index(log)?,
139        rpc_log::extract_log_index(log)?,
140        sender,
141        recipient,
142        decoded.amount0,
143        decoded.amount1,
144        decoded.sqrt_price_x96,
145        decoded.liquidity,
146        decoded.tick.as_i32(),
147    ))
148}
149
150#[cfg(test)]
151mod tests {
152    use std::{str::FromStr, sync::Arc};
153
154    use alloy::primitives::{B256, I256, U160, U256};
155    use rstest::*;
156    use serde_json::json;
157
158    use super::*;
159    use crate::exchanges::arbitrum;
160
161    /// Real HyperSync log from Arbitrum Swap event at block 0x17513444 (391197764)
162    /// Pool: 0xd13040d4fe917ee704158cfcb3338dcd2838b245
163    /// sender: 0x9da4a7d3cf502337797ea37724f7afc426377119
164    /// recipient: 0xd491076c7316bc28fd4d35e3da9ab5286d079250
165    /// amount0: negative (token out)
166    /// amount1: positive (token in)
167    /// tick: -139475 (0xfffddf2d)
168    #[fixture]
169    fn hypersync_log() -> HypersyncLog {
170        let log_json = json!({
171            "removed": null,
172            "log_index": "0x6",
173            "transaction_index": "0x3",
174            "transaction_hash": "0x381ae1c1b65bba31abdfc68ef6b3e3e49913161a15398ccff3b242b05473e720",
175            "block_hash": null,
176            "block_number": "0x17513444",
177            "address": "0xd13040d4fe917EE704158CfCB3338dCd2838B245",
178            "data": "0xffffffffffffffffffffffffffffffffffffffffffffff0918233055494456fe000000000000000000000000000000000000000000000000000e2a274937d6380000000000000000000000000000000000000000003d5fe159ea44896552c1cd000000000000000000000000000000000000000000000074009aac72ba0a9b1cfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffddf2d",
179            "topics": [
180                "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67",
181                "0x0000000000000000000000009da4a7d3cf502337797ea37724f7afc426377119",
182                "0x000000000000000000000000d491076c7316bc28fd4d35e3da9ab5286d079250"
183            ]
184        });
185        serde_json::from_value(log_json).expect("Failed to deserialize HyperSync log")
186    }
187
188    /// Real RPC log from Arbitrum Swap event at block 0x17513444 (391197764)
189    #[fixture]
190    fn rpc_log() -> RpcLog {
191        let log_json = json!({
192            "removed": false,
193            "logIndex": "0x6",
194            "transactionIndex": "0x3",
195            "transactionHash": "0x381ae1c1b65bba31abdfc68ef6b3e3e49913161a15398ccff3b242b05473e720",
196            "blockHash": "0x43082eabb648a3b87bd22abf7ec645a97e6e7f099dcc18894830c70d85675fae",
197            "blockNumber": "0x17513444",
198            "address": "0xd13040d4fe917EE704158CfCB3338dCd2838B245",
199            "data": "0xffffffffffffffffffffffffffffffffffffffffffffff0918233055494456fe000000000000000000000000000000000000000000000000000e2a274937d6380000000000000000000000000000000000000000003d5fe159ea44896552c1cd000000000000000000000000000000000000000000000074009aac72ba0a9b1cfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffddf2d",
200            "topics": [
201                "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67",
202                "0x0000000000000000000000009da4a7d3cf502337797ea37724f7afc426377119",
203                "0x000000000000000000000000d491076c7316bc28fd4d35e3da9ab5286d079250"
204            ]
205        });
206        serde_json::from_value(log_json).expect("Failed to deserialize RPC log")
207    }
208
209    #[rstest]
210    fn test_parse_swap_event_hypersync(hypersync_log: HypersyncLog) {
211        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
212        let event = parse_swap_event_hypersync(dex, &hypersync_log).unwrap();
213
214        assert_eq!(event.block_hash, None);
215
216        assert_eq!(
217            event.pool_identifier.to_string(),
218            "0xd13040d4fe917EE704158CfCB3338dCd2838B245"
219        );
220        assert_eq!(
221            event.sender.to_string().to_lowercase(),
222            "0x9da4a7d3cf502337797ea37724f7afc426377119"
223        );
224        assert_eq!(
225            event.receiver.to_string().to_lowercase(),
226            "0xd491076c7316bc28fd4d35e3da9ab5286d079250"
227        );
228        let expected_amount0 = I256::from_raw(
229            U256::from_str_radix(
230                "ffffffffffffffffffffffffffffffffffffffffffffff0918233055494456fe",
231                16,
232            )
233            .unwrap(),
234        );
235        assert_eq!(event.amount0, expected_amount0);
236        let expected_amount1 = I256::from_raw(U256::from_str_radix("0e2a274937d638", 16).unwrap());
237        assert_eq!(event.amount1, expected_amount1);
238        let expected_sqrt_price = U160::from_str_radix("3d5fe159ea44896552c1cd", 16).unwrap();
239        assert_eq!(event.sqrt_price_x96, expected_sqrt_price);
240        let expected_liquidity = u128::from_str_radix("74009aac72ba0a9b1c", 16).unwrap();
241        assert_eq!(event.liquidity, expected_liquidity);
242        assert_eq!(event.tick, -139475);
243        assert_eq!(event.block_number, 391197764);
244    }
245
246    #[rstest]
247    fn test_parse_swap_event_rpc(rpc_log: RpcLog) {
248        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
249        let event = parse_swap_event_rpc(dex, &rpc_log).unwrap();
250
251        let expected =
252            B256::from_str("0x43082eabb648a3b87bd22abf7ec645a97e6e7f099dcc18894830c70d85675fae")
253                .unwrap();
254        assert_eq!(event.block_hash, Some(expected));
255
256        assert_eq!(
257            event.pool_identifier.to_string(),
258            "0xd13040d4fe917EE704158CfCB3338dCd2838B245"
259        );
260        assert_eq!(
261            event.sender.to_string().to_lowercase(),
262            "0x9da4a7d3cf502337797ea37724f7afc426377119"
263        );
264        assert_eq!(
265            event.receiver.to_string().to_lowercase(),
266            "0xd491076c7316bc28fd4d35e3da9ab5286d079250"
267        );
268        let expected_amount0 = I256::from_raw(
269            U256::from_str_radix(
270                "ffffffffffffffffffffffffffffffffffffffffffffff0918233055494456fe",
271                16,
272            )
273            .unwrap(),
274        );
275        assert_eq!(event.amount0, expected_amount0);
276        let expected_amount1 = I256::from_raw(U256::from_str_radix("0e2a274937d638", 16).unwrap());
277        assert_eq!(event.amount1, expected_amount1);
278        let expected_sqrt_price = U160::from_str_radix("3d5fe159ea44896552c1cd", 16).unwrap();
279        assert_eq!(event.sqrt_price_x96, expected_sqrt_price);
280        let expected_liquidity = u128::from_str_radix("74009aac72ba0a9b1c", 16).unwrap();
281        assert_eq!(event.liquidity, expected_liquidity);
282        assert_eq!(event.tick, -139475);
283        assert_eq!(event.block_number, 391197764);
284    }
285
286    #[rstest]
287    fn test_parse_swap_event_rpc_missing_block_hash_carries_none(mut rpc_log: RpcLog) {
288        rpc_log.block_hash = None;
289
290        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
291        let event = parse_swap_event_rpc(dex, &rpc_log).unwrap();
292
293        assert_eq!(event.block_hash, None);
294        assert_eq!(event.block_number, 391197764);
295    }
296
297    #[rstest]
298    fn test_hypersync_rpc_match(hypersync_log: HypersyncLog, rpc_log: RpcLog) {
299        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
300        let event_hypersync = parse_swap_event_hypersync(Arc::clone(&dex), &hypersync_log).unwrap();
301        let event_rpc = parse_swap_event_rpc(dex, &rpc_log).unwrap();
302
303        assert_eq!(event_hypersync.pool_identifier, event_rpc.pool_identifier);
304        assert_eq!(event_hypersync.sender, event_rpc.sender);
305        assert_eq!(event_hypersync.receiver, event_rpc.receiver);
306        assert_eq!(event_hypersync.amount0, event_rpc.amount0);
307        assert_eq!(event_hypersync.amount1, event_rpc.amount1);
308        assert_eq!(event_hypersync.sqrt_price_x96, event_rpc.sqrt_price_x96);
309        assert_eq!(event_hypersync.liquidity, event_rpc.liquidity);
310        assert_eq!(event_hypersync.tick, event_rpc.tick);
311        assert_eq!(event_hypersync.block_number, event_rpc.block_number);
312        assert_eq!(event_hypersync.transaction_hash, event_rpc.transaction_hash);
313    }
314}