Skip to main content

nautilus_blockchain/exchanges/parsing/pancakeswap_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
33// PancakeSwap V3's Swap appends protocolFees fields, so its topic0 differs from Uniswap V3.
34const SWAP_EVENT_SIGNATURE_HASH: &str =
35    "19b47279256b2a23a1665c810c8d55a1758940ee09377d4f8d26497a3577dc83";
36
37// Uniswap V3's Swap fields plus PancakeSwap's two appended protocolFees fields.
38sol! {
39    struct SwapEventData {
40        int256 amount0;
41        int256 amount1;
42        uint160 sqrt_price_x96;
43        uint128 liquidity;
44        int24 tick;
45        uint128 protocol_fees_token0;
46        uint128 protocol_fees_token1;
47    }
48}
49
50/// Parses a PancakeSwap V3 swap event from a HyperSync log.
51///
52/// The protocol-fee fields are decoded to validate the layout but dropped: the shared
53/// [`SwapEvent`] mirrors the Uniswap V3 fields, which is all downstream pool profiling uses.
54///
55/// # Errors
56///
57/// Returns an error if the log parsing fails or if the event data is invalid.
58///
59/// # Panics
60///
61/// Panics if the contract address is not set in the log.
62pub fn parse_swap_event_hypersync(dex: SharedDex, log: &HypersyncLog) -> anyhow::Result<SwapEvent> {
63    validate_event_signature_hash("SwapEvent", SWAP_EVENT_SIGNATURE_HASH, log)?;
64
65    let sender = extract_address_from_topic(log, 1, "sender")?;
66    let recipient = extract_address_from_topic(log, 2, "recipient")?;
67
68    if let Some(data) = &log.data {
69        let data_bytes = data.as_ref();
70
71        if data_bytes.len() < 7 * 32 {
72            anyhow::bail!("Swap event data is too short");
73        }
74
75        let decoded = match <SwapEventData as SolType>::abi_decode(data_bytes) {
76            Ok(decoded) => decoded,
77            Err(e) => anyhow::bail!("Failed to decode swap event data: {e}"),
78        };
79        let pool_address = Address::from_slice(
80            log.address
81                .clone()
82                .expect("Contract address should be set in logs")
83                .as_ref(),
84        );
85        let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
86        Ok(SwapEvent::new(
87            dex,
88            pool_identifier,
89            extract_block_number(log)?,
90            extract_block_hash(log),
91            extract_transaction_hash(log)?,
92            extract_transaction_index(log)?,
93            extract_log_index(log)?,
94            sender,
95            recipient,
96            decoded.amount0,
97            decoded.amount1,
98            decoded.sqrt_price_x96,
99            decoded.liquidity,
100            decoded.tick.as_i32(),
101        ))
102    } else {
103        Err(anyhow::anyhow!("Missing data in swap event log"))
104    }
105}
106
107/// Parses a PancakeSwap V3 swap event from an RPC log.
108///
109/// # Errors
110///
111/// Returns an error if the log parsing fails or if the event data is invalid.
112pub fn parse_swap_event_rpc(dex: SharedDex, log: &RpcLog) -> anyhow::Result<SwapEvent> {
113    rpc_log::validate_event_signature(log, SWAP_EVENT_SIGNATURE_HASH, "Swap")?;
114
115    let sender = rpc_log::extract_address_from_topic(log, 1, "sender")?;
116    let recipient = rpc_log::extract_address_from_topic(log, 2, "recipient")?;
117
118    let data_bytes = rpc_log::extract_data_bytes(log)?;
119
120    if data_bytes.len() < 7 * 32 {
121        anyhow::bail!("Swap event data is too short");
122    }
123
124    let decoded = match <SwapEventData as SolType>::abi_decode(&data_bytes) {
125        Ok(decoded) => decoded,
126        Err(e) => anyhow::bail!("Failed to decode swap event data: {e}"),
127    };
128
129    let pool_address = rpc_log::extract_address(log)?;
130    let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
131    Ok(SwapEvent::new(
132        dex,
133        pool_identifier,
134        rpc_log::extract_block_number(log)?,
135        rpc_log::extract_block_hash(log)?,
136        rpc_log::extract_transaction_hash(log)?,
137        rpc_log::extract_transaction_index(log)?,
138        rpc_log::extract_log_index(log)?,
139        sender,
140        recipient,
141        decoded.amount0,
142        decoded.amount1,
143        decoded.sqrt_price_x96,
144        decoded.liquidity,
145        decoded.tick.as_i32(),
146    ))
147}
148
149#[cfg(test)]
150mod tests {
151    use std::{str::FromStr, sync::Arc};
152
153    use alloy::primitives::{B256, I256, U160, U256};
154    use rstest::*;
155
156    use super::*;
157    use crate::exchanges::bsc;
158
159    // Real PancakeSwap V3 Swap from BSC block 105495649 (WBNB/USDT 0.01% pool
160    // 0x172fcd41e0913e95784454622d1c3724f546f849)
161    const HYPERSYNC_SWAP_LOG: &str =
162        include_str!("../../../../test_data/pancakeswap_v3_swap_hypersync.json");
163    const RPC_SWAP_LOG: &str = include_str!("../../../../test_data/pancakeswap_v3_swap_rpc.json");
164
165    #[fixture]
166    fn hypersync_log() -> HypersyncLog {
167        serde_json::from_str(HYPERSYNC_SWAP_LOG).expect("Failed to deserialize HyperSync log")
168    }
169
170    #[fixture]
171    fn rpc_log() -> RpcLog {
172        serde_json::from_str(RPC_SWAP_LOG).expect("Failed to deserialize RPC log")
173    }
174
175    #[rstest]
176    fn test_parse_swap_event_hypersync(hypersync_log: HypersyncLog) {
177        let dex = Arc::clone(&bsc::PANCAKESWAP_V3.dex);
178        let event = parse_swap_event_hypersync(dex, &hypersync_log).unwrap();
179
180        assert_eq!(event.block_hash, None);
181
182        assert_eq!(
183            event.pool_identifier.to_string(),
184            "0x172fcD41E0913e95784454622d1c3724f546f849"
185        );
186        assert_eq!(
187            event.sender.to_string().to_lowercase(),
188            "0x7eded5ce04fd9bb6d125a0a470cc3ffcd972e182"
189        );
190        assert_eq!(
191            event.receiver.to_string().to_lowercase(),
192            "0x7eded5ce04fd9bb6d125a0a470cc3ffcd972e182"
193        );
194        assert_eq!(
195            event.amount0,
196            I256::try_from(2291588381489685660_i128).unwrap()
197        );
198        let expected_amount1 = I256::from_raw(
199            U256::from_str_radix(
200                "fffffffffffffffffffffffffffffffffffffffffffffffffff22743d8dee163",
201                16,
202            )
203            .unwrap(),
204        );
205        assert_eq!(event.amount1, expected_amount1);
206        let expected_sqrt_price = U160::from_str_radix("a8edeae49c411da42257f71", 16).unwrap();
207        assert_eq!(event.sqrt_price_x96, expected_sqrt_price);
208        let expected_liquidity = u128::from_str_radix("310fdcabce7b0096dfc84", 16).unwrap();
209        assert_eq!(event.liquidity, expected_liquidity);
210        assert_eq!(event.tick, -63769);
211        assert_eq!(event.block_number, 105495649);
212    }
213
214    #[rstest]
215    fn test_parse_swap_event_rpc(rpc_log: RpcLog) {
216        let dex = Arc::clone(&bsc::PANCAKESWAP_V3.dex);
217        let event = parse_swap_event_rpc(dex, &rpc_log).unwrap();
218
219        let expected =
220            B256::from_str("0x7c92e97f57ff8f490095730746b0b90a7c9e035bcf94c800f50b56fb18986e97")
221                .unwrap();
222        assert_eq!(event.block_hash, Some(expected));
223
224        assert_eq!(
225            event.pool_identifier.to_string(),
226            "0x172fcD41E0913e95784454622d1c3724f546f849"
227        );
228        assert_eq!(
229            event.amount0,
230            I256::try_from(2291588381489685660_i128).unwrap()
231        );
232        let expected_amount1 = I256::from_raw(
233            U256::from_str_radix(
234                "fffffffffffffffffffffffffffffffffffffffffffffffffff22743d8dee163",
235                16,
236            )
237            .unwrap(),
238        );
239        assert_eq!(event.amount1, expected_amount1);
240        assert_eq!(event.tick, -63769);
241        assert_eq!(event.block_number, 105495649);
242    }
243
244    #[rstest]
245    fn test_hypersync_rpc_match(hypersync_log: HypersyncLog, rpc_log: RpcLog) {
246        let dex = Arc::clone(&bsc::PANCAKESWAP_V3.dex);
247        let event_hypersync = parse_swap_event_hypersync(Arc::clone(&dex), &hypersync_log).unwrap();
248        let event_rpc = parse_swap_event_rpc(dex, &rpc_log).unwrap();
249
250        assert_eq!(event_hypersync.pool_identifier, event_rpc.pool_identifier);
251        assert_eq!(event_hypersync.sender, event_rpc.sender);
252        assert_eq!(event_hypersync.receiver, event_rpc.receiver);
253        assert_eq!(event_hypersync.amount0, event_rpc.amount0);
254        assert_eq!(event_hypersync.amount1, event_rpc.amount1);
255        assert_eq!(event_hypersync.sqrt_price_x96, event_rpc.sqrt_price_x96);
256        assert_eq!(event_hypersync.liquidity, event_rpc.liquidity);
257        assert_eq!(event_hypersync.tick, event_rpc.tick);
258        assert_eq!(event_hypersync.block_number, event_rpc.block_number);
259        assert_eq!(event_hypersync.transaction_hash, event_rpc.transaction_hash);
260    }
261
262    #[rstest]
263    fn test_rejects_uniswap_v3_length_data() {
264        // Truncate the data to the Uniswap V3 5-word layout: PancakeSwap V3 requires the two
265        // appended protocolFees words, so the shorter payload must be rejected.
266        let mut value: serde_json::Value = serde_json::from_str(HYPERSYNC_SWAP_LOG).unwrap();
267        let data = value["data"].as_str().unwrap();
268        // 0x + first 5 of the 7 32-byte words.
269        let truncated = data[..2 + 5 * 64].to_string();
270        value["data"] = serde_json::Value::String(truncated);
271        let log: HypersyncLog = serde_json::from_value(value).unwrap();
272
273        let dex = Arc::clone(&bsc::PANCAKESWAP_V3.dex);
274        let err = parse_swap_event_hypersync(dex, &log).unwrap_err();
275        assert!(err.to_string().contains("too short"));
276    }
277
278    #[rstest]
279    fn test_rejects_uniswap_v3_swap_topic() {
280        // The Uniswap V3 Swap topic0 must be rejected: PancakeSwap V3 hashes to its own
281        // topic even though the leading data fields overlap.
282        let uniswap_v3_topic = "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67";
283        let log_json = HYPERSYNC_SWAP_LOG.replace(SWAP_EVENT_SIGNATURE_HASH, uniswap_v3_topic);
284        let log: HypersyncLog = serde_json::from_str(&log_json).unwrap();
285
286        let dex = Arc::clone(&bsc::PANCAKESWAP_V3.dex);
287        let result = parse_swap_event_hypersync(dex, &log);
288        assert!(result.is_err());
289    }
290}