Skip to main content

nautilus_blockchain/exchanges/parsing/pancakeswap_v3/
fee_protocol_update.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::fee_protocol_update::FeeProtocolUpdateEvent,
22    hypersync::{
23        HypersyncLog,
24        log::{
25            extract_block_hash, extract_block_number, extract_log_index, extract_transaction_hash,
26            extract_transaction_index, validate_event_signature_hash,
27        },
28    },
29    rpc::log as rpc_log,
30};
31
32const FEE_PROTOCOL_UPDATE_EVENT_SIGNATURE_HASH: &str =
33    "b3159fed3ddfba67bae294599eafe2d0ec98c08bb38e0e5fb87d33154b6e05aa";
34
35sol! {
36    struct SetFeeProtocolEventData {
37        uint32 fee_protocol0_old;
38        uint32 fee_protocol1_old;
39        uint32 fee_protocol0_new;
40        uint32 fee_protocol1_new;
41    }
42}
43
44/// Parses a PancakeSwap V3 `SetFeeProtocol` event from a HyperSync log.
45///
46/// # Errors
47///
48/// Returns an error if the log parsing fails or if the event data is invalid.
49///
50/// # Panics
51///
52/// Panics if the contract address is not set in the log.
53pub fn parse_fee_protocol_update_event_hypersync(
54    dex: SharedDex,
55    log: &HypersyncLog,
56) -> anyhow::Result<FeeProtocolUpdateEvent> {
57    validate_event_signature_hash(
58        "SetFeeProtocolEvent",
59        FEE_PROTOCOL_UPDATE_EVENT_SIGNATURE_HASH,
60        log,
61    )?;
62
63    if let Some(data) = &log.data {
64        let data_bytes = data.as_ref();
65
66        if data_bytes.len() < 4 * 32 {
67            anyhow::bail!("SetFeeProtocol event data is too short");
68        }
69
70        let decoded = match <SetFeeProtocolEventData as SolType>::abi_decode(data_bytes) {
71            Ok(decoded) => decoded,
72            Err(e) => anyhow::bail!("Failed to decode SetFeeProtocol event data: {e}"),
73        };
74
75        let pool_address = Address::from_slice(
76            log.address
77                .clone()
78                .expect("Contract address should be set in logs")
79                .as_ref(),
80        );
81        let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
82
83        Ok(FeeProtocolUpdateEvent::new(
84            dex,
85            pool_identifier,
86            extract_block_number(log)?,
87            extract_block_hash(log),
88            extract_transaction_hash(log)?,
89            extract_transaction_index(log)?,
90            extract_log_index(log)?,
91            decoded.fee_protocol0_new,
92            decoded.fee_protocol1_new,
93        ))
94    } else {
95        anyhow::bail!("Missing data in SetFeeProtocol event log");
96    }
97}
98
99/// Parses a PancakeSwap V3 `SetFeeProtocol` event from an RPC log.
100///
101/// # Errors
102///
103/// Returns an error if the log parsing fails or if the event data is invalid.
104pub fn parse_fee_protocol_update_event_rpc(
105    dex: SharedDex,
106    log: &RpcLog,
107) -> anyhow::Result<FeeProtocolUpdateEvent> {
108    rpc_log::validate_event_signature(
109        log,
110        FEE_PROTOCOL_UPDATE_EVENT_SIGNATURE_HASH,
111        "SetFeeProtocol",
112    )?;
113
114    let data_bytes = rpc_log::extract_data_bytes(log)?;
115
116    if data_bytes.len() < 4 * 32 {
117        anyhow::bail!("SetFeeProtocol event data is too short");
118    }
119
120    let decoded = match <SetFeeProtocolEventData as SolType>::abi_decode(&data_bytes) {
121        Ok(decoded) => decoded,
122        Err(e) => anyhow::bail!("Failed to decode SetFeeProtocol event data: {e}"),
123    };
124
125    let pool_address = rpc_log::extract_address(log)?;
126    let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
127    Ok(FeeProtocolUpdateEvent::new(
128        dex,
129        pool_identifier,
130        rpc_log::extract_block_number(log)?,
131        rpc_log::extract_block_hash(log)?,
132        rpc_log::extract_transaction_hash(log)?,
133        rpc_log::extract_transaction_index(log)?,
134        rpc_log::extract_log_index(log)?,
135        decoded.fee_protocol0_new,
136        decoded.fee_protocol1_new,
137    ))
138}
139
140#[cfg(test)]
141mod tests {
142    use std::{str::FromStr, sync::Arc};
143
144    use alloy::primitives::B256;
145    use rstest::*;
146
147    use super::*;
148    use crate::exchanges::bsc;
149
150    const HYPERSYNC_LOG: &str =
151        include_str!("../../../../test_data/pancakeswap_v3_set_fee_protocol_hypersync.json");
152    const RPC_LOG: &str =
153        include_str!("../../../../test_data/pancakeswap_v3_set_fee_protocol_rpc.json");
154
155    #[fixture]
156    fn hypersync_log() -> HypersyncLog {
157        serde_json::from_str(HYPERSYNC_LOG).expect("Failed to deserialize HyperSync log")
158    }
159
160    #[fixture]
161    fn rpc_log() -> RpcLog {
162        serde_json::from_str(RPC_LOG).expect("Failed to deserialize RPC log")
163    }
164
165    #[rstest]
166    fn test_parse_fee_protocol_update_event_hypersync(hypersync_log: HypersyncLog) {
167        let dex = Arc::clone(&bsc::PANCAKESWAP_V3.dex);
168        let event = parse_fee_protocol_update_event_hypersync(dex, &hypersync_log).unwrap();
169
170        assert_eq!(event.block_hash, None);
171
172        assert_eq!(
173            event.pool_identifier.to_string(),
174            "0x172fcD41E0913e95784454622d1c3724f546f849"
175        );
176        assert_eq!(event.fee_protocol0_new, 1_000);
177        assert_eq!(event.fee_protocol1_new, 4_000);
178        assert_eq!(event.block_number, 105_475_426);
179        assert_eq!(event.transaction_index, 5);
180        assert_eq!(event.log_index, 17);
181    }
182
183    #[rstest]
184    fn test_parse_fee_protocol_update_event_rpc(rpc_log: RpcLog) {
185        let dex = Arc::clone(&bsc::PANCAKESWAP_V3.dex);
186        let event = parse_fee_protocol_update_event_rpc(dex, &rpc_log).unwrap();
187
188        let expected =
189            B256::from_str("0xe925eaa1f5178ceedfa24043a974edb928ddab7195600b6b99ff5403fbf13c8b")
190                .unwrap();
191        assert_eq!(event.block_hash, Some(expected));
192
193        assert_eq!(
194            event.pool_identifier.to_string(),
195            "0x172fcD41E0913e95784454622d1c3724f546f849"
196        );
197        assert_eq!(event.fee_protocol0_new, 1_000);
198        assert_eq!(event.fee_protocol1_new, 4_000);
199        assert_eq!(event.block_number, 105_475_426);
200    }
201
202    #[rstest]
203    fn test_hypersync_rpc_match(hypersync_log: HypersyncLog, rpc_log: RpcLog) {
204        let dex = Arc::clone(&bsc::PANCAKESWAP_V3.dex);
205        let event_hypersync =
206            parse_fee_protocol_update_event_hypersync(Arc::clone(&dex), &hypersync_log).unwrap();
207        let event_rpc = parse_fee_protocol_update_event_rpc(dex, &rpc_log).unwrap();
208
209        assert_eq!(event_hypersync.pool_identifier, event_rpc.pool_identifier);
210        assert_eq!(
211            event_hypersync.fee_protocol0_new,
212            event_rpc.fee_protocol0_new
213        );
214        assert_eq!(
215            event_hypersync.fee_protocol1_new,
216            event_rpc.fee_protocol1_new
217        );
218        assert_eq!(event_hypersync.block_number, event_rpc.block_number);
219        assert_eq!(event_hypersync.transaction_hash, event_rpc.transaction_hash);
220        assert_eq!(
221            event_hypersync.transaction_index,
222            event_rpc.transaction_index
223        );
224        assert_eq!(event_hypersync.log_index, event_rpc.log_index);
225    }
226}