Skip to main content

nautilus_blockchain/exchanges/parsing/uniswap_v3/
fee_protocol_collect.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_collect::FeeProtocolCollectEvent,
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 FEE_PROTOCOL_COLLECT_EVENT_SIGNATURE_HASH: &str =
34    "596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151";
35
36// Define sol macro for parsing CollectProtocol event data.
37// sender and recipient are indexed (in topics); amount0 and amount1 are non-indexed (in data):
38// amount0 (uint128), amount1 (uint128)
39sol! {
40    struct FeeProtocolCollectEventData {
41        uint128 amount0;
42        uint128 amount1;
43    }
44}
45
46/// Parses a `CollectProtocol` event from a Uniswap V3 HyperSync log.
47///
48/// # Errors
49///
50/// Returns an error if the log parsing fails or if the event data is invalid.
51///
52/// # Panics
53///
54/// Panics if the contract address is not set in the log.
55pub fn parse_fee_protocol_collect_event_hypersync(
56    dex: SharedDex,
57    log: &HypersyncLog,
58) -> anyhow::Result<FeeProtocolCollectEvent> {
59    validate_event_signature_hash(
60        "CollectProtocol",
61        FEE_PROTOCOL_COLLECT_EVENT_SIGNATURE_HASH,
62        log,
63    )?;
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        // Validate the data contains 2 parameters of 32 bytes each
72        if data_bytes.len() < 2 * 32 {
73            anyhow::bail!("CollectProtocol event data is too short");
74        }
75
76        let decoded = match <FeeProtocolCollectEventData as SolType>::abi_decode(data_bytes) {
77            Ok(decoded) => decoded,
78            Err(e) => anyhow::bail!("Failed to decode CollectProtocol event data: {e}"),
79        };
80
81        let pool_address = Address::from_slice(
82            log.address
83                .clone()
84                .expect("Contract address should be set in logs")
85                .as_ref(),
86        );
87        let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
88
89        Ok(FeeProtocolCollectEvent::new(
90            dex,
91            pool_identifier,
92            extract_block_number(log)?,
93            extract_block_hash(log),
94            extract_transaction_hash(log)?,
95            extract_transaction_index(log)?,
96            extract_log_index(log)?,
97            sender,
98            recipient,
99            decoded.amount0,
100            decoded.amount1,
101        ))
102    } else {
103        anyhow::bail!("Missing data in CollectProtocol event log");
104    }
105}
106
107/// Parses a `CollectProtocol` 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_fee_protocol_collect_event_rpc(
113    dex: SharedDex,
114    log: &RpcLog,
115) -> anyhow::Result<FeeProtocolCollectEvent> {
116    rpc_log::validate_event_signature(
117        log,
118        FEE_PROTOCOL_COLLECT_EVENT_SIGNATURE_HASH,
119        "CollectProtocol",
120    )?;
121
122    let sender = rpc_log::extract_address_from_topic(log, 1, "sender")?;
123    let recipient = rpc_log::extract_address_from_topic(log, 2, "recipient")?;
124
125    let data_bytes = rpc_log::extract_data_bytes(log)?;
126
127    // Validate the data contains 2 parameters of 32 bytes each
128    if data_bytes.len() < 2 * 32 {
129        anyhow::bail!("CollectProtocol event data is too short");
130    }
131
132    let decoded = match <FeeProtocolCollectEventData as SolType>::abi_decode(&data_bytes) {
133        Ok(decoded) => decoded,
134        Err(e) => anyhow::bail!("Failed to decode CollectProtocol event data: {e}"),
135    };
136
137    let pool_address = rpc_log::extract_address(log)?;
138    let pool_identifier = PoolIdentifier::Address(Ustr::from(&pool_address.to_string()));
139    Ok(FeeProtocolCollectEvent::new(
140        dex,
141        pool_identifier,
142        rpc_log::extract_block_number(log)?,
143        rpc_log::extract_block_hash(log)?,
144        rpc_log::extract_transaction_hash(log)?,
145        rpc_log::extract_transaction_index(log)?,
146        rpc_log::extract_log_index(log)?,
147        sender,
148        recipient,
149        decoded.amount0,
150        decoded.amount1,
151    ))
152}
153
154#[cfg(test)]
155mod tests {
156    use std::{str::FromStr, sync::Arc};
157
158    use alloy::primitives::B256;
159    use rstest::*;
160    use serde_json::json;
161
162    use super::*;
163    use crate::exchanges::arbitrum;
164
165    // CollectProtocol log at block 0x175a6484 (391799940), pool
166    // 0xd13040d4fe917EE704158CfCB3338dCd2838B245.
167    // sender:    0xc36442b4a4522e871399cd717abdd847ab11fe88
168    // recipient: 0xa61da382c18d9d5beb905ea192bae25e4c15d512
169    // Asymmetric amounts (amount0 != amount1) catch a token0/token1 column swap.
170    const EXPECTED_AMOUNT0: u128 = 0x1234_5678_90ab_cdef;
171    const EXPECTED_AMOUNT1: u128 = 0x0fed_cba9_8765_4321;
172    const DATA: &str = "0x0000000000000000000000000000000000000000000000001234567890abcdef0000000000000000000000000000000000000000000000000fedcba987654321";
173
174    #[fixture]
175    fn hypersync_log() -> HypersyncLog {
176        let log_json = json!({
177            "removed": null,
178            "log_index": "0x11",
179            "transaction_index": "0x5",
180            "transaction_hash": "0x0c70f6d6bcf8508ba620b9d1250c95ad67108e35707c5d7456349ea207051bae",
181            "block_hash": null,
182            "block_number": "0x175a6484",
183            "address": "0xd13040d4fe917EE704158CfCB3338dCd2838B245",
184            "data": DATA,
185            "topics": [
186                "0x596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151",
187                "0x000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88",
188                "0x000000000000000000000000a61da382c18d9d5beb905ea192bae25e4c15d512"
189            ]
190        });
191        serde_json::from_value(log_json).expect("Failed to deserialize HyperSync log")
192    }
193
194    #[fixture]
195    fn rpc_log() -> RpcLog {
196        let log_json = json!({
197            "removed": false,
198            "logIndex": "0x11",
199            "transactionIndex": "0x5",
200            "transactionHash": "0x0c70f6d6bcf8508ba620b9d1250c95ad67108e35707c5d7456349ea207051bae",
201            "blockHash": "0xe925eaa1f5178ceedfa24043a974edb928ddab7195600b6b99ff5403fbf13c8b",
202            "blockNumber": "0x175a6484",
203            "address": "0xd13040d4fe917EE704158CfCB3338dCd2838B245",
204            "data": DATA,
205            "topics": [
206                "0x596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151",
207                "0x000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88",
208                "0x000000000000000000000000a61da382c18d9d5beb905ea192bae25e4c15d512"
209            ]
210        });
211        serde_json::from_value(log_json).expect("Failed to deserialize RPC log")
212    }
213
214    #[rstest]
215    fn test_parse_fee_protocol_collect_event_hypersync(hypersync_log: HypersyncLog) {
216        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
217        let event = parse_fee_protocol_collect_event_hypersync(dex, &hypersync_log).unwrap();
218
219        assert_eq!(event.block_hash, None);
220
221        assert_eq!(
222            event.pool_identifier.to_string(),
223            "0xd13040d4fe917EE704158CfCB3338dCd2838B245"
224        );
225        assert_eq!(
226            event.sender.to_string().to_lowercase(),
227            "0xc36442b4a4522e871399cd717abdd847ab11fe88"
228        );
229        assert_eq!(
230            event.recipient.to_string().to_lowercase(),
231            "0xa61da382c18d9d5beb905ea192bae25e4c15d512"
232        );
233        assert_eq!(event.amount0, EXPECTED_AMOUNT0);
234        assert_eq!(event.amount1, EXPECTED_AMOUNT1);
235        assert_eq!(event.block_number, 391_799_940);
236        assert_eq!(event.transaction_index, 5);
237        assert_eq!(event.log_index, 17);
238    }
239
240    #[rstest]
241    fn test_parse_fee_protocol_collect_event_rpc(rpc_log: RpcLog) {
242        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
243        let event = parse_fee_protocol_collect_event_rpc(dex, &rpc_log).unwrap();
244
245        let expected =
246            B256::from_str("0xe925eaa1f5178ceedfa24043a974edb928ddab7195600b6b99ff5403fbf13c8b")
247                .unwrap();
248        assert_eq!(event.block_hash, Some(expected));
249
250        assert_eq!(
251            event.pool_identifier.to_string(),
252            "0xd13040d4fe917EE704158CfCB3338dCd2838B245"
253        );
254        assert_eq!(
255            event.sender.to_string().to_lowercase(),
256            "0xc36442b4a4522e871399cd717abdd847ab11fe88"
257        );
258        assert_eq!(
259            event.recipient.to_string().to_lowercase(),
260            "0xa61da382c18d9d5beb905ea192bae25e4c15d512"
261        );
262        assert_eq!(event.amount0, EXPECTED_AMOUNT0);
263        assert_eq!(event.amount1, EXPECTED_AMOUNT1);
264        assert_eq!(event.block_number, 391_799_940);
265    }
266
267    #[rstest]
268    fn test_hypersync_rpc_match(hypersync_log: HypersyncLog, rpc_log: RpcLog) {
269        let dex = Arc::clone(&arbitrum::UNISWAP_V3.dex);
270        let event_hypersync =
271            parse_fee_protocol_collect_event_hypersync(Arc::clone(&dex), &hypersync_log).unwrap();
272        let event_rpc = parse_fee_protocol_collect_event_rpc(dex, &rpc_log).unwrap();
273
274        assert_eq!(event_hypersync.pool_identifier, event_rpc.pool_identifier);
275        assert_eq!(event_hypersync.sender, event_rpc.sender);
276        assert_eq!(event_hypersync.recipient, event_rpc.recipient);
277        assert_eq!(event_hypersync.amount0, event_rpc.amount0);
278        assert_eq!(event_hypersync.amount1, event_rpc.amount1);
279        assert_eq!(event_hypersync.block_number, event_rpc.block_number);
280        assert_eq!(event_hypersync.transaction_hash, event_rpc.transaction_hash);
281        assert_eq!(event_hypersync.log_index, event_rpc.log_index);
282    }
283}