Skip to main content

nautilus_blockchain/contracts/
uniswap_v3_pool.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 std::{collections::HashMap, sync::Arc};
17
18use alloy::{
19    primitives::{Address, U256, keccak256},
20    sol,
21    sol_types::{SolCall, private::primitives::aliases::I24},
22};
23use nautilus_core::{UnixNanos, hex};
24use nautilus_model::{
25    defi::{
26        data::block::BlockPosition,
27        pool_analysis::{
28            position::PoolPosition,
29            snapshot::{PoolAnalytics, PoolSnapshot, PoolState},
30        },
31        tick_map::tick::PoolTick,
32    },
33    identifiers::InstrumentId,
34};
35use thiserror::Error;
36
37use super::base::{BaseContract, ContractCall, Multicall3};
38use crate::rpc::{error::BlockchainRpcClientError, http::BlockchainHttpRpcClient};
39
40sol! {
41    contract UniswapV3Pool {
42        /// Packed struct containing core pool state
43        struct Slot0Data {
44            uint160 sqrtPriceX96;
45            int24 tick;
46            uint16 observationIndex;
47            uint16 observationCardinality;
48            uint16 observationCardinalityNext;
49            uint32 feeProtocol;
50            bool unlocked;
51        }
52
53        /// Tick information
54        struct TickInfo {
55            uint128 liquidityGross;
56            int128 liquidityNet;
57            uint256 feeGrowthOutside0X128;
58            uint256 feeGrowthOutside1X128;
59            int56 tickCumulativeOutside;
60            uint160 secondsPerLiquidityOutsideX128;
61            uint32 secondsOutside;
62            bool initialized;
63        }
64
65        /// Position information
66        struct PositionInfo {
67            uint128 liquidity;
68            uint256 feeGrowthInside0LastX128;
69            uint256 feeGrowthInside1LastX128;
70            uint128 tokensOwed0;
71            uint128 tokensOwed1;
72        }
73
74        // Core state getters
75        function slot0() external view returns (Slot0Data memory);
76        function liquidity() external view returns (uint128);
77        function feeGrowthGlobal0X128() external view returns (uint256);
78        function feeGrowthGlobal1X128() external view returns (uint256);
79        function protocolFees() external view returns (uint128 token0, uint128 token1);
80
81        // Tick and position getters
82        function ticks(int24 tick) external view returns (TickInfo memory);
83        function positions(bytes32 key) external view returns (PositionInfo memory);
84    }
85}
86
87const PANCAKESWAP_V3_PROTOCOL_FEE_LANE_SIZE: u32 = 65_536;
88
89/// Protocol-fee encoding used by the pool's `slot0.feeProtocol` field.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum FeeProtocolEncoding {
92    /// Uniswap V3 packs two 4-bit denominators into one byte.
93    UniswapV3Packed,
94    /// PancakeSwap V3 packs two 16-bit basis-point shares into one `uint32`.
95    PancakeSwapV3BasisPoints,
96}
97
98/// Represents errors that can occur when interacting with UniswapV3Pool contract.
99#[derive(Debug, Error)]
100pub enum UniswapV3PoolError {
101    #[error("RPC error: {0}")]
102    RpcError(#[from] BlockchainRpcClientError),
103    #[error("Failed to decode {field} for pool {pool}: {reason} (raw data: {raw_data})")]
104    DecodingError {
105        field: String,
106        pool: Address,
107        reason: String,
108        raw_data: String,
109    },
110    #[error("Call failed for {field} at pool {pool}: {reason}")]
111    CallFailed {
112        field: String,
113        pool: Address,
114        reason: String,
115    },
116    #[error("Tick {tick} is not initialized in pool {pool}")]
117    TickNotInitialized { tick: i32, pool: Address },
118}
119
120/// Interface for interacting with UniswapV3Pool contracts on a blockchain.
121///
122/// This struct provides methods to query pool state including slot0, liquidity,
123/// fee growth, tick data, and position data. Supports both single calls and
124/// batch multicalls for efficiency.
125#[derive(Debug)]
126pub struct UniswapV3PoolContract {
127    /// The base contract providing common RPC execution functionality.
128    base: BaseContract,
129}
130
131impl UniswapV3PoolContract {
132    /// Creates a new UniswapV3Pool contract interface with the specified RPC client.
133    #[must_use]
134    pub fn new(client: Arc<BlockchainHttpRpcClient>, multicall_calls_per_rpc_request: u32) -> Self {
135        Self {
136            base: BaseContract::new_with_multicall_limit(client, multicall_calls_per_rpc_request),
137        }
138    }
139
140    /// Gets all global state in a single multicall.
141    ///
142    /// # Errors
143    ///
144    /// Returns an error if the multicall fails or any decoding fails.
145    pub async fn get_global_state(
146        &self,
147        pool_address: &Address,
148        block: Option<u64>,
149        fee_protocol_encoding: FeeProtocolEncoding,
150    ) -> Result<PoolState, UniswapV3PoolError> {
151        let calls = vec![
152            ContractCall {
153                target: *pool_address,
154                allow_failure: false,
155                call_data: UniswapV3Pool::slot0Call {}.abi_encode(),
156            },
157            ContractCall {
158                target: *pool_address,
159                allow_failure: false,
160                call_data: UniswapV3Pool::liquidityCall {}.abi_encode(),
161            },
162            ContractCall {
163                target: *pool_address,
164                allow_failure: false,
165                call_data: UniswapV3Pool::feeGrowthGlobal0X128Call {}.abi_encode(),
166            },
167            ContractCall {
168                target: *pool_address,
169                allow_failure: false,
170                call_data: UniswapV3Pool::feeGrowthGlobal1X128Call {}.abi_encode(),
171            },
172            ContractCall {
173                target: *pool_address,
174                allow_failure: false,
175                call_data: UniswapV3Pool::protocolFeesCall {}.abi_encode(),
176            },
177        ];
178
179        let results = self.base.execute_multicall(calls, block).await?;
180
181        if results.len() != 5 {
182            return Err(UniswapV3PoolError::CallFailed {
183                field: "global_state_multicall".to_string(),
184                pool: *pool_address,
185                reason: format!("Expected 5 results, received {}", results.len()),
186            });
187        }
188
189        // Decode slot0
190        let slot0 =
191            UniswapV3Pool::slot0Call::abi_decode_returns(&results[0].returnData).map_err(|e| {
192                UniswapV3PoolError::DecodingError {
193                    field: "slot0".to_string(),
194                    pool: *pool_address,
195                    reason: e.to_string(),
196                    raw_data: hex::encode(&results[0].returnData),
197                }
198            })?;
199
200        // Decode liquidity
201        let liquidity = UniswapV3Pool::liquidityCall::abi_decode_returns(&results[1].returnData)
202            .map_err(|e| UniswapV3PoolError::DecodingError {
203                field: "liquidity".to_string(),
204                pool: *pool_address,
205                reason: e.to_string(),
206                raw_data: hex::encode(&results[1].returnData),
207            })?;
208
209        // Decode feeGrowthGlobal0X128
210        let fee_growth_0 =
211            UniswapV3Pool::feeGrowthGlobal0X128Call::abi_decode_returns(&results[2].returnData)
212                .map_err(|e| UniswapV3PoolError::DecodingError {
213                    field: "feeGrowthGlobal0X128".to_string(),
214                    pool: *pool_address,
215                    reason: e.to_string(),
216                    raw_data: hex::encode(&results[2].returnData),
217                })?;
218
219        // Decode feeGrowthGlobal1X128
220        let fee_growth_1 =
221            UniswapV3Pool::feeGrowthGlobal1X128Call::abi_decode_returns(&results[3].returnData)
222                .map_err(|e| UniswapV3PoolError::DecodingError {
223                    field: "feeGrowthGlobal1X128".to_string(),
224                    pool: *pool_address,
225                    reason: e.to_string(),
226                    raw_data: hex::encode(&results[3].returnData),
227                })?;
228
229        // Decode protocolFees
230        let protocol_fees = UniswapV3Pool::protocolFeesCall::abi_decode_returns(
231            &results[4].returnData,
232        )
233        .map_err(|e| UniswapV3PoolError::DecodingError {
234            field: "protocolFees".to_string(),
235            pool: *pool_address,
236            reason: e.to_string(),
237            raw_data: hex::encode(&results[4].returnData),
238        })?;
239
240        let mut state = PoolState {
241            current_tick: slot0.tick.as_i32(),
242            price_sqrt_ratio_x96: slot0.sqrtPriceX96,
243            liquidity,
244            protocol_fees_token0: U256::from(protocol_fees.token0),
245            protocol_fees_token1: U256::from(protocol_fees.token1),
246            fee_protocol: 0,
247            fee_protocol0_basis_points: None,
248            fee_protocol1_basis_points: None,
249            fee_growth_global_0: fee_growth_0,
250            fee_growth_global_1: fee_growth_1,
251        };
252
253        match fee_protocol_encoding {
254            FeeProtocolEncoding::UniswapV3Packed => {
255                let fee_protocol = u8::try_from(slot0.feeProtocol).map_err(|e| {
256                    UniswapV3PoolError::DecodingError {
257                        field: "slot0.feeProtocol".to_string(),
258                        pool: *pool_address,
259                        reason: e.to_string(),
260                        raw_data: slot0.feeProtocol.to_string(),
261                    }
262                })?;
263                state.set_uniswap_v3_fee_protocol(fee_protocol);
264            }
265            FeeProtocolEncoding::PancakeSwapV3BasisPoints => {
266                let (fee_protocol0, fee_protocol1) =
267                    split_pancakeswap_v3_fee_protocol(slot0.feeProtocol);
268                state.set_protocol_fee_basis_points(fee_protocol0, fee_protocol1);
269            }
270        }
271
272        Ok(state)
273    }
274
275    /// Gets tick data for a specific tick.
276    ///
277    /// # Errors
278    ///
279    /// Returns an error if the RPC call fails or decoding fails.
280    pub async fn get_tick(
281        &self,
282        pool_address: &Address,
283        tick: i32,
284        block: Option<u64>,
285    ) -> Result<PoolTick, UniswapV3PoolError> {
286        let tick_i24 = I24::try_from(tick).map_err(|_| UniswapV3PoolError::CallFailed {
287            field: "tick".to_string(),
288            pool: *pool_address,
289            reason: format!("Tick {tick} out of range for int24"),
290        })?;
291
292        let call_data = UniswapV3Pool::ticksCall { tick: tick_i24 }.abi_encode();
293        let raw_response = self
294            .base
295            .execute_call(pool_address, &call_data, block)
296            .await?;
297
298        let tick_info =
299            UniswapV3Pool::ticksCall::abi_decode_returns(&raw_response).map_err(|e| {
300                UniswapV3PoolError::DecodingError {
301                    field: format!("ticks({tick})"),
302                    pool: *pool_address,
303                    reason: e.to_string(),
304                    raw_data: hex::encode(&raw_response),
305                }
306            })?;
307
308        Ok(PoolTick::new(
309            tick,
310            tick_info.liquidityGross,
311            tick_info.liquidityNet,
312            tick_info.feeGrowthOutside0X128,
313            tick_info.feeGrowthOutside1X128,
314            tick_info.initialized,
315            0, // last_updated_block - not available from RPC
316        ))
317    }
318
319    /// Gets tick data for multiple ticks in a single multicall.
320    ///
321    /// # Errors
322    ///
323    /// Returns an error if the multicall fails, a subcall fails, or any tick decoding fails.
324    pub async fn batch_get_ticks(
325        &self,
326        pool_address: &Address,
327        ticks: &[i32],
328        block: Option<u64>,
329    ) -> Result<HashMap<i32, PoolTick>, UniswapV3PoolError> {
330        let calls: Vec<ContractCall> = ticks
331            .iter()
332            .map(|&tick| {
333                let tick_i24 = I24::try_from(tick).map_err(|_| UniswapV3PoolError::CallFailed {
334                    field: format!("ticks({tick})"),
335                    pool: *pool_address,
336                    reason: "tick is out of range for int24".to_string(),
337                })?;
338                Ok(ContractCall {
339                    target: *pool_address,
340                    allow_failure: false,
341                    call_data: UniswapV3Pool::ticksCall { tick: tick_i24 }.abi_encode(),
342                })
343            })
344            .collect::<Result<_, UniswapV3PoolError>>()?;
345
346        let results = self.base.execute_multicall(calls, block).await?;
347        decode_tick_results(pool_address, ticks, &results)
348    }
349
350    /// Computes the position key used by Uniswap V3.
351    ///
352    /// The key is: keccak256(abi.encodePacked(owner, tickLower, tickUpper))
353    #[must_use]
354    pub fn compute_position_key(owner: &Address, tick_lower: i32, tick_upper: i32) -> [u8; 32] {
355        // Pack: address (20 bytes) + int24 (3 bytes) + int24 (3 bytes) = 26 bytes total
356        let mut packed = Vec::with_capacity(26);
357
358        // Add owner address (20 bytes)
359        packed.extend_from_slice(owner.as_slice());
360
361        // Add tick_lower as int24 (3 bytes, big-endian, sign-extended)
362        let tick_lower_bytes = tick_lower.to_be_bytes();
363        packed.extend_from_slice(&tick_lower_bytes[1..4]);
364
365        // Add tick_upper as int24 (3 bytes, big-endian, sign-extended)
366        let tick_upper_bytes = tick_upper.to_be_bytes();
367        packed.extend_from_slice(&tick_upper_bytes[1..4]);
368
369        keccak256(&packed).into()
370    }
371
372    /// Gets position data for multiple positions in a single multicall.
373    ///
374    /// # Errors
375    ///
376    /// Returns an error if the multicall fails, a subcall fails, or any position decoding fails.
377    pub async fn batch_get_positions(
378        &self,
379        pool_address: &Address,
380        positions: &[(Address, i32, i32)],
381        block: Option<u64>,
382    ) -> Result<Vec<PoolPosition>, UniswapV3PoolError> {
383        let calls: Vec<ContractCall> = positions
384            .iter()
385            .map(|(owner, tick_lower, tick_upper)| {
386                let position_key = Self::compute_position_key(owner, *tick_lower, *tick_upper);
387                ContractCall {
388                    target: *pool_address,
389                    allow_failure: false,
390                    call_data: UniswapV3Pool::positionsCall {
391                        key: position_key.into(),
392                    }
393                    .abi_encode(),
394                }
395            })
396            .collect();
397
398        let results = self.base.execute_multicall(calls, block).await?;
399        decode_position_results(pool_address, positions, &results)
400    }
401
402    /// Fetches a complete pool snapshot directly from on-chain state.
403    ///
404    /// Retrieves global state, tick data, and position data from the blockchain
405    /// and constructs a `PoolSnapshot` representing the current on-chain state.
406    /// This snapshot can be compared against profiler state for validation.
407    ///
408    /// # Errors
409    ///
410    /// Returns an error if any RPC calls fail or data cannot be decoded.
411    #[expect(clippy::too_many_arguments)]
412    pub async fn fetch_snapshot(
413        &self,
414        pool_address: &Address,
415        instrument_id: InstrumentId,
416        tick_values: &[i32],
417        position_keys: &[(Address, i32, i32)],
418        block_position: BlockPosition,
419        ts_event: UnixNanos,
420        ts_init: UnixNanos,
421        fee_protocol_encoding: FeeProtocolEncoding,
422    ) -> Result<PoolSnapshot, UniswapV3PoolError> {
423        // Fetch all data at the specified block
424        let block = Some(block_position.number);
425        let global_state = self
426            .get_global_state(pool_address, block, fee_protocol_encoding)
427            .await?;
428        let ticks_map = self
429            .batch_get_ticks(pool_address, tick_values, block)
430            .await?;
431        let positions = self
432            .batch_get_positions(pool_address, position_keys, block)
433            .await?;
434
435        Ok(PoolSnapshot::new(
436            instrument_id,
437            global_state,
438            positions,
439            ticks_map.into_values().collect(),
440            PoolAnalytics::default(),
441            block_position,
442            ts_event,
443            ts_init,
444        ))
445    }
446}
447
448fn decode_tick_results(
449    pool_address: &Address,
450    ticks: &[i32],
451    results: &[Multicall3::Result],
452) -> Result<HashMap<i32, PoolTick>, UniswapV3PoolError> {
453    if results.len() != ticks.len() {
454        return Err(UniswapV3PoolError::CallFailed {
455            field: "ticks".to_string(),
456            pool: *pool_address,
457            reason: format!(
458                "expected {} multicall results, received {}",
459                ticks.len(),
460                results.len()
461            ),
462        });
463    }
464
465    let mut tick_infos = HashMap::with_capacity(ticks.len());
466
467    for (&tick_value, result) in ticks.iter().zip(results) {
468        if !result.success {
469            return Err(UniswapV3PoolError::CallFailed {
470                field: format!("ticks({tick_value})"),
471                pool: *pool_address,
472                reason: "multicall subcall failed".to_string(),
473            });
474        }
475
476        let tick_info =
477            UniswapV3Pool::ticksCall::abi_decode_returns(&result.returnData).map_err(|e| {
478                UniswapV3PoolError::DecodingError {
479                    field: format!("ticks({tick_value})"),
480                    pool: *pool_address,
481                    reason: e.to_string(),
482                    raw_data: hex::encode(&result.returnData),
483                }
484            })?;
485        tick_infos.insert(
486            tick_value,
487            PoolTick::new(
488                tick_value,
489                tick_info.liquidityGross,
490                tick_info.liquidityNet,
491                tick_info.feeGrowthOutside0X128,
492                tick_info.feeGrowthOutside1X128,
493                tick_info.initialized,
494                0,
495            ),
496        );
497    }
498
499    Ok(tick_infos)
500}
501
502fn decode_position_results(
503    pool_address: &Address,
504    positions: &[(Address, i32, i32)],
505    results: &[Multicall3::Result],
506) -> Result<Vec<PoolPosition>, UniswapV3PoolError> {
507    if results.len() != positions.len() {
508        return Err(UniswapV3PoolError::CallFailed {
509            field: "positions".to_string(),
510            pool: *pool_address,
511            reason: format!(
512                "expected {} multicall results, received {}",
513                positions.len(),
514                results.len()
515            ),
516        });
517    }
518
519    positions
520        .iter()
521        .zip(results)
522        .map(|((owner, tick_lower, tick_upper), result)| {
523            let field = format!("positions({owner}, {tick_lower}, {tick_upper})");
524
525            if !result.success {
526                return Err(UniswapV3PoolError::CallFailed {
527                    field,
528                    pool: *pool_address,
529                    reason: "multicall subcall failed".to_string(),
530                });
531            }
532
533            let info = UniswapV3Pool::positionsCall::abi_decode_returns(&result.returnData)
534                .map_err(|e| UniswapV3PoolError::DecodingError {
535                    field,
536                    pool: *pool_address,
537                    reason: e.to_string(),
538                    raw_data: hex::encode(&result.returnData),
539                })?;
540            Ok(PoolPosition {
541                owner: *owner,
542                tick_lower: *tick_lower,
543                tick_upper: *tick_upper,
544                liquidity: info.liquidity,
545                fee_growth_inside_0_last: info.feeGrowthInside0LastX128,
546                fee_growth_inside_1_last: info.feeGrowthInside1LastX128,
547                tokens_owed_0: info.tokensOwed0,
548                tokens_owed_1: info.tokensOwed1,
549                total_amount0_deposited: U256::ZERO,
550                total_amount1_deposited: U256::ZERO,
551                total_amount0_collected: 0,
552                total_amount1_collected: 0,
553            })
554        })
555        .collect()
556}
557
558const fn split_pancakeswap_v3_fee_protocol(fee_protocol: u32) -> (u32, u32) {
559    (
560        fee_protocol % PANCAKESWAP_V3_PROTOCOL_FEE_LANE_SIZE,
561        fee_protocol >> 16,
562    )
563}
564
565#[cfg(test)]
566mod tests {
567    use alloy::primitives::Bytes;
568    use rstest::rstest;
569
570    use super::*;
571
572    #[rstest]
573    fn split_pancakeswap_v3_fee_protocol_returns_token_basis_points() {
574        let fee_protocol = 3_200 + (4_000 << 16);
575
576        assert_eq!(
577            split_pancakeswap_v3_fee_protocol(fee_protocol),
578            (3_200, 4_000)
579        );
580        assert_eq!(split_pancakeswap_v3_fee_protocol(0), (0, 0));
581    }
582
583    #[rstest]
584    fn decode_tick_results_rejects_failed_subcall() {
585        let results = vec![Multicall3::Result {
586            success: false,
587            returnData: Bytes::new(),
588        }];
589
590        let error = decode_tick_results(&Address::ZERO, &[10], &results).unwrap_err();
591
592        assert!(matches!(
593            error,
594            UniswapV3PoolError::CallFailed { field, .. } if field == "ticks(10)"
595        ));
596    }
597
598    #[rstest]
599    fn decode_tick_results_rejects_missing_result() {
600        let error = decode_tick_results(&Address::ZERO, &[10], &[]).unwrap_err();
601
602        assert!(matches!(
603            error,
604            UniswapV3PoolError::CallFailed { field, .. } if field == "ticks"
605        ));
606    }
607
608    #[rstest]
609    fn decode_position_results_rejects_undecodable_result() {
610        let results = vec![Multicall3::Result {
611            success: true,
612            returnData: Bytes::new(),
613        }];
614
615        let error = decode_position_results(&Address::ZERO, &[(Address::ZERO, -10, 10)], &results)
616            .unwrap_err();
617
618        assert!(matches!(error, UniswapV3PoolError::DecodingError { .. }));
619    }
620
621    #[rstest]
622    fn decode_position_results_rejects_failed_subcall() {
623        let results = vec![Multicall3::Result {
624            success: false,
625            returnData: Bytes::new(),
626        }];
627
628        let error = decode_position_results(&Address::ZERO, &[(Address::ZERO, -10, 10)], &results)
629            .unwrap_err();
630
631        assert!(matches!(
632            error,
633            UniswapV3PoolError::CallFailed { field, .. }
634                if field == "positions(0x0000000000000000000000000000000000000000, -10, 10)"
635        ));
636    }
637
638    #[rstest]
639    fn decode_position_results_rejects_missing_result() {
640        let error =
641            decode_position_results(&Address::ZERO, &[(Address::ZERO, -10, 10)], &[]).unwrap_err();
642
643        assert!(matches!(
644            error,
645            UniswapV3PoolError::CallFailed { field, .. } if field == "positions"
646        ));
647    }
648}